From 4d06e9b6942d6b7294c0f424f50e979f6c0b4eb7 Mon Sep 17 00:00:00 2001 From: Simon Li Date: Mon, 29 Mar 2021 20:54:19 +0100 Subject: [PATCH] noVNC-1.2.0 --- .../share/web/noVNC-1.2.0/.eslintrc | 2 + .../noVNC-1.2.0/.github/workflows/deploy.yml | 49 + .../noVNC-1.2.0/.github/workflows/lint.yml | 19 + .../noVNC-1.2.0/.github/workflows/test.yml | 30 + .../share/web/noVNC-1.2.0/.travis.yml | 58 - .../share/web/noVNC-1.2.0/LICENSE.txt | 2 +- .../share/web/noVNC-1.2.0/README.md | 68 +- jupyter_desktop/share/web/noVNC-1.2.0/VERSION | 1 - .../web/noVNC-1.2.0/app/error-handler.js | 8 + .../web/noVNC-1.2.0/app/images/mouse_left.svg | 92 - .../noVNC-1.2.0/app/images/mouse_middle.svg | 92 - .../web/noVNC-1.2.0/app/images/mouse_none.svg | 92 - .../noVNC-1.2.0/app/images/mouse_right.svg | 92 - .../web/noVNC-1.2.0/app/images/windows.svg | 70 +- .../share/web/noVNC-1.2.0/app/locale/README | 1 + .../share/web/noVNC-1.2.0/app/locale/ja.json | 73 + .../share/web/noVNC-1.2.0/app/locale/sv.json | 15 +- .../web/noVNC-1.2.0/app/locale/zh_CN.json | 34 +- .../share/web/noVNC-1.2.0/app/styles/base.css | 104 +- .../share/web/noVNC-1.2.0/app/ui.js | 280 +- .../share/web/noVNC-1.2.0/app/webutil.js | 16 +- .../share/web/noVNC-1.2.0/core/base64.js | 8 +- .../web/noVNC-1.2.0/core/decoders/copyrect.js | 4 +- .../web/noVNC-1.2.0/core/decoders/hextile.js | 22 +- .../web/noVNC-1.2.0/core/decoders/raw.js | 18 +- .../web/noVNC-1.2.0/core/decoders/rre.js | 4 +- .../web/noVNC-1.2.0/core/decoders/tight.js | 20 +- .../web/noVNC-1.2.0/core/decoders/tightpng.js | 6 +- .../share/web/noVNC-1.2.0/core/deflator.js | 85 + .../share/web/noVNC-1.2.0/core/display.js | 175 +- .../share/web/noVNC-1.2.0/core/encodings.js | 5 +- .../share/web/noVNC-1.2.0/core/inflator.js | 42 +- .../web/noVNC-1.2.0/core/input/domkeytable.js | 14 +- .../noVNC-1.2.0/core/input/gesturehandler.js | 567 + .../web/noVNC-1.2.0/core/input/keyboard.js | 40 +- .../share/web/noVNC-1.2.0/core/input/mouse.js | 276 - .../share/web/noVNC-1.2.0/core/input/util.js | 50 +- .../share/web/noVNC-1.2.0/core/rfb.js | 1510 +- .../web/noVNC-1.2.0/core/util/browser.js | 42 +- .../share/web/noVNC-1.2.0/core/util/cursor.js | 100 +- .../web/noVNC-1.2.0/core/util/element.js | 32 + .../share/web/noVNC-1.2.0/core/util/events.js | 91 +- .../web/noVNC-1.2.0/core/util/eventtarget.js | 2 +- .../share/web/noVNC-1.2.0/core/util/int.js | 15 + .../web/noVNC-1.2.0/core/util/logging.js | 16 +- .../web/noVNC-1.2.0/core/util/polyfill.js | 9 +- .../web/noVNC-1.2.0/core/util/strings.js | 26 +- .../share/web/noVNC-1.2.0/core/websock.js | 66 +- .../web/noVNC-1.2.0/docs/API-internal.md | 46 +- .../share/web/noVNC-1.2.0/docs/API.md | 28 +- .../share/web/noVNC-1.2.0/docs/EMBEDDING.md | 4 + .../share/web/noVNC-1.2.0/karma.conf.js | 86 +- .../share/web/noVNC-1.2.0/package.json | 62 +- .../share/web/noVNC-1.2.0/po/.eslintrc | 5 + .../share/web/noVNC-1.2.0/po/Makefile | 2 +- .../share/web/noVNC-1.2.0/po/ja.po | 303 + .../share/web/noVNC-1.2.0/po/noVNC.pot | 180 +- .../share/web/noVNC-1.2.0/po/po2js | 8 +- .../share/web/noVNC-1.2.0/po/sv.po | 208 +- .../share/web/noVNC-1.2.0/po/xgettext-html | 14 +- .../share/web/noVNC-1.2.0/po/zh_CN.po | 40 +- .../web/noVNC-1.2.0/snap/hooks/configure | 3 + .../web/noVNC-1.2.0/snap/local/svc_wrapper.sh | 29 + .../share/web/noVNC-1.2.0/snap/snapcraft.yaml | 36 + .../share/web/noVNC-1.2.0/tests/assertions.js | 28 +- .../web/noVNC-1.2.0/tests/fake.websocket.js | 32 +- .../web/noVNC-1.2.0/tests/playback-ui.js | 16 +- .../share/web/noVNC-1.2.0/tests/playback.js | 30 +- .../web/noVNC-1.2.0/tests/test.deflator.js | 82 + .../web/noVNC-1.2.0/tests/test.display.js | 138 +- .../noVNC-1.2.0/tests/test.gesturehandler.js | 1033 + .../web/noVNC-1.2.0/tests/test.helper.js | 37 +- .../share/web/noVNC-1.2.0/tests/test.int.js | 16 + .../web/noVNC-1.2.0/tests/test.keyboard.js | 218 +- .../noVNC-1.2.0/tests/test.localization.js | 4 +- .../share/web/noVNC-1.2.0/tests/test.mouse.js | 304 - .../share/web/noVNC-1.2.0/tests/test.rfb.js | 3071 +- .../share/web/noVNC-1.2.0/tests/test.util.js | 34 +- .../web/noVNC-1.2.0/tests/test.websock.js | 124 +- .../web/noVNC-1.2.0/tests/test.webutil.js | 4 +- .../web/noVNC-1.2.0/utils/genkeysymdef.js | 8 +- .../share/web/noVNC-1.2.0/utils/img2js.py | 40 - .../share/web/noVNC-1.2.0/utils/json2graph.py | 206 - .../share/web/noVNC-1.2.0/utils/launch.sh | 24 +- .../web/noVNC-1.2.0/utils/use_require.js | 267 +- .../noVNC-1.2.0/utils/use_require_helpers.js | 56 +- .../vendor/browser-es-module-loader/README.md | 4 +- .../dist/babel-worker.js | 152025 +++++++++++---- .../dist/browser-es-module-loader.js | 2561 +- .../dist/browser-es-module-loader.js.map | 2 +- .../browser-es-module-loader/genworker.js | 13 + .../browser-es-module-loader/rollup.config.js | 15 +- .../src/babel-worker.js | 18 +- .../src/browser-es-module-loader.js | 1 - .../vendor/pako/lib/zlib/deflate.js | 60 +- .../vendor/pako/lib/zlib/inflate.js | 34 +- .../share/web/noVNC-1.2.0/vnc.html | 106 +- .../share/web/noVNC-1.2.0/vnc_lite.html | 32 +- 98 files changed, 118119 insertions(+), 48021 deletions(-) create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/deploy.yml create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/lint.yml create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/test.yml delete mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/.travis.yml delete mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/VERSION delete mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_left.svg delete mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_middle.svg delete mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_none.svg delete mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_right.svg create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/app/locale/README create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/app/locale/ja.json create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/core/deflator.js create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/core/input/gesturehandler.js delete mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/core/input/mouse.js create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/core/util/element.js create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/core/util/int.js create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/po/.eslintrc create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/po/ja.po create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/snap/hooks/configure create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/snap/local/svc_wrapper.sh create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/snap/snapcraft.yaml create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/tests/test.deflator.js create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/tests/test.gesturehandler.js create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/tests/test.int.js delete mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/tests/test.mouse.js delete mode 100755 jupyter_desktop/share/web/noVNC-1.2.0/utils/img2js.py delete mode 100755 jupyter_desktop/share/web/noVNC-1.2.0/utils/json2graph.py create mode 100644 jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/genworker.js diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/.eslintrc b/jupyter_desktop/share/web/noVNC-1.2.0/.eslintrc index 900a7186..a53bb402 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/.eslintrc +++ b/jupyter_desktop/share/web/noVNC-1.2.0/.eslintrc @@ -25,6 +25,7 @@ "brace-style": ["error", "1tbs", { "allowSingleLine": true }], "indent": ["error", 4, { "SwitchCase": 1, + "FunctionDeclaration": { "parameters": "first" }, "CallExpression": { "arguments": "first" }, "ArrayExpression": "first", "ObjectExpression": "first", @@ -44,5 +45,6 @@ "named": "never", "asyncArrow": "always" }], "switch-colon-spacing": ["error"], + "camelcase": ["error", { allow: ["^XK_", "^XF86XK_"] }], } } diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/deploy.yml b/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/deploy.yml new file mode 100644 index 00000000..454ff8bd --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/deploy.yml @@ -0,0 +1,49 @@ +name: Publish + +on: + release: + types: [published] + +jobs: + npm: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + with: + # Needs to be explicitly specified for auth to work + registry-url: 'https://registry.npmjs.org' + - run: npm install + - run: npm publish --access public + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + if: ${{ !github.event.release.prerelease }} + - run: npm publish --access public --tag beta + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + if: ${{ github.event.release.prerelease }} + snap: + runs-on: ubuntu-latest + container: snapcore/snapcraft + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + - run: npm install + - run: ./utils/use_require.js --clean --as commonjs --with-app + - run: | + cp utils/launch.sh build/launch.sh + cp snap/local/svc_wrapper.sh build/svc_wrapper.sh + - run: | + VERSION=$(grep '"version"' package.json | cut -d '"' -f 4) + echo $VERSION + sed -i "s/@VERSION@/$VERSION/g" snap/snapcraft.yaml + - run: snapcraft + - run: | + mkdir .snapcraft + echo ${SNAPCRAFT_LOGIN} | base64 --decode --ignore-garbage > .snapcraft/snapcraft.cfg + env: + SNAPCRAFT_LOGIN: ${{secrets.SNAPCRAFT_LOGIN}} + - run: snapcraft push --release=stable *.snap + if: ${{ !github.event.release.prerelease }} + - run: snapcraft push --release=beta *.snap + if: ${{ github.event.release.prerelease }} diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/lint.yml b/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/lint.yml new file mode 100644 index 00000000..aaa36736 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/lint.yml @@ -0,0 +1,19 @@ +name: Lint + +on: [push, pull_request] + +jobs: + eslint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + - run: npm install + - run: npm run lint + html: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + - run: npm install + - run: git ls-tree --name-only -r HEAD | grep -E "[.](html|css)$" | xargs ./utils/validate diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/test.yml b/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/test.yml new file mode 100644 index 00000000..5b03504f --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/.github/workflows/test.yml @@ -0,0 +1,30 @@ +name: Test + +on: [push, pull_request] + +jobs: + test: + strategy: + matrix: + os: + - ubuntu-latest + - windows-latest + browser: + - ChromeHeadless + - FirefoxHeadless + include: + - os: macos-latest + browser: Safari + - os: windows-latest + browser: EdgeHeadless + - os: windows-latest + browser: IE + fail-fast: false + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + - run: npm install + - run: npm run test + env: + TEST_BROWSER_NAME: ${{ matrix.browser }} diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/.travis.yml b/jupyter_desktop/share/web/noVNC-1.2.0/.travis.yml deleted file mode 100644 index 78b521a8..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/.travis.yml +++ /dev/null @@ -1,58 +0,0 @@ -language: node_js -sudo: false -cache: - directories: - - node_modules -node_js: - - 6 -env: - matrix: - - TEST_BROWSER_NAME=chrome TEST_BROWSER_OS='Windows 10' -# FIXME Skip tests in Linux since Sauce Labs browser versions are ancient. -# - TEST_BROWSER_NAME=chrome TEST_BROWSER_OS='Linux' - - TEST_BROWSER_NAME=chrome TEST_BROWSER_OS='OS X 10.11' - - TEST_BROWSER_NAME=firefox TEST_BROWSER_OS='Windows 10' -# - TEST_BROWSER_NAME=firefox TEST_BROWSER_OS='Linux' - - TEST_BROWSER_NAME=firefox TEST_BROWSER_OS='OS X 10.11' - - TEST_BROWSER_NAME='internet explorer' TEST_BROWSER_OS='Windows 10' - - TEST_BROWSER_NAME='internet explorer' TEST_BROWSER_OS='Windows 7' - - TEST_BROWSER_NAME=microsoftedge TEST_BROWSER_OS='Windows 10' - - TEST_BROWSER_NAME=safari TEST_BROWSER_OS='OS X 10.13' -before_script: npm install -g karma-cli -addons: - sauce_connect: - username: "directxman12" - jwt: - secure: "d3ekMYslpn6R4f0ajtRMt9SUFmNGDiItHpqaXC5T4KI0KMEsxgvEOfJot5PiFFJWg1DSpJZH6oaW2UxGZ3duJLZrXIEd/JePY8a6NtT35BNgiDPgcp+eu2Bu3rhrSNg7/HEsD1ma+JeUTnv18Ai5oMFfCCQJx2J6osIxyl/ZVxA=" -stages: -- lint -- test -- name: deploy - if: tag is PRESENT -jobs: - include: - - stage: lint - env: - addons: - before_script: - script: npm run lint - - - env: - addons: - before_script: - script: git ls-tree --name-only -r HEAD | grep -E "[.](html|css)$" | xargs ./utils/validate - - stage: deploy - env: - addons: - script: skip - before_script: skip - deploy: - provider: npm - email: ossman@cendio.se - api_key: - secure: "Qq2Mi9xQawO2zlAigzshzMu2QMHvu1IaN9l0ZIivE99wHJj7eS5f4miJ9wB+/mWRRgb3E8uj9ZRV24+Oc36drlBTU9sz+lHhH0uFMfAIseceK64wZV9sLAZm472fmPp2xdUeTCCqPaRy7g1XBqiJ0LyZvEFLsRijqcLjPBF+b8w=" - on: - tags: true - repo: novnc/noVNC - - diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/LICENSE.txt b/jupyter_desktop/share/web/noVNC-1.2.0/LICENSE.txt index 20f3eb02..ed6b6575 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/LICENSE.txt +++ b/jupyter_desktop/share/web/noVNC-1.2.0/LICENSE.txt @@ -1,4 +1,4 @@ -noVNC is Copyright (C) 2018 The noVNC Authors +noVNC is Copyright (C) 2019 The noVNC Authors (./AUTHORS) The noVNC core library files are licensed under the MPL 2.0 (Mozilla diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/README.md b/jupyter_desktop/share/web/noVNC-1.2.0/README.md index 566b8e4f..b5b84c3c 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/README.md +++ b/jupyter_desktop/share/web/noVNC-1.2.0/README.md @@ -1,6 +1,7 @@ ## noVNC: HTML VNC Client Library and Application -[![Build Status](https://travis-ci.org/novnc/noVNC.svg?branch=master)](https://travis-ci.org/novnc/noVNC) +[![Test Status](https://github.com/novnc/noVNC/workflows/Test/badge.svg)](https://github.com/novnc/noVNC/actions?query=workflow%3ATest) +[![Lint Status](https://github.com/novnc/noVNC/workflows/Lint/badge.svg)](https://github.com/novnc/noVNC/actions?query=workflow%3ALint) ### Description @@ -24,6 +25,7 @@ for a more complete list with additional info and links. - [Browser Requirements](#browser-requirements) - [Server Requirements](#server-requirements) - [Quick Start](#quick-start) +- [Installation from Snap Package](#installation-from-snap-package) - [Integration and Deployment](#integration-and-deployment) - [Authors/Contributors](#authorscontributors) @@ -68,6 +70,7 @@ Please tweet [@noVNC](http://www.twitter.com/noVNC) if you do. * Local cursor rendering * Clipboard copy/paste * Translations +* Touch gestures for emulating common mouse actions * Licensed mainly under the [MPL 2.0](http://www.mozilla.org/MPL/2.0/), see [the license document](LICENSE.txt) for details @@ -88,7 +91,7 @@ noVNC uses many modern web technologies so a formal requirement list is not available. However these are the minimum versions we are currently aware of: -* Chrome 49, Firefox 44, Safari 10, Opera 36, IE 11, Edge 12 +* Chrome 49, Firefox 44, Safari 11, Opera 36, IE 11, Edge 12 ### Server Requirements @@ -115,6 +118,66 @@ proxy. script. Hit the Connect button, enter a password if the VNC server has one configured, and enjoy! +### Installation from Snap Package +Running the command below will install the latest release of noVNC from Snap: + +`sudo snap install novnc` + +#### Running noVNC + +You can run the Snap-package installed novnc directly with, for example: + +`novnc --listen 6081 --vnc localhost:5901 # /snap/bin/novnc if /snap/bin is not in your PATH` + +#### Running as a Service (Daemon) +The Snap package also has the capability to run a 'novnc' service which can be +configured to listen on multiple ports connecting to multiple VNC servers +(effectively a service runing multiple instances of novnc). +Instructions (with example values): + +List current services (out-of-box this will be blank): + +``` +sudo snap get novnc services +Key Value +services.n6080 {...} +services.n6081 {...} +``` + +Create a new service that listens on port 6082 and connects to the VNC server +running on port 5902 on localhost: + +`sudo snap set novnc services.n6082.listen=6082 services.n6082.vnc=localhost:5902` + +(Any services you define with 'snap set' will be automatically started) +Note that the name of the service, 'n6082' in this example, can be anything +as long as it doesn't start with a number or contain spaces/special characters. + +View the configuration of the service just created: + +``` +sudo snap get novnc services.n6082 +Key Value +services.n6082.listen 6082 +services.n6082.vnc localhost:5902 +``` + +Disable a service (note that because of a limitation in Snap it's currently not +possible to unset config variables, setting them to blank values is the way +to disable a service): + +`sudo snap set novnc services.n6082.listen='' services.n6082.vnc=''` + +(Any services you set to blank with 'snap set' like this will be automatically stopped) + +Verify that the service is disabled (blank values): + +``` +sudo snap get novnc services.n6082 +Key Value +services.n6082.listen +services.n6082.vnc +``` ### Integration and Deployment @@ -133,7 +196,6 @@ that list and you think you should be, feel free to send a PR to fix that. * Core team: * [Joel Martin](https://github.com/kanaka) * [Samuel Mannehed](https://github.com/samhed) (Cendio) - * [Peter Åstrand](https://github.com/astrand) (Cendio) * [Solly Ross](https://github.com/DirectXMan12) (Red Hat / OpenStack) * [Pierre Ossman](https://github.com/CendioOssman) (Cendio) diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/VERSION b/jupyter_desktop/share/web/noVNC-1.2.0/VERSION deleted file mode 100644 index 9084fa2f..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/VERSION +++ /dev/null @@ -1 +0,0 @@ -1.1.0 diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/error-handler.js b/jupyter_desktop/share/web/noVNC-1.2.0/app/error-handler.js index 8e294166..81a6cba8 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/error-handler.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/error-handler.js @@ -1,3 +1,11 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC Authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + // NB: this should *not* be included as a module until we have // native support in the browsers, so that our error handler // can catch script-loading errors. diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_left.svg b/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_left.svg deleted file mode 100644 index ce4cca41..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_left.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_middle.svg b/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_middle.svg deleted file mode 100644 index 6603425c..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_middle.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_none.svg b/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_none.svg deleted file mode 100644 index 3e0f838a..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_none.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_right.svg b/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_right.svg deleted file mode 100644 index f4bad767..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/mouse_right.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/windows.svg b/jupyter_desktop/share/web/noVNC-1.2.0/app/images/windows.svg index 270405c7..ad5eec36 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/images/windows.svg +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/images/windows.svg @@ -15,18 +15,18 @@ inkscape:export-xdpi="90" sodipodi:docname="windows.svg" inkscape:export-filename="/home/ossman/devel/noVNC/images/drag.png" - inkscape:version="0.92.3 (2405546, 2018-03-11)" + inkscape:version="0.92.4 (unknown)" x="0px" y="0px" - viewBox="-293 384 25 23" + viewBox="-293 384 25 25" xml:space="preserve" width="25" - height="23">image/svg+xml + inkscape:current-layer="svg2"> - - - - - - - - - \ No newline at end of file + + \ No newline at end of file diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/README b/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/README new file mode 100644 index 00000000..ca4f548b --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/README @@ -0,0 +1 @@ +DO NOT MODIFY THE FILES IN THIS FOLDER, THEY ARE AUTOMATICALLY GENERATED FROM THE PO-FILES. diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/ja.json b/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/ja.json new file mode 100644 index 00000000..e5fe3401 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/ja.json @@ -0,0 +1,73 @@ +{ + "Connecting...": "接続しています...", + "Disconnecting...": "切断しています...", + "Reconnecting...": "再接続しています...", + "Internal error": "内部エラー", + "Must set host": "ホストを設定する必要があります", + "Connected (encrypted) to ": "接続しました (暗号化済み): ", + "Connected (unencrypted) to ": "接続しました (暗号化されていません): ", + "Something went wrong, connection is closed": "何かが問題で、接続が閉じられました", + "Failed to connect to server": "サーバーへの接続に失敗しました", + "Disconnected": "切断しました", + "New connection has been rejected with reason: ": "新規接続は次の理由で拒否されました: ", + "New connection has been rejected": "新規接続は拒否されました", + "Password is required": "パスワードが必要です", + "noVNC encountered an error:": "noVNC でエラーが発生しました:", + "Hide/Show the control bar": "コントロールバーを隠す/表示する", + "Move/Drag Viewport": "ビューポートを移動/ドラッグ", + "viewport drag": "ビューポートをドラッグ", + "Active Mouse Button": "アクティブなマウスボタン", + "No mousebutton": "マウスボタンなし", + "Left mousebutton": "左マウスボタン", + "Middle mousebutton": "中マウスボタン", + "Right mousebutton": "右マウスボタン", + "Keyboard": "キーボード", + "Show Keyboard": "キーボードを表示", + "Extra keys": "追加キー", + "Show Extra Keys": "追加キーを表示", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Ctrl キーを切り替え", + "Alt": "Alt", + "Toggle Alt": "Alt キーを切り替え", + "Toggle Windows": "Windows キーを切り替え", + "Windows": "Windows", + "Send Tab": "Tab キーを送信", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "Escape キーを送信", + "Ctrl+Alt+Del": "Ctrl+Alt+Del", + "Send Ctrl-Alt-Del": "Ctrl-Alt-Del を送信", + "Shutdown/Reboot": "シャットダウン/再起動", + "Shutdown/Reboot...": "シャットダウン/再起動...", + "Power": "電源", + "Shutdown": "シャットダウン", + "Reboot": "再起動", + "Reset": "リセット", + "Clipboard": "クリップボード", + "Clear": "クリア", + "Fullscreen": "全画面表示", + "Settings": "設定", + "Shared Mode": "共有モード", + "View Only": "表示のみ", + "Clip to Window": "ウィンドウにクリップ", + "Scaling Mode:": "スケーリングモード:", + "None": "なし", + "Local Scaling": "ローカルスケーリング", + "Remote Resizing": "リモートでリサイズ", + "Advanced": "高度", + "Repeater ID:": "リピーター ID:", + "WebSocket": "WebSocket", + "Encrypt": "暗号化", + "Host:": "ホスト:", + "Port:": "ポート:", + "Path:": "パス:", + "Automatic Reconnect": "自動再接続", + "Reconnect Delay (ms):": "再接続する遅延 (ミリ秒):", + "Show Dot when No Cursor": "カーソルがないときにドットを表示", + "Logging:": "ロギング:", + "Disconnect": "切断", + "Connect": "接続", + "Password:": "パスワード:", + "Send Password": "パスワードを送信", + "Cancel": "キャンセル" +} \ No newline at end of file diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/sv.json b/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/sv.json index d49ea540..e46df45b 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/sv.json +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/sv.json @@ -11,16 +11,11 @@ "Disconnected": "Frånkopplad", "New connection has been rejected with reason: ": "Ny anslutning har blivit nekad med följande skäl: ", "New connection has been rejected": "Ny anslutning har blivit nekad", - "Password is required": "Lösenord krävs", + "Credentials are required": "Användaruppgifter krävs", "noVNC encountered an error:": "noVNC stötte på ett problem:", "Hide/Show the control bar": "Göm/Visa kontrollbaren", + "Drag": "Dra", "Move/Drag Viewport": "Flytta/Dra Vyn", - "viewport drag": "dra vy", - "Active Mouse Button": "Aktiv musknapp", - "No mousebutton": "Ingen musknapp", - "Left mousebutton": "Vänster musknapp", - "Middle mousebutton": "Mitten-musknapp", - "Right mousebutton": "Höger musknapp", "Keyboard": "Tangentbord", "Show Keyboard": "Visa Tangentbord", "Extra keys": "Extraknappar", @@ -55,6 +50,8 @@ "Local Scaling": "Lokal Skalning", "Remote Resizing": "Ändra Storlek", "Advanced": "Avancerat", + "Quality:": "Kvalitet:", + "Compression level:": "Kompressionsnivå:", "Repeater ID:": "Repeater-ID:", "WebSocket": "WebSocket", "Encrypt": "Kryptera", @@ -65,9 +62,11 @@ "Reconnect Delay (ms):": "Fördröjning (ms):", "Show Dot when No Cursor": "Visa prick när ingen muspekare finns", "Logging:": "Loggning:", + "Version:": "Version:", "Disconnect": "Koppla från", "Connect": "Anslut", + "Username:": "Användarnamn:", "Password:": "Lösenord:", - "Send Password": "Skicka lösenord", + "Send Credentials": "Skicka Användaruppgifter", "Cancel": "Avbryt" } \ No newline at end of file diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/zh_CN.json b/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/zh_CN.json index b6699562..f0aea9af 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/zh_CN.json +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/locale/zh_CN.json @@ -1,19 +1,19 @@ { - "Connecting...": "链接中...", - "Disconnecting...": "正在中断连接...", - "Reconnecting...": "重新链接中...", + "Connecting...": "连接中...", + "Disconnecting...": "正在断开连接...", + "Reconnecting...": "重新连接中...", "Internal error": "内部错误", "Must set host": "请提供主机名", - "Connected (encrypted) to ": "已加密链接到", - "Connected (unencrypted) to ": "未加密链接到", - "Something went wrong, connection is closed": "发生错误,链接已关闭", - "Failed to connect to server": "无法链接到服务器", - "Disconnected": "链接已中断", - "New connection has been rejected with reason: ": "链接被拒绝,原因:", - "New connection has been rejected": "链接被拒绝", + "Connected (encrypted) to ": "已连接到(加密)", + "Connected (unencrypted) to ": "已连接到(未加密)", + "Something went wrong, connection is closed": "发生错误,连接已关闭", + "Failed to connect to server": "无法连接到服务器", + "Disconnected": "已断开连接", + "New connection has been rejected with reason: ": "连接被拒绝,原因:", + "New connection has been rejected": "连接被拒绝", "Password is required": "请提供密码", "noVNC encountered an error:": "noVNC 遇到一个错误:", - "Hide/Show the control bar": "显示/隐藏控制列", + "Hide/Show the control bar": "显示/隐藏控制栏", "Move/Drag Viewport": "拖放显示范围", "viewport drag": "显示范围拖放", "Active Mouse Button": "启动鼠标按鍵", @@ -43,10 +43,10 @@ "Reset": "重置", "Clipboard": "剪贴板", "Clear": "清除", - "Fullscreen": "全屏幕", + "Fullscreen": "全屏", "Settings": "设置", "Shared Mode": "分享模式", - "View Only": "仅检视", + "View Only": "仅查看", "Clip to Window": "限制/裁切窗口大小", "Scaling Mode:": "缩放模式:", "None": "无", @@ -59,11 +59,11 @@ "Host:": "主机:", "Port:": "端口:", "Path:": "路径:", - "Automatic Reconnect": "自动重新链接", - "Reconnect Delay (ms):": "重新链接间隔 (ms):", + "Automatic Reconnect": "自动重新连接", + "Reconnect Delay (ms):": "重新连接间隔 (ms):", "Logging:": "日志级别:", - "Disconnect": "终端链接", - "Connect": "链接", + "Disconnect": "中断连接", + "Connect": "连接", "Password:": "密码:", "Cancel": "取消" } \ No newline at end of file diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/styles/base.css b/jupyter_desktop/share/web/noVNC-1.2.0/app/styles/base.css index 3ca9894d..fd78b79c 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/styles/base.css +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/styles/base.css @@ -1,6 +1,6 @@ /* * noVNC base CSS - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * noVNC is licensed under the MPL 2.0 (see LICENSE.txt) * This file is licensed under the 2-Clause BSD license (see LICENSE.txt). */ @@ -83,8 +83,20 @@ html { * ---------------------------------------- */ -input[type=input], input[type=password], input[type=number], -input:not([type]), textarea { +input:not([type]), +input[type=date], +input[type=datetime-local], +input[type=email], +input[type=month], +input[type=number], +input[type=password], +input[type=search], +input[type=tel], +input[type=text], +input[type=time], +input[type=url], +input[type=week], +textarea { /* Disable default rendering */ -webkit-appearance: none; -moz-appearance: none; @@ -98,7 +110,11 @@ input:not([type]), textarea { background: linear-gradient(to top, rgb(255, 255, 255) 80%, rgb(240, 240, 240)); } -input[type=button], input[type=submit], select { +input[type=button], +input[type=color], +input[type=reset], +input[type=submit], +select { /* Disable default rendering */ -webkit-appearance: none; -moz-appearance: none; @@ -116,7 +132,10 @@ input[type=button], input[type=submit], select { vertical-align: middle; } -input[type=button], input[type=submit] { +input[type=button], +input[type=color], +input[type=reset], +input[type=submit] { padding-left: 20px; padding-right: 20px; } @@ -126,35 +145,72 @@ option { background: white; } -input[type=input]:focus, input[type=password]:focus, -input:not([type]):focus, input[type=button]:focus, +input:not([type]):focus, +input[type=button]:focus, +input[type=color]:focus, +input[type=date]:focus, +input[type=datetime-local]:focus, +input[type=email]:focus, +input[type=month]:focus, +input[type=number]:focus, +input[type=password]:focus, +input[type=reset]:focus, +input[type=search]:focus, input[type=submit]:focus, -textarea:focus, select:focus { +input[type=tel]:focus, +input[type=text]:focus, +input[type=time]:focus, +input[type=url]:focus, +input[type=week]:focus, +select:focus, +textarea:focus { box-shadow: 0px 0px 3px rgba(74, 144, 217, 0.5); border-color: rgb(74, 144, 217); outline: none; } input[type=button]::-moz-focus-inner, +input[type=color]::-moz-focus-inner, +input[type=reset]::-moz-focus-inner, input[type=submit]::-moz-focus-inner { border: none; } -input[type=input]:disabled, input[type=password]:disabled, -input:not([type]):disabled, input[type=button]:disabled, -input[type=submit]:disabled, input[type=number]:disabled, -textarea:disabled, select:disabled { +input:not([type]):disabled, +input[type=button]:disabled, +input[type=color]:disabled, +input[type=date]:disabled, +input[type=datetime-local]:disabled, +input[type=email]:disabled, +input[type=month]:disabled, +input[type=number]:disabled, +input[type=password]:disabled, +input[type=reset]:disabled, +input[type=search]:disabled, +input[type=submit]:disabled, +input[type=tel]:disabled, +input[type=text]:disabled, +input[type=time]:disabled, +input[type=url]:disabled, +input[type=week]:disabled, +select:disabled, +textarea:disabled { color: rgb(128, 128, 128); background: rgb(240, 240, 240); } -input[type=button]:active, input[type=submit]:active, +input[type=button]:active, +input[type=color]:active, +input[type=reset]:active, +input[type=submit]:active, select:active { border-bottom-width: 1px; margin-top: 3px; } :root:not(.noVNC_touch) input[type=button]:hover:not(:disabled), +:root:not(.noVNC_touch) input[type=color]:hover:not(:disabled), +:root:not(.noVNC_touch) input[type=reset]:hover:not(:disabled), :root:not(.noVNC_touch) input[type=submit]:hover:not(:disabled), :root:not(.noVNC_touch) select:hover:not(:disabled) { background: linear-gradient(to top, rgb(255, 255, 255), rgb(250, 250, 250)); @@ -579,7 +635,7 @@ select:active { } /* Extra manual keys */ -:root:not(.noVNC_connected) #noVNC_extra_keys { +:root:not(.noVNC_connected) #noVNC_toggle_extra_keys_button { display: none; } @@ -631,6 +687,16 @@ select:active { width: 100px; } +/* Version */ + +.noVNC_version_wrapper { + font-size: small; +} + +.noVNC_version { + margin-left: 1rem; +} + /* Connection Controls */ :root:not(.noVNC_connected) #noVNC_disconnect_button { display: none; @@ -780,19 +846,23 @@ select:active { * ---------------------------------------- */ -#noVNC_password_dlg { +#noVNC_credentials_dlg { position: relative; transform: translateY(-50px); } -#noVNC_password_dlg.noVNC_open { +#noVNC_credentials_dlg.noVNC_open { transform: translateY(0); } -#noVNC_password_dlg ul { +#noVNC_credentials_dlg ul { list-style: none; margin: 0px; padding: 0px; } +.noVNC_hidden { + display: none; +} + /* ---------------------------------------- * Main Area diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/ui.js b/jupyter_desktop/share/web/noVNC-1.2.0/app/ui.js index 17ec48d4..c70743dc 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/ui.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/ui.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -8,7 +8,7 @@ import * as Log from '../core/util/logging.js'; import _, { l10n } from './localization.js'; -import { isTouchDevice, isSafari, isIOS, isAndroid, dragThreshold } +import { isTouchDevice, isSafari, hasScrollbarGutter, dragThreshold } from '../core/util/browser.js'; import { setCapture, getPointerEvent } from '../core/util/events.js'; import KeyTable from "../core/input/keysym.js"; @@ -17,6 +17,8 @@ import Keyboard from "../core/input/keyboard.js"; import RFB from "../core/rfb.js"; import * as WebUtil from "./webutil.js"; +const PAGE_TITLE = "noVNC"; + const UI = { connected: false, @@ -35,9 +37,9 @@ const UI = { lastKeyboardinput: null, defaultKeyboardinputLen: 100, - inhibit_reconnect: true, - reconnect_callback: null, - reconnect_password: null, + inhibitReconnect: true, + reconnectCallback: null, + reconnectPassword: null, prime() { return WebUtil.initSettings().then(() => { @@ -59,6 +61,17 @@ const UI = { // Translate the DOM l10n.translateDOM(); + WebUtil.fetchJSON('./package.json') + .then((packageInfo) => { + Array.from(document.getElementsByClassName('noVNC_version')).forEach(el => el.innerText = packageInfo.version); + }) + .catch((err) => { + Log.Error("Couldn't fetch package.json: " + err); + Array.from(document.getElementsByClassName('noVNC_version_wrapper')) + .concat(Array.from(document.getElementsByClassName('noVNC_version_separator'))) + .forEach(el => el.style.display = 'none'); + }); + // Adapt the interface for touch screen devices if (isTouchDevice) { document.documentElement.classList.add("noVNC_touch"); @@ -148,6 +161,8 @@ const UI = { UI.initSetting('encrypt', (window.location.protocol === "https:")); UI.initSetting('view_clip', false); UI.initSetting('resize', 'off'); + UI.initSetting('quality', 6); + UI.initSetting('compression', 2); UI.initSetting('shared', true); UI.initSetting('view_only', false); UI.initSetting('show_dot', false); @@ -219,14 +234,6 @@ const UI = { }, addTouchSpecificHandlers() { - document.getElementById("noVNC_mouse_button0") - .addEventListener('click', () => UI.setMouseButton(1)); - document.getElementById("noVNC_mouse_button1") - .addEventListener('click', () => UI.setMouseButton(2)); - document.getElementById("noVNC_mouse_button2") - .addEventListener('click', () => UI.setMouseButton(4)); - document.getElementById("noVNC_mouse_button4") - .addEventListener('click', () => UI.setMouseButton(0)); document.getElementById("noVNC_keyboard_button") .addEventListener('click', UI.toggleVirtualKeyboard); @@ -303,8 +310,8 @@ const UI = { document.getElementById("noVNC_cancel_reconnect_button") .addEventListener('click', UI.cancelReconnect); - document.getElementById("noVNC_password_button") - .addEventListener('click', UI.setPassword); + document.getElementById("noVNC_credentials_button") + .addEventListener('click', UI.setCredentials); }, addClipboardHandlers() { @@ -334,6 +341,10 @@ const UI = { UI.addSettingChangeHandler('resize'); UI.addSettingChangeHandler('resize', UI.applyResizeMode); UI.addSettingChangeHandler('resize', UI.updateViewClip); + UI.addSettingChangeHandler('quality'); + UI.addSettingChangeHandler('quality', UI.updateQuality); + UI.addSettingChangeHandler('compression'); + UI.addSettingChangeHandler('compression', UI.updateCompression); UI.addSettingChangeHandler('view_clip'); UI.addSettingChangeHandler('view_clip', UI.updateViewClip); UI.addSettingChangeHandler('shared'); @@ -375,25 +386,25 @@ const UI = { document.documentElement.classList.remove("noVNC_disconnecting"); document.documentElement.classList.remove("noVNC_reconnecting"); - const transition_elem = document.getElementById("noVNC_transition_text"); + const transitionElem = document.getElementById("noVNC_transition_text"); switch (state) { case 'init': break; case 'connecting': - transition_elem.textContent = _("Connecting..."); + transitionElem.textContent = _("Connecting..."); document.documentElement.classList.add("noVNC_connecting"); break; case 'connected': document.documentElement.classList.add("noVNC_connected"); break; case 'disconnecting': - transition_elem.textContent = _("Disconnecting..."); + transitionElem.textContent = _("Disconnecting..."); document.documentElement.classList.add("noVNC_disconnecting"); break; case 'disconnected': break; case 'reconnecting': - transition_elem.textContent = _("Reconnecting..."); + transitionElem.textContent = _("Reconnecting..."); document.documentElement.classList.add("noVNC_reconnecting"); break; default: @@ -411,7 +422,6 @@ const UI = { UI.disableSetting('port'); UI.disableSetting('path'); UI.disableSetting('repeaterID'); - UI.setMouseButton(1); // Hide the controlbar after 2 seconds UI.closeControlbarTimeout = setTimeout(UI.closeControlbar, 2000); @@ -426,38 +436,35 @@ const UI = { UI.keepControlbar(); } - // State change closes the password dialog - document.getElementById('noVNC_password_dlg') + // State change closes dialogs as they may not be relevant + // anymore + UI.closeAllPanels(); + document.getElementById('noVNC_credentials_dlg') .classList.remove('noVNC_open'); }, - showStatus(text, status_type, time) { + showStatus(text, statusType, time) { const statusElem = document.getElementById('noVNC_status'); - clearTimeout(UI.statusTimeout); - - if (typeof status_type === 'undefined') { - status_type = 'normal'; + if (typeof statusType === 'undefined') { + statusType = 'normal'; } // Don't overwrite more severe visible statuses and never // errors. Only shows the first error. - let visible_status_type = 'none'; if (statusElem.classList.contains("noVNC_open")) { if (statusElem.classList.contains("noVNC_status_error")) { - visible_status_type = 'error'; - } else if (statusElem.classList.contains("noVNC_status_warn")) { - visible_status_type = 'warn'; - } else { - visible_status_type = 'normal'; + return; + } + if (statusElem.classList.contains("noVNC_status_warn") && + statusType === 'normal') { + return; } } - if (visible_status_type === 'error' || - (visible_status_type === 'warn' && status_type === 'normal')) { - return; - } - switch (status_type) { + clearTimeout(UI.statusTimeout); + + switch (statusType) { case 'error': statusElem.classList.remove("noVNC_status_warn"); statusElem.classList.remove("noVNC_status_normal"); @@ -487,7 +494,7 @@ const UI = { } // Error messages do not timeout - if (status_type !== 'error') { + if (statusType !== 'error') { UI.statusTimeout = window.setTimeout(UI.hideStatus, time); } }, @@ -507,6 +514,13 @@ const UI = { }, idleControlbar() { + // Don't fade if a child of the control bar has focus + if (document.getElementById('noVNC_control_bar') + .contains(document.activeElement) && document.hasFocus()) { + UI.activateControlbar(); + return; + } + document.getElementById('noVNC_control_bar_anchor') .classList.add("noVNC_idle"); }, @@ -524,6 +538,7 @@ const UI = { UI.closeAllPanels(); document.getElementById('noVNC_control_bar') .classList.remove("noVNC_open"); + UI.rfb.focus(); }, toggleControlbar() { @@ -821,6 +836,8 @@ const UI = { UI.updateSetting('encrypt'); UI.updateSetting('view_clip'); UI.updateSetting('resize'); + UI.updateSetting('quality'); + UI.updateSetting('compression'); UI.updateSetting('shared'); UI.updateSetting('view_only'); UI.updateSetting('path'); @@ -977,7 +994,7 @@ const UI = { if (typeof password === 'undefined') { password = WebUtil.getConfigVar('password'); - UI.reconnect_password = password; + UI.reconnectPassword = password; } if (password === null) { @@ -992,7 +1009,6 @@ const UI = { return; } - UI.closeAllPanels(); UI.closeConnectPanel(); UI.updateVisualState('connecting'); @@ -1009,7 +1025,6 @@ const UI = { UI.rfb = new RFB(document.getElementById('noVNC_container'), url, { shared: UI.getSetting('shared'), - showDotCursor: UI.getSetting('show_dot'), repeaterID: UI.getSetting('repeaterID'), credentials: { password: password } }); UI.rfb.addEventListener("connect", UI.connectFinished); @@ -1023,18 +1038,20 @@ const UI = { UI.rfb.clipViewport = UI.getSetting('view_clip'); UI.rfb.scaleViewport = UI.getSetting('resize') === 'scale'; UI.rfb.resizeSession = UI.getSetting('resize') === 'remote'; + UI.rfb.qualityLevel = parseInt(UI.getSetting('quality')); + UI.rfb.compressionLevel = parseInt(UI.getSetting('compression')); + UI.rfb.showDotCursor = UI.getSetting('show_dot'); UI.updateViewOnly(); // requires UI.rfb }, disconnect() { - UI.closeAllPanels(); UI.rfb.disconnect(); UI.connected = false; // Disable automatic reconnecting - UI.inhibit_reconnect = true; + UI.inhibitReconnect = true; UI.updateVisualState('disconnecting'); @@ -1042,20 +1059,20 @@ const UI = { }, reconnect() { - UI.reconnect_callback = null; + UI.reconnectCallback = null; // if reconnect has been disabled in the meantime, do nothing. - if (UI.inhibit_reconnect) { + if (UI.inhibitReconnect) { return; } - UI.connect(null, UI.reconnect_password); + UI.connect(null, UI.reconnectPassword); }, cancelReconnect() { - if (UI.reconnect_callback !== null) { - clearTimeout(UI.reconnect_callback); - UI.reconnect_callback = null; + if (UI.reconnectCallback !== null) { + clearTimeout(UI.reconnectCallback); + UI.reconnectCallback = null; } UI.updateVisualState('disconnected'); @@ -1066,7 +1083,7 @@ const UI = { connectFinished(e) { UI.connected = true; - UI.inhibit_reconnect = false; + UI.inhibitReconnect = false; let msg; if (UI.getSetting('encrypt')) { @@ -1100,17 +1117,19 @@ const UI = { } else { UI.showStatus(_("Failed to connect to server"), 'error'); } - } else if (UI.getSetting('reconnect', false) === true && !UI.inhibit_reconnect) { + } else if (UI.getSetting('reconnect', false) === true && !UI.inhibitReconnect) { UI.updateVisualState('reconnecting'); const delay = parseInt(UI.getSetting('reconnect_delay')); - UI.reconnect_callback = setTimeout(UI.reconnect, delay); + UI.reconnectCallback = setTimeout(UI.reconnect, delay); return; } else { UI.updateVisualState('disconnected'); UI.showStatus(_("Disconnected"), 'normal'); } + document.title = PAGE_TITLE; + UI.openControlbar(); UI.openConnectPanel(); }, @@ -1137,27 +1156,46 @@ const UI = { credentials(e) { // FIXME: handle more types - document.getElementById('noVNC_password_dlg') + + document.getElementById("noVNC_username_block").classList.remove("noVNC_hidden"); + document.getElementById("noVNC_password_block").classList.remove("noVNC_hidden"); + + let inputFocus = "none"; + if (e.detail.types.indexOf("username") === -1) { + document.getElementById("noVNC_username_block").classList.add("noVNC_hidden"); + } else { + inputFocus = inputFocus === "none" ? "noVNC_username_input" : inputFocus; + } + if (e.detail.types.indexOf("password") === -1) { + document.getElementById("noVNC_password_block").classList.add("noVNC_hidden"); + } else { + inputFocus = inputFocus === "none" ? "noVNC_password_input" : inputFocus; + } + document.getElementById('noVNC_credentials_dlg') .classList.add('noVNC_open'); setTimeout(() => document - .getElementById('noVNC_password_input').focus(), 100); + .getElementById(inputFocus).focus(), 100); - Log.Warn("Server asked for a password"); - UI.showStatus(_("Password is required"), "warning"); + Log.Warn("Server asked for credentials"); + UI.showStatus(_("Credentials are required"), "warning"); }, - setPassword(e) { + setCredentials(e) { // Prevent actually submitting the form e.preventDefault(); - const inputElem = document.getElementById('noVNC_password_input'); - const password = inputElem.value; + let inputElemUsername = document.getElementById('noVNC_username_input'); + const username = inputElemUsername.value; + + let inputElemPassword = document.getElementById('noVNC_password_input'); + const password = inputElemPassword.value; // Clear the input after reading the password - inputElem.value = ""; - UI.rfb.sendCredentials({ password: password }); - UI.reconnect_password = password; - document.getElementById('noVNC_password_dlg') + inputElemPassword.value = ""; + + UI.rfb.sendCredentials({ username: username, password: password }); + UI.reconnectPassword = password; + document.getElementById('noVNC_credentials_dlg') .classList.remove('noVNC_open'); }, @@ -1240,8 +1278,9 @@ const UI = { // Can't be clipping if viewport is scaled to fit UI.forceSetting('view_clip', false); UI.rfb.clipViewport = false; - } else if (isIOS() || isAndroid()) { - // iOS and Android usually have shit scrollbars + } else if (!hasScrollbarGutter) { + // Some platforms have scrollbars that are difficult + // to use in our case, so we always use our own panning UI.forceSetting('view_clip', true); UI.rfb.clipViewport = true; } else { @@ -1284,30 +1323,40 @@ const UI = { viewDragButton.classList.remove("noVNC_selected"); } - // Different behaviour for touch vs non-touch - // The button is disabled instead of hidden on touch devices - if (isTouchDevice) { + if (UI.rfb.clipViewport) { viewDragButton.classList.remove("noVNC_hidden"); - - if (UI.rfb.clipViewport) { - viewDragButton.disabled = false; - } else { - viewDragButton.disabled = true; - } } else { - viewDragButton.disabled = false; - - if (UI.rfb.clipViewport) { - viewDragButton.classList.remove("noVNC_hidden"); - } else { - viewDragButton.classList.add("noVNC_hidden"); - } + viewDragButton.classList.add("noVNC_hidden"); } }, /* ------^------- * /VIEWDRAG * ============== + * QUALITY + * ------v------*/ + + updateQuality() { + if (!UI.rfb) return; + + UI.rfb.qualityLevel = parseInt(UI.getSetting('quality')); + }, + +/* ------^------- + * /QUALITY + * ============== + * COMPRESSION + * ------v------*/ + + updateCompression() { + if (!UI.rfb) return; + + UI.rfb.compressionLevel = parseInt(UI.getSetting('compression')); + }, + +/* ------^------- + * /COMPRESSION + * ============== * KEYBOARD * ------v------*/ @@ -1502,20 +1551,20 @@ const UI = { }, sendEsc() { - UI.rfb.sendKey(KeyTable.XK_Escape, "Escape"); + UI.sendKey(KeyTable.XK_Escape, "Escape"); }, sendTab() { - UI.rfb.sendKey(KeyTable.XK_Tab); + UI.sendKey(KeyTable.XK_Tab, "Tab"); }, toggleCtrl() { const btn = document.getElementById('noVNC_toggle_ctrl_button'); if (btn.classList.contains("noVNC_selected")) { - UI.rfb.sendKey(KeyTable.XK_Control_L, "ControlLeft", false); + UI.sendKey(KeyTable.XK_Control_L, "ControlLeft", false); btn.classList.remove("noVNC_selected"); } else { - UI.rfb.sendKey(KeyTable.XK_Control_L, "ControlLeft", true); + UI.sendKey(KeyTable.XK_Control_L, "ControlLeft", true); btn.classList.add("noVNC_selected"); } }, @@ -1523,10 +1572,10 @@ const UI = { toggleWindows() { const btn = document.getElementById('noVNC_toggle_windows_button'); if (btn.classList.contains("noVNC_selected")) { - UI.rfb.sendKey(KeyTable.XK_Super_L, "MetaLeft", false); + UI.sendKey(KeyTable.XK_Super_L, "MetaLeft", false); btn.classList.remove("noVNC_selected"); } else { - UI.rfb.sendKey(KeyTable.XK_Super_L, "MetaLeft", true); + UI.sendKey(KeyTable.XK_Super_L, "MetaLeft", true); btn.classList.add("noVNC_selected"); } }, @@ -1534,16 +1583,39 @@ const UI = { toggleAlt() { const btn = document.getElementById('noVNC_toggle_alt_button'); if (btn.classList.contains("noVNC_selected")) { - UI.rfb.sendKey(KeyTable.XK_Alt_L, "AltLeft", false); + UI.sendKey(KeyTable.XK_Alt_L, "AltLeft", false); btn.classList.remove("noVNC_selected"); } else { - UI.rfb.sendKey(KeyTable.XK_Alt_L, "AltLeft", true); + UI.sendKey(KeyTable.XK_Alt_L, "AltLeft", true); btn.classList.add("noVNC_selected"); } }, sendCtrlAltDel() { UI.rfb.sendCtrlAltDel(); + // See below + UI.rfb.focus(); + UI.idleControlbar(); + }, + + sendKey(keysym, code, down) { + UI.rfb.sendKey(keysym, code, down); + + // Move focus to the screen in order to be able to use the + // keyboard right after these extra keys. + // The exception is when a virtual keyboard is used, because + // if we focus the screen the virtual keyboard would be closed. + // In this case we focus our special virtual keyboard input + // element instead. + if (document.getElementById('noVNC_keyboard_button') + .classList.contains("noVNC_selected")) { + document.getElementById('noVNC_keyboardinput').focus(); + } else { + UI.rfb.focus(); + } + // fade out the controlbar to highlight that + // the focus has been moved to the screen + UI.idleControlbar(); }, /* ------^------- @@ -1552,24 +1624,6 @@ const UI = { * MISC * ------v------*/ - setMouseButton(num) { - const view_only = UI.rfb.viewOnly; - if (UI.rfb && !view_only) { - UI.rfb.touchButton = num; - } - - const blist = [0, 1, 2, 4]; - for (let b = 0; b < blist.length; b++) { - const button = document.getElementById('noVNC_mouse_button' + - blist[b]); - if (blist[b] === num && !view_only) { - button.classList.remove("noVNC_hidden"); - } else { - button.classList.add("noVNC_hidden"); - } - } - }, - updateViewOnly() { if (!UI.rfb) return; UI.rfb.viewOnly = UI.getSetting('view_only'); @@ -1580,14 +1634,14 @@ const UI = { .classList.add('noVNC_hidden'); document.getElementById('noVNC_toggle_extra_keys_button') .classList.add('noVNC_hidden'); - document.getElementById('noVNC_mouse_button' + UI.rfb.touchButton) + document.getElementById('noVNC_clipboard_button') .classList.add('noVNC_hidden'); } else { document.getElementById('noVNC_keyboard_button') .classList.remove('noVNC_hidden'); document.getElementById('noVNC_toggle_extra_keys_button') .classList.remove('noVNC_hidden'); - document.getElementById('noVNC_mouse_button' + UI.rfb.touchButton) + document.getElementById('noVNC_clipboard_button') .classList.remove('noVNC_hidden'); } }, @@ -1598,13 +1652,13 @@ const UI = { }, updateLogging() { - WebUtil.init_logging(UI.getSetting('logging')); + WebUtil.initLogging(UI.getSetting('logging')); }, updateDesktopName(e) { UI.desktopName = e.detail.name; // Display the desktop name in the document title - document.title = e.detail.name + " - noVNC"; + document.title = e.detail.name + " - " + PAGE_TITLE; }, bell(e) { @@ -1640,7 +1694,7 @@ const UI = { }; // Set up translations -const LINGUAS = ["cs", "de", "el", "es", "ko", "nl", "pl", "ru", "sv", "tr", "zh_CN", "zh_TW"]; +const LINGUAS = ["cs", "de", "el", "es", "ja", "ko", "nl", "pl", "ru", "sv", "tr", "zh_CN", "zh_TW"]; l10n.setup(LINGUAS); if (l10n.language === "en" || l10n.dictionary !== undefined) { UI.prime(); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/app/webutil.js b/jupyter_desktop/share/web/noVNC-1.2.0/app/webutil.js index 98e1d9e6..a099f9d7 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/app/webutil.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/app/webutil.js @@ -1,21 +1,21 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. */ -import { init_logging as main_init_logging } from '../core/util/logging.js'; +import { initLogging as mainInitLogging } from '../core/util/logging.js'; // init log level reading the logging HTTP param -export function init_logging(level) { +export function initLogging(level) { "use strict"; if (typeof level !== "undefined") { - main_init_logging(level); + mainInitLogging(level); } else { const param = document.location.href.match(/logging=([A-Za-z0-9._-]*)/); - main_init_logging(param || undefined); + mainInitLogging(param || undefined); } } @@ -184,7 +184,7 @@ export function injectParamIfMissing(path, param, value) { const elem = document.createElement('a'); elem.href = path; - const param_eq = encodeURIComponent(param) + "="; + const paramEq = encodeURIComponent(param) + "="; let query; if (elem.search) { query = elem.search.slice(1).split('&'); @@ -192,8 +192,8 @@ export function injectParamIfMissing(path, param, value) { query = []; } - if (!query.some(v => v.startsWith(param_eq))) { - query.push(param_eq + encodeURIComponent(value)); + if (!query.some(v => v.startsWith(paramEq))) { + query.push(paramEq + encodeURIComponent(value)); elem.search = "?" + query.join("&"); } diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/base64.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/base64.js index 88e74546..db572c2d 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/base64.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/base64.js @@ -57,12 +57,12 @@ export default { /* eslint-enable comma-spacing */ decode(data, offset = 0) { - let data_length = data.indexOf('=') - offset; - if (data_length < 0) { data_length = data.length - offset; } + let dataLength = data.indexOf('=') - offset; + if (dataLength < 0) { dataLength = data.length - offset; } /* Every four characters is 3 resulting numbers */ - const result_length = (data_length >> 2) * 3 + Math.floor((data_length % 4) / 1.5); - const result = new Array(result_length); + const resultLength = (dataLength >> 2) * 3 + Math.floor((dataLength % 4) / 1.5); + const result = new Array(resultLength); // Convert one by one. diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/copyrect.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/copyrect.js index a78ded75..0e0536a6 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/copyrect.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/copyrect.js @@ -1,8 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/hextile.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/hextile.js index aa76d2f3..8dbe8092 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/hextile.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/hextile.js @@ -1,8 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -19,10 +17,10 @@ export default class HextileDecoder { decodeRect(x, y, width, height, sock, display, depth) { if (this._tiles === 0) { - this._tiles_x = Math.ceil(width / 16); - this._tiles_y = Math.ceil(height / 16); - this._total_tiles = this._tiles_x * this._tiles_y; - this._tiles = this._total_tiles; + this._tilesX = Math.ceil(width / 16); + this._tilesY = Math.ceil(height / 16); + this._totalTiles = this._tilesX * this._tilesY; + this._tiles = this._totalTiles; } while (this._tiles > 0) { @@ -41,11 +39,11 @@ export default class HextileDecoder { subencoding + ")"); } - const curr_tile = this._total_tiles - this._tiles; - const tile_x = curr_tile % this._tiles_x; - const tile_y = Math.floor(curr_tile / this._tiles_x); - const tx = x + tile_x * 16; - const ty = y + tile_y * 16; + const currTile = this._totalTiles - this._tiles; + const tileX = currTile % this._tilesX; + const tileY = Math.floor(currTile / this._tilesX); + const tx = x + tileX * 16; + const ty = y + tileY * 16; const tw = Math.min(16, (x + width) - tx); const th = Math.min(16, (y + height) - ty); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/raw.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/raw.js index f676e0d9..4d84d7d1 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/raw.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/raw.js @@ -1,8 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -26,15 +24,15 @@ export default class RawDecoder { return false; } - const cur_y = y + (height - this._lines); - const curr_height = Math.min(this._lines, - Math.floor(sock.rQlen / bytesPerLine)); + const curY = y + (height - this._lines); + const currHeight = Math.min(this._lines, + Math.floor(sock.rQlen / bytesPerLine)); let data = sock.rQ; let index = sock.rQi; // Convert data if needed if (depth == 8) { - const pixels = width * curr_height; + const pixels = width * currHeight; const newdata = new Uint8Array(pixels * 4); for (let i = 0; i < pixels; i++) { newdata[i * 4 + 0] = ((data[index + i] >> 0) & 0x3) * 255 / 3; @@ -46,9 +44,9 @@ export default class RawDecoder { index = 0; } - display.blitImage(x, cur_y, width, curr_height, data, index); - sock.rQskipBytes(curr_height * bytesPerLine); - this._lines -= curr_height; + display.blitImage(x, curY, width, currHeight, data, index); + sock.rQskipBytes(currHeight * bytesPerLine); + this._lines -= currHeight; if (this._lines > 0) { return false; } diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/rre.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/rre.js index 57414a09..6219369d 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/rre.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/rre.js @@ -1,8 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/tight.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/tight.js index bcda04ce..b207419e 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/tight.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/tight.js @@ -1,9 +1,7 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin + * Copyright (C) 2019 The noVNC Authors * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca) - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -94,7 +92,7 @@ export default class TightDecoder { return false; } - display.imageRect(x, y, "image/jpeg", data); + display.imageRect(x, y, width, height, "image/jpeg", data); return true; } @@ -162,10 +160,9 @@ export default class TightDecoder { return false; } - data = this._zlibs[streamId].inflate(data, true, uncompressedSize); - if (data.length != uncompressedSize) { - throw new Error("Incomplete zlib block"); - } + this._zlibs[streamId].setInput(data); + data = this._zlibs[streamId].inflate(uncompressedSize); + this._zlibs[streamId].setInput(null); } display.blitRgbImage(x, y, width, height, data, 0, false); @@ -210,10 +207,9 @@ export default class TightDecoder { return false; } - data = this._zlibs[streamId].inflate(data, true, uncompressedSize); - if (data.length != uncompressedSize) { - throw new Error("Incomplete zlib block"); - } + this._zlibs[streamId].setInput(data); + data = this._zlibs[streamId].inflate(uncompressedSize); + this._zlibs[streamId].setInput(null); } // Convert indexed (palette based) image data to RGB diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/tightpng.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/tightpng.js index 7bbde3a4..82f492de 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/tightpng.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/decoders/tightpng.js @@ -1,8 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2018 Samuel Mannehed for Cendio AB - * Copyright (C) 2018 Pierre Ossman for Cendio AB + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -18,7 +16,7 @@ export default class TightPNGDecoder extends TightDecoder { return false; } - display.imageRect(x, y, "image/png", data); + display.imageRect(x, y, width, height, "image/png", data); return true; } diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/deflator.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/deflator.js new file mode 100644 index 00000000..fe2a8f70 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/deflator.js @@ -0,0 +1,85 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC Authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +import { deflateInit, deflate } from "../vendor/pako/lib/zlib/deflate.js"; +import { Z_FULL_FLUSH } from "../vendor/pako/lib/zlib/deflate.js"; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; + +export default class Deflator { + constructor() { + this.strm = new ZStream(); + this.chunkSize = 1024 * 10 * 10; + this.outputBuffer = new Uint8Array(this.chunkSize); + this.windowBits = 5; + + deflateInit(this.strm, this.windowBits); + } + + deflate(inData) { + /* eslint-disable camelcase */ + this.strm.input = inData; + this.strm.avail_in = this.strm.input.length; + this.strm.next_in = 0; + this.strm.output = this.outputBuffer; + this.strm.avail_out = this.chunkSize; + this.strm.next_out = 0; + /* eslint-enable camelcase */ + + let lastRet = deflate(this.strm, Z_FULL_FLUSH); + let outData = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); + + if (lastRet < 0) { + throw new Error("zlib deflate failed"); + } + + if (this.strm.avail_in > 0) { + // Read chunks until done + + let chunks = [outData]; + let totalLen = outData.length; + do { + /* eslint-disable camelcase */ + this.strm.output = new Uint8Array(this.chunkSize); + this.strm.next_out = 0; + this.strm.avail_out = this.chunkSize; + /* eslint-enable camelcase */ + + lastRet = deflate(this.strm, Z_FULL_FLUSH); + + if (lastRet < 0) { + throw new Error("zlib deflate failed"); + } + + let chunk = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); + totalLen += chunk.length; + chunks.push(chunk); + } while (this.strm.avail_in > 0); + + // Combine chunks into a single data + + let newData = new Uint8Array(totalLen); + let offset = 0; + + for (let i = 0; i < chunks.length; i++) { + newData.set(chunks[i], offset); + offset += chunks[i].length; + } + + outData = newData; + } + + /* eslint-disable camelcase */ + this.strm.input = null; + this.strm.avail_in = 0; + this.strm.next_in = 0; + /* eslint-enable camelcase */ + + return outData; + } + +} diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/display.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/display.js index 1528384d..cf1a51aa 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/display.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/display.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -9,24 +9,24 @@ import * as Log from './util/logging.js'; import Base64 from "./base64.js"; import { supportsImageMetadata } from './util/browser.js'; +import { toSigned32bit } from './util/int.js'; export default class Display { constructor(target) { this._drawCtx = null; - this._c_forceCanvas = false; this._renderQ = []; // queue drawing actions for in-oder rendering this._flushing = false; // the full frame buffer (logical canvas) size - this._fb_width = 0; - this._fb_height = 0; + this._fbWidth = 0; + this._fbHeight = 0; this._prevDrawStyle = ""; this._tile = null; this._tile16x16 = null; - this._tile_x = 0; - this._tile_y = 0; + this._tileX = 0; + this._tileY = 0; Log.Debug(">> Display.constructor"); @@ -60,8 +60,6 @@ export default class Display { Log.Debug("User Agent: " + navigator.userAgent); - this.clear(); - // Check canvas features if (!('createImageData' in this._drawCtx)) { throw new Error("Canvas does not support createImageData"); @@ -74,7 +72,6 @@ export default class Display { this._scale = 1.0; this._clipViewport = false; - this.logo = null; // ===== EVENT HANDLERS ===== @@ -98,11 +95,11 @@ export default class Display { } get width() { - return this._fb_width; + return this._fbWidth; } get height() { - return this._fb_height; + return this._fbHeight; } // ===== PUBLIC METHODS ===== @@ -125,15 +122,15 @@ export default class Display { if (deltaX < 0 && vp.x + deltaX < 0) { deltaX = -vp.x; } - if (vx2 + deltaX >= this._fb_width) { - deltaX -= vx2 + deltaX - this._fb_width + 1; + if (vx2 + deltaX >= this._fbWidth) { + deltaX -= vx2 + deltaX - this._fbWidth + 1; } if (vp.y + deltaY < 0) { deltaY = -vp.y; } - if (vy2 + deltaY >= this._fb_height) { - deltaY -= (vy2 + deltaY - this._fb_height + 1); + if (vy2 + deltaY >= this._fbHeight) { + deltaY -= (vy2 + deltaY - this._fbHeight + 1); } if (deltaX === 0 && deltaY === 0) { @@ -156,18 +153,18 @@ export default class Display { typeof(height) === "undefined") { Log.Debug("Setting viewport to full display region"); - width = this._fb_width; - height = this._fb_height; + width = this._fbWidth; + height = this._fbHeight; } width = Math.floor(width); height = Math.floor(height); - if (width > this._fb_width) { - width = this._fb_width; + if (width > this._fbWidth) { + width = this._fbWidth; } - if (height > this._fb_height) { - height = this._fb_height; + if (height > this._fbHeight) { + height = this._fbHeight; } const vp = this._viewportLoc; @@ -194,21 +191,21 @@ export default class Display { if (this._scale === 0) { return 0; } - return x / this._scale + this._viewportLoc.x; + return toSigned32bit(x / this._scale + this._viewportLoc.x); } absY(y) { if (this._scale === 0) { return 0; } - return y / this._scale + this._viewportLoc.y; + return toSigned32bit(y / this._scale + this._viewportLoc.y); } resize(width, height) { this._prevDrawStyle = ""; - this._fb_width = width; - this._fb_height = height; + this._fbWidth = width; + this._fbHeight = height; const canvas = this._backbuffer; if (canvas.width !== width || canvas.height !== height) { @@ -256,9 +253,9 @@ export default class Display { // Update the visible canvas with the contents of the // rendering canvas - flip(from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - this._renderQ_push({ + flip(fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ 'type': 'flip' }); } else { @@ -302,17 +299,6 @@ export default class Display { } } - clear() { - if (this._logo) { - this.resize(this._logo.width, this._logo.height); - this.imageRect(0, 0, this._logo.type, this._logo.data); - } else { - this.resize(240, 20); - this._drawCtx.clearRect(0, 0, this._fb_width, this._fb_height); - } - this.flip(); - } - pending() { return this._renderQ.length > 0; } @@ -325,9 +311,9 @@ export default class Display { } } - fillRect(x, y, width, height, color, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - this._renderQ_push({ + fillRect(x, y, width, height, color, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ 'type': 'fill', 'x': x, 'y': y, @@ -342,14 +328,14 @@ export default class Display { } } - copyImage(old_x, old_y, new_x, new_y, w, h, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { - this._renderQ_push({ + copyImage(oldX, oldY, newX, newY, w, h, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { + this._renderQPush({ 'type': 'copy', - 'old_x': old_x, - 'old_y': old_y, - 'x': new_x, - 'y': new_y, + 'oldX': oldX, + 'oldY': oldY, + 'x': newX, + 'y': newY, 'width': w, 'height': h, }); @@ -367,27 +353,35 @@ export default class Display { this._drawCtx.imageSmoothingEnabled = false; this._drawCtx.drawImage(this._backbuffer, - old_x, old_y, w, h, - new_x, new_y, w, h); - this._damage(new_x, new_y, w, h); + oldX, oldY, w, h, + newX, newY, w, h); + this._damage(newX, newY, w, h); } } - imageRect(x, y, mime, arr) { + imageRect(x, y, width, height, mime, arr) { + /* The internal logic cannot handle empty images, so bail early */ + if ((width === 0) || (height === 0)) { + return; + } + const img = new Image(); img.src = "data: " + mime + ";base64," + Base64.encode(arr); - this._renderQ_push({ + + this._renderQPush({ 'type': 'img', 'img': img, 'x': x, - 'y': y + 'y': y, + 'width': width, + 'height': height }); } // start updating a tile startTile(x, y, width, height, color) { - this._tile_x = x; - this._tile_y = y; + this._tileX = x; + this._tileY = y; if (width === 16 && height === 16) { this._tile = this._tile16x16; } else { @@ -430,21 +424,21 @@ export default class Display { // draw the current tile to the screen finishTile() { - this._drawCtx.putImageData(this._tile, this._tile_x, this._tile_y); - this._damage(this._tile_x, this._tile_y, + this._drawCtx.putImageData(this._tile, this._tileX, this._tileY); + this._damage(this._tileX, this._tileY, this._tile.width, this._tile.height); } - blitImage(x, y, width, height, arr, offset, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { + blitImage(x, y, width, height, arr, offset, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { // NB(directxman12): it's technically more performant here to use preallocated arrays, // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, // this probably isn't getting called *nearly* as much - const new_arr = new Uint8Array(width * height * 4); - new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); - this._renderQ_push({ + const newArr = new Uint8Array(width * height * 4); + newArr.set(new Uint8Array(arr.buffer, 0, newArr.length)); + this._renderQPush({ 'type': 'blit', - 'data': new_arr, + 'data': newArr, 'x': x, 'y': y, 'width': width, @@ -455,16 +449,16 @@ export default class Display { } } - blitRgbImage(x, y, width, height, arr, offset, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { + blitRgbImage(x, y, width, height, arr, offset, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { // NB(directxman12): it's technically more performant here to use preallocated arrays, // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, // this probably isn't getting called *nearly* as much - const new_arr = new Uint8Array(width * height * 3); - new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); - this._renderQ_push({ + const newArr = new Uint8Array(width * height * 3); + newArr.set(new Uint8Array(arr.buffer, 0, newArr.length)); + this._renderQPush({ 'type': 'blitRgb', - 'data': new_arr, + 'data': newArr, 'x': x, 'y': y, 'width': width, @@ -475,16 +469,16 @@ export default class Display { } } - blitRgbxImage(x, y, width, height, arr, offset, from_queue) { - if (this._renderQ.length !== 0 && !from_queue) { + blitRgbxImage(x, y, width, height, arr, offset, fromQueue) { + if (this._renderQ.length !== 0 && !fromQueue) { // NB(directxman12): it's technically more performant here to use preallocated arrays, // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, // this probably isn't getting called *nearly* as much - const new_arr = new Uint8Array(width * height * 4); - new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); - this._renderQ_push({ + const newArr = new Uint8Array(width * height * 4); + newArr.set(new Uint8Array(arr.buffer, 0, newArr.length)); + this._renderQPush({ 'type': 'blitRgbx', - 'data': new_arr, + 'data': newArr, 'x': x, 'y': y, 'width': width, @@ -589,23 +583,23 @@ export default class Display { this._damage(x, y, img.width, img.height); } - _renderQ_push(action) { + _renderQPush(action) { this._renderQ.push(action); if (this._renderQ.length === 1) { // If this can be rendered immediately it will be, otherwise // the scanner will wait for the relevant event - this._scan_renderQ(); + this._scanRenderQ(); } } - _resume_renderQ() { + _resumeRenderQ() { // "this" is the object that is ready, not the // display object - this.removeEventListener('load', this._noVNC_display._resume_renderQ); - this._noVNC_display._scan_renderQ(); + this.removeEventListener('load', this._noVNCDisplay._resumeRenderQ); + this._noVNCDisplay._scanRenderQ(); } - _scan_renderQ() { + _scanRenderQ() { let ready = true; while (ready && this._renderQ.length > 0) { const a = this._renderQ[0]; @@ -614,7 +608,7 @@ export default class Display { this.flip(true); break; case 'copy': - this.copyImage(a.old_x, a.old_y, a.x, a.y, a.width, a.height, true); + this.copyImage(a.oldX, a.oldY, a.x, a.y, a.width, a.height, true); break; case 'fill': this.fillRect(a.x, a.y, a.width, a.height, a.color, true); @@ -629,11 +623,18 @@ export default class Display { this.blitRgbxImage(a.x, a.y, a.width, a.height, a.data, 0, true); break; case 'img': - if (a.img.complete) { + /* IE tends to set "complete" prematurely, so check dimensions */ + if (a.img.complete && (a.img.width !== 0) && (a.img.height !== 0)) { + if (a.img.width !== a.width || a.img.height !== a.height) { + Log.Error("Decoded image has incorrect dimensions. Got " + + a.img.width + "x" + a.img.height + ". Expected " + + a.width + "x" + a.height + "."); + return; + } this.drawImage(a.img, a.x, a.y); } else { - a.img._noVNC_display = this; - a.img.addEventListener('load', this._resume_renderQ); + a.img._noVNCDisplay = this; + a.img.addEventListener('load', this._resumeRenderQ); // We need to wait for this image to 'load' // to keep things in-order ready = false; diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/encodings.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/encodings.js index 9fd38d58..51c09929 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/encodings.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/encodings.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -20,12 +20,15 @@ export const encodings = { pseudoEncodingLastRect: -224, pseudoEncodingCursor: -239, pseudoEncodingQEMUExtendedKeyEvent: -258, + pseudoEncodingDesktopName: -307, pseudoEncodingExtendedDesktopSize: -308, pseudoEncodingXvp: -309, pseudoEncodingFence: -312, pseudoEncodingContinuousUpdates: -313, pseudoEncodingCompressLevel9: -247, pseudoEncodingCompressLevel0: -256, + pseudoEncodingVMwareCursor: 0x574d5664, + pseudoEncodingExtendedClipboard: 0xc0a1e5ce }; export function encodingName(num) { diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/inflator.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/inflator.js index 0eab8fe4..4b337607 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/inflator.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/inflator.js @@ -1,3 +1,11 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC Authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + import { inflateInit, inflate, inflateReset } from "../vendor/pako/lib/zlib/inflate.js"; import ZStream from "../vendor/pako/lib/zlib/zstream.js"; @@ -11,12 +19,22 @@ export default class Inflate { inflateInit(this.strm, this.windowBits); } - inflate(data, flush, expected) { - this.strm.input = data; - this.strm.avail_in = this.strm.input.length; - this.strm.next_in = 0; - this.strm.next_out = 0; + setInput(data) { + if (!data) { + //FIXME: flush remaining data. + /* eslint-disable camelcase */ + this.strm.input = null; + this.strm.avail_in = 0; + this.strm.next_in = 0; + } else { + this.strm.input = data; + this.strm.avail_in = this.strm.input.length; + this.strm.next_in = 0; + /* eslint-enable camelcase */ + } + } + inflate(expected) { // resize our output buffer if it's too small // (we could just use multiple chunks, but that would cause an extra // allocation each time to flatten the chunks) @@ -25,9 +43,19 @@ export default class Inflate { this.strm.output = new Uint8Array(this.chunkSize); } - this.strm.avail_out = this.chunkSize; + /* eslint-disable camelcase */ + this.strm.next_out = 0; + this.strm.avail_out = expected; + /* eslint-enable camelcase */ + + let ret = inflate(this.strm, 0); // Flush argument not used. + if (ret < 0) { + throw new Error("zlib inflate failed"); + } - inflate(this.strm, flush); + if (this.strm.next_out != expected) { + throw new Error("Incomplete zlib block"); + } return new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out); } diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/domkeytable.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/domkeytable.js index 60ae3f91..b84ad45d 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/domkeytable.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/domkeytable.js @@ -43,12 +43,10 @@ addStandard("CapsLock", KeyTable.XK_Caps_Lock); addLeftRight("Control", KeyTable.XK_Control_L, KeyTable.XK_Control_R); // - Fn // - FnLock -addLeftRight("Hyper", KeyTable.XK_Super_L, KeyTable.XK_Super_R); addLeftRight("Meta", KeyTable.XK_Super_L, KeyTable.XK_Super_R); addStandard("NumLock", KeyTable.XK_Num_Lock); addStandard("ScrollLock", KeyTable.XK_Scroll_Lock); addLeftRight("Shift", KeyTable.XK_Shift_L, KeyTable.XK_Shift_R); -addLeftRight("Super", KeyTable.XK_Super_L, KeyTable.XK_Super_R); // - Symbol // - SymbolLock @@ -72,6 +70,9 @@ addNumpad("PageUp", KeyTable.XK_Prior, KeyTable.XK_KP_Prior); // 2.5. Editing Keys addStandard("Backspace", KeyTable.XK_BackSpace); +// Browsers send "Clear" for the numpad 5 without NumLock because +// Windows uses VK_Clear for that key. But Unix expects KP_Begin for +// that scenario. addNumpad("Clear", KeyTable.XK_Clear, KeyTable.XK_KP_Begin); addStandard("Copy", KeyTable.XF86XK_Copy); // - CrSel @@ -194,7 +195,8 @@ addStandard("F35", KeyTable.XK_F35); addStandard("Close", KeyTable.XF86XK_Close); addStandard("MailForward", KeyTable.XF86XK_MailForward); addStandard("MailReply", KeyTable.XF86XK_Reply); -addStandard("MainSend", KeyTable.XF86XK_Send); +addStandard("MailSend", KeyTable.XF86XK_Send); +// - MediaClose addStandard("MediaFastForward", KeyTable.XF86XK_AudioForward); addStandard("MediaPause", KeyTable.XF86XK_AudioPause); addStandard("MediaPlay", KeyTable.XF86XK_AudioPlay); @@ -218,11 +220,9 @@ addStandard("SpellCheck", KeyTable.XF86XK_Spell); // - AudioBalanceLeft // - AudioBalanceRight -// - AudioBassDown // - AudioBassBoostDown // - AudioBassBoostToggle // - AudioBassBoostUp -// - AudioBassUp // - AudioFaderFront // - AudioFaderRear // - AudioSurroundModeNext @@ -243,12 +243,12 @@ addStandard("MicrophoneVolumeMute", KeyTable.XF86XK_AudioMicMute); // 2.14. Application Keys -addStandard("LaunchCalculator", KeyTable.XF86XK_Calculator); +addStandard("LaunchApplication1", KeyTable.XF86XK_MyComputer); +addStandard("LaunchApplication2", KeyTable.XF86XK_Calculator); addStandard("LaunchCalendar", KeyTable.XF86XK_Calendar); addStandard("LaunchMail", KeyTable.XF86XK_Mail); addStandard("LaunchMediaPlayer", KeyTable.XF86XK_AudioMedia); addStandard("LaunchMusicPlayer", KeyTable.XF86XK_Music); -addStandard("LaunchMyComputer", KeyTable.XF86XK_MyComputer); addStandard("LaunchPhone", KeyTable.XF86XK_Phone); addStandard("LaunchScreenSaver", KeyTable.XF86XK_ScreenSaver); addStandard("LaunchSpreadsheet", KeyTable.XF86XK_Excel); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/gesturehandler.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/gesturehandler.js new file mode 100644 index 00000000..6fa72d2a --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/gesturehandler.js @@ -0,0 +1,567 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC Authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + * + */ + +const GH_NOGESTURE = 0; +const GH_ONETAP = 1; +const GH_TWOTAP = 2; +const GH_THREETAP = 4; +const GH_DRAG = 8; +const GH_LONGPRESS = 16; +const GH_TWODRAG = 32; +const GH_PINCH = 64; + +const GH_INITSTATE = 127; + +const GH_MOVE_THRESHOLD = 50; +const GH_ANGLE_THRESHOLD = 90; // Degrees + +// Timeout when waiting for gestures (ms) +const GH_MULTITOUCH_TIMEOUT = 250; + +// Maximum time between press and release for a tap (ms) +const GH_TAP_TIMEOUT = 1000; + +// Timeout when waiting for longpress (ms) +const GH_LONGPRESS_TIMEOUT = 1000; + +// Timeout when waiting to decide between PINCH and TWODRAG (ms) +const GH_TWOTOUCH_TIMEOUT = 50; + +export default class GestureHandler { + constructor() { + this._target = null; + + this._state = GH_INITSTATE; + + this._tracked = []; + this._ignored = []; + + this._waitingRelease = false; + this._releaseStart = 0.0; + + this._longpressTimeoutId = null; + this._twoTouchTimeoutId = null; + + this._boundEventHandler = this._eventHandler.bind(this); + } + + attach(target) { + this.detach(); + + this._target = target; + this._target.addEventListener('touchstart', + this._boundEventHandler); + this._target.addEventListener('touchmove', + this._boundEventHandler); + this._target.addEventListener('touchend', + this._boundEventHandler); + this._target.addEventListener('touchcancel', + this._boundEventHandler); + } + + detach() { + if (!this._target) { + return; + } + + this._stopLongpressTimeout(); + this._stopTwoTouchTimeout(); + + this._target.removeEventListener('touchstart', + this._boundEventHandler); + this._target.removeEventListener('touchmove', + this._boundEventHandler); + this._target.removeEventListener('touchend', + this._boundEventHandler); + this._target.removeEventListener('touchcancel', + this._boundEventHandler); + this._target = null; + } + + _eventHandler(e) { + let fn; + + e.stopPropagation(); + e.preventDefault(); + + switch (e.type) { + case 'touchstart': + fn = this._touchStart; + break; + case 'touchmove': + fn = this._touchMove; + break; + case 'touchend': + case 'touchcancel': + fn = this._touchEnd; + break; + } + + for (let i = 0; i < e.changedTouches.length; i++) { + let touch = e.changedTouches[i]; + fn.call(this, touch.identifier, touch.clientX, touch.clientY); + } + } + + _touchStart(id, x, y) { + // Ignore any new touches if there is already an active gesture, + // or we're in a cleanup state + if (this._hasDetectedGesture() || (this._state === GH_NOGESTURE)) { + this._ignored.push(id); + return; + } + + // Did it take too long between touches that we should no longer + // consider this a single gesture? + if ((this._tracked.length > 0) && + ((Date.now() - this._tracked[0].started) > GH_MULTITOUCH_TIMEOUT)) { + this._state = GH_NOGESTURE; + this._ignored.push(id); + return; + } + + // If we're waiting for fingers to release then we should no longer + // recognize new touches + if (this._waitingRelease) { + this._state = GH_NOGESTURE; + this._ignored.push(id); + return; + } + + this._tracked.push({ + id: id, + started: Date.now(), + active: true, + firstX: x, + firstY: y, + lastX: x, + lastY: y, + angle: 0 + }); + + switch (this._tracked.length) { + case 1: + this._startLongpressTimeout(); + break; + + case 2: + this._state &= ~(GH_ONETAP | GH_DRAG | GH_LONGPRESS); + this._stopLongpressTimeout(); + break; + + case 3: + this._state &= ~(GH_TWOTAP | GH_TWODRAG | GH_PINCH); + break; + + default: + this._state = GH_NOGESTURE; + } + } + + _touchMove(id, x, y) { + let touch = this._tracked.find(t => t.id === id); + + // If this is an update for a touch we're not tracking, ignore it + if (touch === undefined) { + return; + } + + // Update the touches last position with the event coordinates + touch.lastX = x; + touch.lastY = y; + + let deltaX = x - touch.firstX; + let deltaY = y - touch.firstY; + + // Update angle when the touch has moved + if ((touch.firstX !== touch.lastX) || + (touch.firstY !== touch.lastY)) { + touch.angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI; + } + + if (!this._hasDetectedGesture()) { + // Ignore moves smaller than the minimum threshold + if (Math.hypot(deltaX, deltaY) < GH_MOVE_THRESHOLD) { + return; + } + + // Can't be a tap or long press as we've seen movement + this._state &= ~(GH_ONETAP | GH_TWOTAP | GH_THREETAP | GH_LONGPRESS); + this._stopLongpressTimeout(); + + if (this._tracked.length !== 1) { + this._state &= ~(GH_DRAG); + } + if (this._tracked.length !== 2) { + this._state &= ~(GH_TWODRAG | GH_PINCH); + } + + // We need to figure out which of our different two touch gestures + // this might be + if (this._tracked.length === 2) { + + // The other touch is the one where the id doesn't match + let prevTouch = this._tracked.find(t => t.id !== id); + + // How far the previous touch point has moved since start + let prevDeltaMove = Math.hypot(prevTouch.firstX - prevTouch.lastX, + prevTouch.firstY - prevTouch.lastY); + + // We know that the current touch moved far enough, + // but unless both touches moved further than their + // threshold we don't want to disqualify any gestures + if (prevDeltaMove > GH_MOVE_THRESHOLD) { + + // The angle difference between the direction of the touch points + let deltaAngle = Math.abs(touch.angle - prevTouch.angle); + deltaAngle = Math.abs(((deltaAngle + 180) % 360) - 180); + + // PINCH or TWODRAG can be eliminated depending on the angle + if (deltaAngle > GH_ANGLE_THRESHOLD) { + this._state &= ~GH_TWODRAG; + } else { + this._state &= ~GH_PINCH; + } + + if (this._isTwoTouchTimeoutRunning()) { + this._stopTwoTouchTimeout(); + } + } else if (!this._isTwoTouchTimeoutRunning()) { + // We can't determine the gesture right now, let's + // wait and see if more events are on their way + this._startTwoTouchTimeout(); + } + } + + if (!this._hasDetectedGesture()) { + return; + } + + this._pushEvent('gesturestart'); + } + + this._pushEvent('gesturemove'); + } + + _touchEnd(id, x, y) { + // Check if this is an ignored touch + if (this._ignored.indexOf(id) !== -1) { + // Remove this touch from ignored + this._ignored.splice(this._ignored.indexOf(id), 1); + + // And reset the state if there are no more touches + if ((this._ignored.length === 0) && + (this._tracked.length === 0)) { + this._state = GH_INITSTATE; + this._waitingRelease = false; + } + return; + } + + // We got a touchend before the timer triggered, + // this cannot result in a gesture anymore. + if (!this._hasDetectedGesture() && + this._isTwoTouchTimeoutRunning()) { + this._stopTwoTouchTimeout(); + this._state = GH_NOGESTURE; + } + + // Some gestures don't trigger until a touch is released + if (!this._hasDetectedGesture()) { + // Can't be a gesture that relies on movement + this._state &= ~(GH_DRAG | GH_TWODRAG | GH_PINCH); + // Or something that relies on more time + this._state &= ~GH_LONGPRESS; + this._stopLongpressTimeout(); + + if (!this._waitingRelease) { + this._releaseStart = Date.now(); + this._waitingRelease = true; + + // Can't be a tap that requires more touches than we current have + switch (this._tracked.length) { + case 1: + this._state &= ~(GH_TWOTAP | GH_THREETAP); + break; + + case 2: + this._state &= ~(GH_ONETAP | GH_THREETAP); + break; + } + } + } + + // Waiting for all touches to release? (i.e. some tap) + if (this._waitingRelease) { + // Were all touches released at roughly the same time? + if ((Date.now() - this._releaseStart) > GH_MULTITOUCH_TIMEOUT) { + this._state = GH_NOGESTURE; + } + + // Did too long time pass between press and release? + if (this._tracked.some(t => (Date.now() - t.started) > GH_TAP_TIMEOUT)) { + this._state = GH_NOGESTURE; + } + + let touch = this._tracked.find(t => t.id === id); + touch.active = false; + + // Are we still waiting for more releases? + if (this._hasDetectedGesture()) { + this._pushEvent('gesturestart'); + } else { + // Have we reached a dead end? + if (this._state !== GH_NOGESTURE) { + return; + } + } + } + + if (this._hasDetectedGesture()) { + this._pushEvent('gestureend'); + } + + // Ignore any remaining touches until they are ended + for (let i = 0; i < this._tracked.length; i++) { + if (this._tracked[i].active) { + this._ignored.push(this._tracked[i].id); + } + } + this._tracked = []; + + this._state = GH_NOGESTURE; + + // Remove this touch from ignored if it's in there + if (this._ignored.indexOf(id) !== -1) { + this._ignored.splice(this._ignored.indexOf(id), 1); + } + + // We reset the state if ignored is empty + if ((this._ignored.length === 0)) { + this._state = GH_INITSTATE; + this._waitingRelease = false; + } + } + + _hasDetectedGesture() { + if (this._state === GH_NOGESTURE) { + return false; + } + // Check to see if the bitmask value is a power of 2 + // (i.e. only one bit set). If it is, we have a state. + if (this._state & (this._state - 1)) { + return false; + } + + // For taps we also need to have all touches released + // before we've fully detected the gesture + if (this._state & (GH_ONETAP | GH_TWOTAP | GH_THREETAP)) { + if (this._tracked.some(t => t.active)) { + return false; + } + } + + return true; + } + + _startLongpressTimeout() { + this._stopLongpressTimeout(); + this._longpressTimeoutId = setTimeout(() => this._longpressTimeout(), + GH_LONGPRESS_TIMEOUT); + } + + _stopLongpressTimeout() { + clearTimeout(this._longpressTimeoutId); + this._longpressTimeoutId = null; + } + + _longpressTimeout() { + if (this._hasDetectedGesture()) { + throw new Error("A longpress gesture failed, conflict with a different gesture"); + } + + this._state = GH_LONGPRESS; + this._pushEvent('gesturestart'); + } + + _startTwoTouchTimeout() { + this._stopTwoTouchTimeout(); + this._twoTouchTimeoutId = setTimeout(() => this._twoTouchTimeout(), + GH_TWOTOUCH_TIMEOUT); + } + + _stopTwoTouchTimeout() { + clearTimeout(this._twoTouchTimeoutId); + this._twoTouchTimeoutId = null; + } + + _isTwoTouchTimeoutRunning() { + return this._twoTouchTimeoutId !== null; + } + + _twoTouchTimeout() { + if (this._tracked.length === 0) { + throw new Error("A pinch or two drag gesture failed, no tracked touches"); + } + + // How far each touch point has moved since start + let avgM = this._getAverageMovement(); + let avgMoveH = Math.abs(avgM.x); + let avgMoveV = Math.abs(avgM.y); + + // The difference in the distance between where + // the touch points started and where they are now + let avgD = this._getAverageDistance(); + let deltaTouchDistance = Math.abs(Math.hypot(avgD.first.x, avgD.first.y) - + Math.hypot(avgD.last.x, avgD.last.y)); + + if ((avgMoveV < deltaTouchDistance) && + (avgMoveH < deltaTouchDistance)) { + this._state = GH_PINCH; + } else { + this._state = GH_TWODRAG; + } + + this._pushEvent('gesturestart'); + this._pushEvent('gesturemove'); + } + + _pushEvent(type) { + let detail = { type: this._stateToGesture(this._state) }; + + // For most gesture events the current (average) position is the + // most useful + let avg = this._getPosition(); + let pos = avg.last; + + // However we have a slight distance to detect gestures, so for the + // first gesture event we want to use the first positions we saw + if (type === 'gesturestart') { + pos = avg.first; + } + + // For these gestures, we always want the event coordinates + // to be where the gesture began, not the current touch location. + switch (this._state) { + case GH_TWODRAG: + case GH_PINCH: + pos = avg.first; + break; + } + + detail['clientX'] = pos.x; + detail['clientY'] = pos.y; + + // FIXME: other coordinates? + + // Some gestures also have a magnitude + if (this._state === GH_PINCH) { + let distance = this._getAverageDistance(); + if (type === 'gesturestart') { + detail['magnitudeX'] = distance.first.x; + detail['magnitudeY'] = distance.first.y; + } else { + detail['magnitudeX'] = distance.last.x; + detail['magnitudeY'] = distance.last.y; + } + } else if (this._state === GH_TWODRAG) { + if (type === 'gesturestart') { + detail['magnitudeX'] = 0.0; + detail['magnitudeY'] = 0.0; + } else { + let movement = this._getAverageMovement(); + detail['magnitudeX'] = movement.x; + detail['magnitudeY'] = movement.y; + } + } + + let gev = new CustomEvent(type, { detail: detail }); + this._target.dispatchEvent(gev); + } + + _stateToGesture(state) { + switch (state) { + case GH_ONETAP: + return 'onetap'; + case GH_TWOTAP: + return 'twotap'; + case GH_THREETAP: + return 'threetap'; + case GH_DRAG: + return 'drag'; + case GH_LONGPRESS: + return 'longpress'; + case GH_TWODRAG: + return 'twodrag'; + case GH_PINCH: + return 'pinch'; + } + + throw new Error("Unknown gesture state: " + state); + } + + _getPosition() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture position, no tracked touches"); + } + + let size = this._tracked.length; + let fx = 0, fy = 0, lx = 0, ly = 0; + + for (let i = 0; i < this._tracked.length; i++) { + fx += this._tracked[i].firstX; + fy += this._tracked[i].firstY; + lx += this._tracked[i].lastX; + ly += this._tracked[i].lastY; + } + + return { first: { x: fx / size, + y: fy / size }, + last: { x: lx / size, + y: ly / size } }; + } + + _getAverageMovement() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture movement, no tracked touches"); + } + + let totalH, totalV; + totalH = totalV = 0; + let size = this._tracked.length; + + for (let i = 0; i < this._tracked.length; i++) { + totalH += this._tracked[i].lastX - this._tracked[i].firstX; + totalV += this._tracked[i].lastY - this._tracked[i].firstY; + } + + return { x: totalH / size, + y: totalV / size }; + } + + _getAverageDistance() { + if (this._tracked.length === 0) { + throw new Error("Failed to get gesture distance, no tracked touches"); + } + + // Distance between the first and last tracked touches + + let first = this._tracked[0]; + let last = this._tracked[this._tracked.length - 1]; + + let fdx = Math.abs(last.firstX - first.firstX); + let fdy = Math.abs(last.firstY - first.firstY); + + let ldx = Math.abs(last.lastX - first.lastX); + let ldy = Math.abs(last.lastY - first.lastY); + + return { first: { x: fdx, y: fdy }, + last: { x: ldx, y: ldy } }; + } +} diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/keyboard.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/keyboard.js index 9dbc8d6e..9e6af2ac 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/keyboard.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/keyboard.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 or any later version (see LICENSE.txt) */ @@ -118,9 +118,7 @@ export default class Keyboard { // We cannot handle keys we cannot track, but we also need // to deal with virtual keyboards which omit key info - // (iOS omits tracking info on keyup events, which forces us to - // special treat that platform here) - if ((code === 'Unidentified') || browser.isIOS()) { + if (code === 'Unidentified') { if (keysym) { // If it's a virtual keyboard then it should be // sufficient to just send press and release right @@ -137,7 +135,7 @@ export default class Keyboard { // keys around a bit to make things more sane for the remote // server. This method is used by RealVNC and TigerVNC (and // possibly others). - if (browser.isMac()) { + if (browser.isMac() || browser.isIOS()) { switch (keysym) { case KeyTable.XK_Super_L: keysym = KeyTable.XK_Alt_L; @@ -164,7 +162,7 @@ export default class Keyboard { // state change events. That gets extra confusing for CapsLock // which toggles on each press, but not on release. So pretend // it was a quick press and release of the button. - if (browser.isMac() && (code === 'CapsLock')) { + if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) { this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true); this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false); stopEvent(e); @@ -276,13 +274,28 @@ export default class Keyboard { } // See comment in _handleKeyDown() - if (browser.isMac() && (code === 'CapsLock')) { + if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) { this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true); this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false); return; } this._sendKeyEvent(this._keyDownList[code], code, false); + + // Windows has a rather nasty bug where it won't send key + // release events for a Shift button if the other Shift is still + // pressed + if (browser.isWindows() && ((code === 'ShiftLeft') || + (code === 'ShiftRight'))) { + if ('ShiftRight' in this._keyDownList) { + this._sendKeyEvent(this._keyDownList['ShiftRight'], + 'ShiftRight', false); + } + if ('ShiftLeft' in this._keyDownList) { + this._sendKeyEvent(this._keyDownList['ShiftLeft'], + 'ShiftLeft', false); + } + } } _handleAltGrTimeout() { @@ -299,8 +312,11 @@ export default class Keyboard { Log.Debug("<< Keyboard.allKeysUp"); } - // Firefox Alt workaround, see below + // Alt workaround for Firefox on Windows, see below _checkAlt(e) { + if (e.skipCheckAlt) { + return; + } if (e.altKey) { return; } @@ -315,6 +331,7 @@ export default class Keyboard { const event = new KeyboardEvent('keyup', { key: downList[code], code: code }); + event.skipCheckAlt = true; target.dispatchEvent(event); }); } @@ -331,9 +348,10 @@ export default class Keyboard { // Release (key up) if window loses focus window.addEventListener('blur', this._eventHandlers.blur); - // Firefox has broken handling of Alt, so we need to poll as - // best we can for releases (still doesn't prevent the menu - // from popping up though as we can't call preventDefault()) + // Firefox on Windows has broken handling of Alt, so we need to + // poll as best we can for releases (still doesn't prevent the + // menu from popping up though as we can't call + // preventDefault()) if (browser.isWindows() && browser.isFirefox()) { const handler = this._eventHandlers.checkalt; ['mousedown', 'mouseup', 'mousemove', 'wheel', diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/mouse.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/mouse.js deleted file mode 100644 index 58a2982a..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/mouse.js +++ /dev/null @@ -1,276 +0,0 @@ -/* - * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors - * Licensed under MPL 2.0 or any later version (see LICENSE.txt) - */ - -import * as Log from '../util/logging.js'; -import { isTouchDevice } from '../util/browser.js'; -import { setCapture, stopEvent, getPointerEvent } from '../util/events.js'; - -const WHEEL_STEP = 10; // Delta threshold for a mouse wheel step -const WHEEL_STEP_TIMEOUT = 50; // ms -const WHEEL_LINE_HEIGHT = 19; - -export default class Mouse { - constructor(target) { - this._target = target || document; - - this._doubleClickTimer = null; - this._lastTouchPos = null; - - this._pos = null; - this._wheelStepXTimer = null; - this._wheelStepYTimer = null; - this._accumulatedWheelDeltaX = 0; - this._accumulatedWheelDeltaY = 0; - - this._eventHandlers = { - 'mousedown': this._handleMouseDown.bind(this), - 'mouseup': this._handleMouseUp.bind(this), - 'mousemove': this._handleMouseMove.bind(this), - 'mousewheel': this._handleMouseWheel.bind(this), - 'mousedisable': this._handleMouseDisable.bind(this) - }; - - // ===== PROPERTIES ===== - - this.touchButton = 1; // Button mask (1, 2, 4) for touch devices (0 means ignore clicks) - - // ===== EVENT HANDLERS ===== - - this.onmousebutton = () => {}; // Handler for mouse button click/release - this.onmousemove = () => {}; // Handler for mouse movement - } - - // ===== PRIVATE METHODS ===== - - _resetDoubleClickTimer() { - this._doubleClickTimer = null; - } - - _handleMouseButton(e, down) { - this._updateMousePosition(e); - let pos = this._pos; - - let bmask; - if (e.touches || e.changedTouches) { - // Touch device - - // When two touches occur within 500 ms of each other and are - // close enough together a double click is triggered. - if (down == 1) { - if (this._doubleClickTimer === null) { - this._lastTouchPos = pos; - } else { - clearTimeout(this._doubleClickTimer); - - // When the distance between the two touches is small enough - // force the position of the latter touch to the position of - // the first. - - const xs = this._lastTouchPos.x - pos.x; - const ys = this._lastTouchPos.y - pos.y; - const d = Math.sqrt((xs * xs) + (ys * ys)); - - // The goal is to trigger on a certain physical width, the - // devicePixelRatio brings us a bit closer but is not optimal. - const threshold = 20 * (window.devicePixelRatio || 1); - if (d < threshold) { - pos = this._lastTouchPos; - } - } - this._doubleClickTimer = setTimeout(this._resetDoubleClickTimer.bind(this), 500); - } - bmask = this.touchButton; - // If bmask is set - } else if (e.which) { - /* everything except IE */ - bmask = 1 << e.button; - } else { - /* IE including 9 */ - bmask = (e.button & 0x1) + // Left - (e.button & 0x2) * 2 + // Right - (e.button & 0x4) / 2; // Middle - } - - Log.Debug("onmousebutton " + (down ? "down" : "up") + - ", x: " + pos.x + ", y: " + pos.y + ", bmask: " + bmask); - this.onmousebutton(pos.x, pos.y, down, bmask); - - stopEvent(e); - } - - _handleMouseDown(e) { - // Touch events have implicit capture - if (e.type === "mousedown") { - setCapture(this._target); - } - - this._handleMouseButton(e, 1); - } - - _handleMouseUp(e) { - this._handleMouseButton(e, 0); - } - - // Mouse wheel events are sent in steps over VNC. This means that the VNC - // protocol can't handle a wheel event with specific distance or speed. - // Therefor, if we get a lot of small mouse wheel events we combine them. - _generateWheelStepX() { - - if (this._accumulatedWheelDeltaX < 0) { - this.onmousebutton(this._pos.x, this._pos.y, 1, 1 << 5); - this.onmousebutton(this._pos.x, this._pos.y, 0, 1 << 5); - } else if (this._accumulatedWheelDeltaX > 0) { - this.onmousebutton(this._pos.x, this._pos.y, 1, 1 << 6); - this.onmousebutton(this._pos.x, this._pos.y, 0, 1 << 6); - } - - this._accumulatedWheelDeltaX = 0; - } - - _generateWheelStepY() { - - if (this._accumulatedWheelDeltaY < 0) { - this.onmousebutton(this._pos.x, this._pos.y, 1, 1 << 3); - this.onmousebutton(this._pos.x, this._pos.y, 0, 1 << 3); - } else if (this._accumulatedWheelDeltaY > 0) { - this.onmousebutton(this._pos.x, this._pos.y, 1, 1 << 4); - this.onmousebutton(this._pos.x, this._pos.y, 0, 1 << 4); - } - - this._accumulatedWheelDeltaY = 0; - } - - _resetWheelStepTimers() { - window.clearTimeout(this._wheelStepXTimer); - window.clearTimeout(this._wheelStepYTimer); - this._wheelStepXTimer = null; - this._wheelStepYTimer = null; - } - - _handleMouseWheel(e) { - this._resetWheelStepTimers(); - - this._updateMousePosition(e); - - let dX = e.deltaX; - let dY = e.deltaY; - - // Pixel units unless it's non-zero. - // Note that if deltamode is line or page won't matter since we aren't - // sending the mouse wheel delta to the server anyway. - // The difference between pixel and line can be important however since - // we have a threshold that can be smaller than the line height. - if (e.deltaMode !== 0) { - dX *= WHEEL_LINE_HEIGHT; - dY *= WHEEL_LINE_HEIGHT; - } - - this._accumulatedWheelDeltaX += dX; - this._accumulatedWheelDeltaY += dY; - - // Generate a mouse wheel step event when the accumulated delta - // for one of the axes is large enough. - // Small delta events that do not pass the threshold get sent - // after a timeout. - if (Math.abs(this._accumulatedWheelDeltaX) > WHEEL_STEP) { - this._generateWheelStepX(); - } else { - this._wheelStepXTimer = - window.setTimeout(this._generateWheelStepX.bind(this), - WHEEL_STEP_TIMEOUT); - } - if (Math.abs(this._accumulatedWheelDeltaY) > WHEEL_STEP) { - this._generateWheelStepY(); - } else { - this._wheelStepYTimer = - window.setTimeout(this._generateWheelStepY.bind(this), - WHEEL_STEP_TIMEOUT); - } - - stopEvent(e); - } - - _handleMouseMove(e) { - this._updateMousePosition(e); - this.onmousemove(this._pos.x, this._pos.y); - stopEvent(e); - } - - _handleMouseDisable(e) { - /* - * Stop propagation if inside canvas area - * Note: This is only needed for the 'click' event as it fails - * to fire properly for the target element so we have - * to listen on the document element instead. - */ - if (e.target == this._target) { - stopEvent(e); - } - } - - // Update coordinates relative to target - _updateMousePosition(e) { - e = getPointerEvent(e); - const bounds = this._target.getBoundingClientRect(); - let x; - let y; - // Clip to target bounds - if (e.clientX < bounds.left) { - x = 0; - } else if (e.clientX >= bounds.right) { - x = bounds.width - 1; - } else { - x = e.clientX - bounds.left; - } - if (e.clientY < bounds.top) { - y = 0; - } else if (e.clientY >= bounds.bottom) { - y = bounds.height - 1; - } else { - y = e.clientY - bounds.top; - } - this._pos = {x: x, y: y}; - } - - // ===== PUBLIC METHODS ===== - - grab() { - if (isTouchDevice) { - this._target.addEventListener('touchstart', this._eventHandlers.mousedown); - this._target.addEventListener('touchend', this._eventHandlers.mouseup); - this._target.addEventListener('touchmove', this._eventHandlers.mousemove); - } - this._target.addEventListener('mousedown', this._eventHandlers.mousedown); - this._target.addEventListener('mouseup', this._eventHandlers.mouseup); - this._target.addEventListener('mousemove', this._eventHandlers.mousemove); - this._target.addEventListener('wheel', this._eventHandlers.mousewheel); - - /* Prevent middle-click pasting (see above for why we bind to document) */ - document.addEventListener('click', this._eventHandlers.mousedisable); - - /* preventDefault() on mousedown doesn't stop this event for some - reason so we have to explicitly block it */ - this._target.addEventListener('contextmenu', this._eventHandlers.mousedisable); - } - - ungrab() { - this._resetWheelStepTimers(); - - if (isTouchDevice) { - this._target.removeEventListener('touchstart', this._eventHandlers.mousedown); - this._target.removeEventListener('touchend', this._eventHandlers.mouseup); - this._target.removeEventListener('touchmove', this._eventHandlers.mousemove); - } - this._target.removeEventListener('mousedown', this._eventHandlers.mousedown); - this._target.removeEventListener('mouseup', this._eventHandlers.mouseup); - this._target.removeEventListener('mousemove', this._eventHandlers.mousemove); - this._target.removeEventListener('wheel', this._eventHandlers.mousewheel); - - document.removeEventListener('click', this._eventHandlers.mousedisable); - - this._target.removeEventListener('contextmenu', this._eventHandlers.mousedisable); - } -} diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/util.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/util.js index f177ef53..1b98040b 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/input/util.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/input/util.js @@ -1,3 +1,4 @@ +import KeyTable from "./keysym.js"; import keysyms from "./keysymdef.js"; import vkeys from "./vkeys.js"; import fixedkeys from "./fixedkeys.js"; @@ -91,6 +92,8 @@ export function getKey(evt) { // Mozilla isn't fully in sync with the spec yet switch (evt.key) { case 'OS': return 'Meta'; + case 'LaunchMyComputer': return 'LaunchApplication1'; + case 'LaunchCalculator': return 'LaunchApplication2'; } // iOS leaks some OS names @@ -102,9 +105,21 @@ export function getKey(evt) { case 'UIKeyInputEscape': return 'Escape'; } - // IE and Edge have broken handling of AltGraph so we cannot - // trust them for printable characters - if ((evt.key.length !== 1) || (!browser.isIE() && !browser.isEdge())) { + // Broken behaviour in Chrome + if ((evt.key === '\x00') && (evt.code === 'NumpadDecimal')) { + return 'Delete'; + } + + // IE and Edge need special handling, but for everyone else we + // can trust the value provided + if (!browser.isIE() && !browser.isEdge()) { + return evt.key; + } + + // IE and Edge have broken handling of AltGraph so we can only + // trust them for non-printable characters (and unfortunately + // they also specify 'Unidentified' for some problem keys) + if ((evt.key.length !== 1) && (evt.key !== 'Unidentified')) { return evt.key; } } @@ -141,10 +156,39 @@ export function getKeysym(evt) { location = 2; } + // And for Clear + if ((key === 'Clear') && (location === 3)) { + let code = getKeycode(evt); + if (code === 'NumLock') { + location = 0; + } + } + if ((location === undefined) || (location > 3)) { location = 0; } + // The original Meta key now gets confused with the Windows key + // https://bugs.chromium.org/p/chromium/issues/detail?id=1020141 + // https://bugzilla.mozilla.org/show_bug.cgi?id=1232918 + if (key === 'Meta') { + let code = getKeycode(evt); + if (code === 'AltLeft') { + return KeyTable.XK_Meta_L; + } else if (code === 'AltRight') { + return KeyTable.XK_Meta_R; + } + } + + // macOS has Clear instead of NumLock, but the remote system is + // probably not macOS, so lying here is probably best... + if (key === 'Clear') { + let code = getKeycode(evt); + if (code === 'NumLock') { + return KeyTable.XK_Num_Lock; + } + } + return DOMKeyTable[key][location]; } diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/rfb.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/rfb.js index 89b8130d..f35d503f 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/rfb.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/rfb.js @@ -1,19 +1,24 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2020 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. * */ +import { toUnsigned32bit, toSigned32bit } from './util/int.js'; import * as Log from './util/logging.js'; -import { decodeUTF8 } from './util/strings.js'; +import { encodeUTF8, decodeUTF8 } from './util/strings.js'; import { dragThreshold } from './util/browser.js'; +import { clientToElement } from './util/element.js'; +import { setCapture } from './util/events.js'; import EventTargetMixin from './util/eventtarget.js'; import Display from "./display.js"; +import Inflator from "./inflator.js"; +import Deflator from "./deflator.js"; import Keyboard from "./input/keyboard.js"; -import Mouse from "./input/mouse.js"; +import GestureHandler from "./input/gesturehandler.js"; import Cursor from "./util/cursor.js"; import Websock from "./websock.js"; import DES from "./des.js"; @@ -33,6 +38,36 @@ import TightPNGDecoder from "./decoders/tightpng.js"; const DISCONNECT_TIMEOUT = 3; const DEFAULT_BACKGROUND = 'rgb(40, 40, 40)'; +// Minimum wait (ms) between two mouse moves +const MOUSE_MOVE_DELAY = 17; + +// Wheel thresholds +const WHEEL_STEP = 50; // Pixels needed for one step +const WHEEL_LINE_HEIGHT = 19; // Assumed pixels for one line step + +// Gesture thresholds +const GESTURE_ZOOMSENS = 75; +const GESTURE_SCRLSENS = 50; +const DOUBLE_TAP_TIMEOUT = 1000; +const DOUBLE_TAP_THRESHOLD = 50; + +// Extended clipboard pseudo-encoding formats +const extendedClipboardFormatText = 1; +/*eslint-disable no-unused-vars */ +const extendedClipboardFormatRtf = 1 << 1; +const extendedClipboardFormatHtml = 1 << 2; +const extendedClipboardFormatDib = 1 << 3; +const extendedClipboardFormatFiles = 1 << 4; +/*eslint-enable */ + +// Extended clipboard pseudo-encoding actions +const extendedClipboardActionCaps = 1 << 24; +const extendedClipboardActionRequest = 1 << 25; +const extendedClipboardActionPeek = 1 << 26; +const extendedClipboardActionNotify = 1 << 27; +const extendedClipboardActionProvide = 1 << 28; + + export default class RFB extends EventTargetMixin { constructor(target, url, options) { if (!target) { @@ -49,27 +84,28 @@ export default class RFB extends EventTargetMixin { // Connection details options = options || {}; - this._rfb_credentials = options.credentials || {}; + this._rfbCredentials = options.credentials || {}; this._shared = 'shared' in options ? !!options.shared : true; this._repeaterID = options.repeaterID || ''; - this._showDotCursor = options.showDotCursor || false; + this._wsProtocols = options.wsProtocols || []; // Internal state - this._rfb_connection_state = ''; - this._rfb_init_state = ''; - this._rfb_auth_scheme = -1; - this._rfb_clean_disconnect = true; + this._rfbConnectionState = ''; + this._rfbInitState = ''; + this._rfbAuthScheme = -1; + this._rfbCleanDisconnect = true; // Server capabilities - this._rfb_version = 0; - this._rfb_max_version = 3.8; - this._rfb_tightvnc = false; - this._rfb_xvp_ver = 0; + this._rfbVersion = 0; + this._rfbMaxVersion = 3.8; + this._rfbTightVNC = false; + this._rfbVeNCryptState = 0; + this._rfbXvpVer = 0; - this._fb_width = 0; - this._fb_height = 0; + this._fbWidth = 0; + this._fbHeight = 0; - this._fb_name = ""; + this._fbName = ""; this._capabilities = { power: false }; @@ -79,21 +115,26 @@ export default class RFB extends EventTargetMixin { this._enabledContinuousUpdates = false; this._supportsSetDesktopSize = false; - this._screen_id = 0; - this._screen_flags = 0; + this._screenID = 0; + this._screenFlags = 0; this._qemuExtKeyEventSupported = false; + this._clipboardText = null; + this._clipboardServerCapabilitiesActions = {}; + this._clipboardServerCapabilitiesFormats = {}; + // Internal objects this._sock = null; // Websock object this._display = null; // Display object this._flushing = false; // Display flushing state this._keyboard = null; // Keyboard input handler object - this._mouse = null; // Mouse input handler object + this._gestures = null; // Gesture input handler object // Timers this._disconnTimer = null; // disconnection timer this._resizeTimeout = null; // resize rate limiting + this._mouseMoveTimer = null; // Decoder states this._decoders = {}; @@ -108,16 +149,28 @@ export default class RFB extends EventTargetMixin { }; // Mouse state - this._mouse_buttonMask = 0; - this._mouse_arr = []; + this._mousePos = {}; + this._mouseButtonMask = 0; + this._mouseLastMoveTime = 0; this._viewportDragging = false; this._viewportDragPos = {}; this._viewportHasMoved = false; + this._accumulatedWheelDeltaX = 0; + this._accumulatedWheelDeltaY = 0; + + // Gesture state + this._gestureLastTapTime = null; + this._gestureFirstDoubleTapEv = null; + this._gestureLastMagnitudeX = 0; + this._gestureLastMagnitudeY = 0; // Bound event handlers this._eventHandlers = { focusCanvas: this._focusCanvas.bind(this), windowResize: this._windowResize.bind(this), + handleMouse: this._handleMouse.bind(this), + handleWheel: this._handleWheel.bind(this), + handleGesture: this._handleGesture.bind(this), }; // main setup @@ -172,27 +225,24 @@ export default class RFB extends EventTargetMixin { throw exc; } this._display.onflush = this._onFlush.bind(this); - this._display.clear(); this._keyboard = new Keyboard(this._canvas); this._keyboard.onkeyevent = this._handleKeyEvent.bind(this); - this._mouse = new Mouse(this._canvas); - this._mouse.onmousebutton = this._handleMouseButton.bind(this); - this._mouse.onmousemove = this._handleMouseMove.bind(this); + this._gestures = new GestureHandler(); this._sock = new Websock(); this._sock.on('message', () => { - this._handle_message(); + this._handleMessage(); }); this._sock.on('open', () => { - if ((this._rfb_connection_state === 'connecting') && - (this._rfb_init_state === '')) { - this._rfb_init_state = 'ProtocolVersion'; + if ((this._rfbConnectionState === 'connecting') && + (this._rfbInitState === '')) { + this._rfbInitState = 'ProtocolVersion'; Log.Debug("Starting VNC handshake"); } else { this._fail("Unexpected server connection while " + - this._rfb_connection_state); + this._rfbConnectionState); } }); this._sock.on('close', (e) => { @@ -205,7 +255,7 @@ export default class RFB extends EventTargetMixin { } msg += ")"; } - switch (this._rfb_connection_state) { + switch (this._rfbConnectionState) { case 'connecting': this._fail("Connection closed " + msg); break; @@ -246,6 +296,15 @@ export default class RFB extends EventTargetMixin { this._clipViewport = false; this._scaleViewport = false; this._resizeSession = false; + + this._showDotCursor = false; + if (options.showDotCursor !== undefined) { + Log.Warn("Specifying showDotCursor as a RFB constructor argument is deprecated"); + this._showDotCursor = options.showDotCursor; + } + + this._qualityLevel = 6; + this._compressionLevel = 2; } // ===== PROPERTIES ===== @@ -254,22 +313,20 @@ export default class RFB extends EventTargetMixin { set viewOnly(viewOnly) { this._viewOnly = viewOnly; - if (this._rfb_connection_state === "connecting" || - this._rfb_connection_state === "connected") { + if (this._rfbConnectionState === "connecting" || + this._rfbConnectionState === "connected") { if (viewOnly) { this._keyboard.ungrab(); - this._mouse.ungrab(); } else { this._keyboard.grab(); - this._mouse.grab(); } } } get capabilities() { return this._capabilities; } - get touchButton() { return this._mouse.touchButton; } - set touchButton(button) { this._mouse.touchButton = button; } + get touchButton() { return 0; } + set touchButton(button) { Log.Warn("Using old API!"); } get clipViewport() { return this._clipViewport; } set clipViewport(viewport) { @@ -308,6 +365,46 @@ export default class RFB extends EventTargetMixin { get background() { return this._screen.style.background; } set background(cssValue) { this._screen.style.background = cssValue; } + get qualityLevel() { + return this._qualityLevel; + } + set qualityLevel(qualityLevel) { + if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { + Log.Error("qualityLevel must be an integer between 0 and 9"); + return; + } + + if (this._qualityLevel === qualityLevel) { + return; + } + + this._qualityLevel = qualityLevel; + + if (this._rfbConnectionState === 'connected') { + this._sendEncodings(); + } + } + + get compressionLevel() { + return this._compressionLevel; + } + set compressionLevel(compressionLevel) { + if (!Number.isInteger(compressionLevel) || compressionLevel < 0 || compressionLevel > 9) { + Log.Error("compressionLevel must be an integer between 0 and 9"); + return; + } + + if (this._compressionLevel === compressionLevel) { + return; + } + + this._compressionLevel = compressionLevel; + + if (this._rfbConnectionState === 'connected') { + this._sendEncodings(); + } + } + // ===== PUBLIC METHODS ===== disconnect() { @@ -318,12 +415,12 @@ export default class RFB extends EventTargetMixin { } sendCredentials(creds) { - this._rfb_credentials = creds; - setTimeout(this._init_msg.bind(this), 0); + this._rfbCredentials = creds; + setTimeout(this._initMsg.bind(this), 0); } sendCtrlAltDel() { - if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; } + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } Log.Info("Sending Ctrl-Alt-Del"); this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true); @@ -349,7 +446,7 @@ export default class RFB extends EventTargetMixin { // Send a key press. If 'down' is not specified then send a down key // followed by an up key. sendKey(keysym, code, down) { - if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; } + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } if (down === undefined) { this.sendKey(keysym, code, true); @@ -384,8 +481,22 @@ export default class RFB extends EventTargetMixin { } clipboardPasteFrom(text) { - if (this._rfb_connection_state !== 'connected' || this._viewOnly) { return; } - RFB.messages.clientCutText(this._sock, text); + if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } + + if (this._clipboardServerCapabilitiesFormats[extendedClipboardFormatText] && + this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) { + + this._clipboardText = text; + RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]); + } else { + let data = new Uint8Array(text.length); + for (let i = 0; i < text.length; i++) { + // FIXME: text can have values outside of Latin1/Uint8 + data[i] = text.charCodeAt(i); + } + + RFB.messages.clientCutText(this._sock, data); + } } // ===== PRIVATE METHODS ===== @@ -397,7 +508,7 @@ export default class RFB extends EventTargetMixin { try { // WebSocket.onopen transitions to the RFB init states - this._sock.open(this._url, ['binary']); + this._sock.open(this._url, this._wsProtocols); } catch (e) { if (e.name === 'SyntaxError') { this._fail("Invalid host or port (" + e + ")"); @@ -409,6 +520,8 @@ export default class RFB extends EventTargetMixin { // Make our elements part of the page this._target.appendChild(this._screen); + this._gestures.attach(this._canvas); + this._cursor.attach(this._canvas); this._refreshCursor(); @@ -420,17 +533,44 @@ export default class RFB extends EventTargetMixin { this._canvas.addEventListener("mousedown", this._eventHandlers.focusCanvas); this._canvas.addEventListener("touchstart", this._eventHandlers.focusCanvas); + // Mouse events + this._canvas.addEventListener('mousedown', this._eventHandlers.handleMouse); + this._canvas.addEventListener('mouseup', this._eventHandlers.handleMouse); + this._canvas.addEventListener('mousemove', this._eventHandlers.handleMouse); + // Prevent middle-click pasting (see handler for why we bind to document) + this._canvas.addEventListener('click', this._eventHandlers.handleMouse); + // preventDefault() on mousedown doesn't stop this event for some + // reason so we have to explicitly block it + this._canvas.addEventListener('contextmenu', this._eventHandlers.handleMouse); + + // Wheel events + this._canvas.addEventListener("wheel", this._eventHandlers.handleWheel); + + // Gesture events + this._canvas.addEventListener("gesturestart", this._eventHandlers.handleGesture); + this._canvas.addEventListener("gesturemove", this._eventHandlers.handleGesture); + this._canvas.addEventListener("gestureend", this._eventHandlers.handleGesture); + Log.Debug("<< RFB.connect"); } _disconnect() { Log.Debug(">> RFB.disconnect"); this._cursor.detach(); + this._canvas.removeEventListener("gesturestart", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("gesturemove", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("gestureend", this._eventHandlers.handleGesture); + this._canvas.removeEventListener("wheel", this._eventHandlers.handleWheel); + this._canvas.removeEventListener('mousedown', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('mouseup', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('mousemove', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('click', this._eventHandlers.handleMouse); + this._canvas.removeEventListener('contextmenu', this._eventHandlers.handleMouse); this._canvas.removeEventListener("mousedown", this._eventHandlers.focusCanvas); this._canvas.removeEventListener("touchstart", this._eventHandlers.focusCanvas); window.removeEventListener('resize', this._eventHandlers.windowResize); this._keyboard.ungrab(); - this._mouse.ungrab(); + this._gestures.detach(); this._sock.close(); try { this._target.removeChild(this._screen); @@ -443,15 +583,11 @@ export default class RFB extends EventTargetMixin { } } clearTimeout(this._resizeTimeout); + clearTimeout(this._mouseMoveTimer); Log.Debug("<< RFB.disconnect"); } _focusCanvas(event) { - // Respect earlier handlers' request to not do side-effects - if (event.defaultPrevented) { - return; - } - if (!this.focusOnClick) { return; } @@ -459,6 +595,13 @@ export default class RFB extends EventTargetMixin { this.focus(); } + _setDesktopName(name) { + this._fbName = name; + this.dispatchEvent(new CustomEvent( + "desktopname", + { detail: { name: this._fbName } })); + } + _windowResize(event) { // If the window resized then our screen element might have // as well. Update the viewport dimensions. @@ -481,19 +624,19 @@ export default class RFB extends EventTargetMixin { // Update state of clipping in Display object, and make sure the // configured viewport matches the current screen size _updateClip() { - const cur_clip = this._display.clipViewport; - let new_clip = this._clipViewport; + const curClip = this._display.clipViewport; + let newClip = this._clipViewport; if (this._scaleViewport) { // Disable viewport clipping if we are scaling - new_clip = false; + newClip = false; } - if (cur_clip !== new_clip) { - this._display.clipViewport = new_clip; + if (curClip !== newClip) { + this._display.clipViewport = newClip; } - if (new_clip) { + if (newClip) { // When clipping is enabled, the screen is limited to // the size of the container. const size = this._screenSize(); @@ -526,7 +669,7 @@ export default class RFB extends EventTargetMixin { const size = this._screenSize(); RFB.messages.setDesktopSize(this._sock, Math.floor(size.w), Math.floor(size.h), - this._screen_id, this._screen_flags); + this._screenID, this._screenFlags); Log.Debug('Requested new desktop size: ' + size.w + 'x' + size.h); @@ -558,7 +701,7 @@ export default class RFB extends EventTargetMixin { * disconnected - permanent state */ _updateConnectionState(state) { - const oldstate = this._rfb_connection_state; + const oldstate = this._rfbConnectionState; if (state === oldstate) { Log.Debug("Already in state '" + state + "', ignoring"); @@ -612,7 +755,7 @@ export default class RFB extends EventTargetMixin { // State change actions - this._rfb_connection_state = state; + this._rfbConnectionState = state; Log.Debug("New state '" + state + "', was '" + oldstate + "'."); @@ -646,7 +789,7 @@ export default class RFB extends EventTargetMixin { case 'disconnected': this.dispatchEvent(new CustomEvent( "disconnect", { detail: - { clean: this._rfb_clean_disconnect } })); + { clean: this._rfbCleanDisconnect } })); break; } } @@ -657,7 +800,7 @@ export default class RFB extends EventTargetMixin { * should be logged but not sent to the user interface. */ _fail(details) { - switch (this._rfb_connection_state) { + switch (this._rfbConnectionState) { case 'disconnecting': Log.Error("Failed when disconnecting: " + details); break; @@ -671,7 +814,7 @@ export default class RFB extends EventTargetMixin { Log.Error("RFB failure: " + details); break; } - this._rfb_clean_disconnect = false; //This is sent to the UI + this._rfbCleanDisconnect = false; //This is sent to the UI // Transition to disconnected without waiting for socket to close this._updateConnectionState('disconnecting'); @@ -686,13 +829,13 @@ export default class RFB extends EventTargetMixin { { detail: { capabilities: this._capabilities } })); } - _handle_message() { + _handleMessage() { if (this._sock.rQlen === 0) { - Log.Warn("handle_message called on an empty receive queue"); + Log.Warn("handleMessage called on an empty receive queue"); return; } - switch (this._rfb_connection_state) { + switch (this._rfbConnectionState) { case 'disconnected': Log.Error("Got data while disconnected"); break; @@ -701,7 +844,7 @@ export default class RFB extends EventTargetMixin { if (this._flushing) { break; } - if (!this._normal_msg()) { + if (!this._normalMsg()) { break; } if (this._sock.rQlen === 0) { @@ -710,7 +853,7 @@ export default class RFB extends EventTargetMixin { } break; default: - this._init_msg(); + this._initMsg(); break; } } @@ -719,13 +862,52 @@ export default class RFB extends EventTargetMixin { this.sendKey(keysym, code, down); } - _handleMouseButton(x, y, down, bmask) { - if (down) { - this._mouse_buttonMask |= bmask; - } else { - this._mouse_buttonMask &= ~bmask; + _handleMouse(ev) { + /* + * We don't check connection status or viewOnly here as the + * mouse events might be used to control the viewport + */ + + if (ev.type === 'click') { + /* + * Note: This is only needed for the 'click' event as it fails + * to fire properly for the target element so we have + * to listen on the document element instead. + */ + if (ev.target !== this._canvas) { + return; + } + } + + // FIXME: if we're in view-only and not dragging, + // should we stop events? + ev.stopPropagation(); + ev.preventDefault(); + + if ((ev.type === 'click') || (ev.type === 'contextmenu')) { + return; + } + + let pos = clientToElement(ev.clientX, ev.clientY, + this._canvas); + + switch (ev.type) { + case 'mousedown': + setCapture(this._canvas); + this._handleMouseButton(pos.x, pos.y, + true, 1 << ev.button); + break; + case 'mouseup': + this._handleMouseButton(pos.x, pos.y, + false, 1 << ev.button); + break; + case 'mousemove': + this._handleMouseMove(pos.x, pos.y); + break; } + } + _handleMouseButton(x, y, down, bmask) { if (this.dragViewport) { if (down && !this._viewportDragging) { this._viewportDragging = true; @@ -746,17 +928,24 @@ export default class RFB extends EventTargetMixin { // Otherwise we treat this as a mouse click event. // Send the button down event here, as the button up // event is sent at the end of this function. - RFB.messages.pointerEvent(this._sock, - this._display.absX(x), - this._display.absY(y), - bmask); + this._sendMouse(x, y, bmask); } } - if (this._viewOnly) { return; } // View only, skip mouse events + // Flush waiting move event first + if (this._mouseMoveTimer !== null) { + clearTimeout(this._mouseMoveTimer); + this._mouseMoveTimer = null; + this._sendMouse(x, y, this._mouseButtonMask); + } - if (this._rfb_connection_state !== 'connected') { return; } - RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask); + if (down) { + this._mouseButtonMask |= bmask; + } else { + this._mouseButtonMask &= ~bmask; + } + + this._sendMouse(x, y, this._mouseButtonMask); } _handleMouseMove(x, y) { @@ -776,66 +965,304 @@ export default class RFB extends EventTargetMixin { return; } + this._mousePos = { 'x': x, 'y': y }; + + // Limit many mouse move events to one every MOUSE_MOVE_DELAY ms + if (this._mouseMoveTimer == null) { + + const timeSinceLastMove = Date.now() - this._mouseLastMoveTime; + if (timeSinceLastMove > MOUSE_MOVE_DELAY) { + this._sendMouse(x, y, this._mouseButtonMask); + this._mouseLastMoveTime = Date.now(); + } else { + // Too soon since the latest move, wait the remaining time + this._mouseMoveTimer = setTimeout(() => { + this._handleDelayedMouseMove(); + }, MOUSE_MOVE_DELAY - timeSinceLastMove); + } + } + } + + _handleDelayedMouseMove() { + this._mouseMoveTimer = null; + this._sendMouse(this._mousePos.x, this._mousePos.y, + this._mouseButtonMask); + this._mouseLastMoveTime = Date.now(); + } + + _sendMouse(x, y, mask) { + if (this._rfbConnectionState !== 'connected') { return; } + if (this._viewOnly) { return; } // View only, skip mouse events + + RFB.messages.pointerEvent(this._sock, this._display.absX(x), + this._display.absY(y), mask); + } + + _handleWheel(ev) { + if (this._rfbConnectionState !== 'connected') { return; } if (this._viewOnly) { return; } // View only, skip mouse events - if (this._rfb_connection_state !== 'connected') { return; } - RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask); + ev.stopPropagation(); + ev.preventDefault(); + + let pos = clientToElement(ev.clientX, ev.clientY, + this._canvas); + + let dX = ev.deltaX; + let dY = ev.deltaY; + + // Pixel units unless it's non-zero. + // Note that if deltamode is line or page won't matter since we aren't + // sending the mouse wheel delta to the server anyway. + // The difference between pixel and line can be important however since + // we have a threshold that can be smaller than the line height. + if (ev.deltaMode !== 0) { + dX *= WHEEL_LINE_HEIGHT; + dY *= WHEEL_LINE_HEIGHT; + } + + // Mouse wheel events are sent in steps over VNC. This means that the VNC + // protocol can't handle a wheel event with specific distance or speed. + // Therefor, if we get a lot of small mouse wheel events we combine them. + this._accumulatedWheelDeltaX += dX; + this._accumulatedWheelDeltaY += dY; + + // Generate a mouse wheel step event when the accumulated delta + // for one of the axes is large enough. + if (Math.abs(this._accumulatedWheelDeltaX) >= WHEEL_STEP) { + if (this._accumulatedWheelDeltaX < 0) { + this._handleMouseButton(pos.x, pos.y, true, 1 << 5); + this._handleMouseButton(pos.x, pos.y, false, 1 << 5); + } else if (this._accumulatedWheelDeltaX > 0) { + this._handleMouseButton(pos.x, pos.y, true, 1 << 6); + this._handleMouseButton(pos.x, pos.y, false, 1 << 6); + } + + this._accumulatedWheelDeltaX = 0; + } + if (Math.abs(this._accumulatedWheelDeltaY) >= WHEEL_STEP) { + if (this._accumulatedWheelDeltaY < 0) { + this._handleMouseButton(pos.x, pos.y, true, 1 << 3); + this._handleMouseButton(pos.x, pos.y, false, 1 << 3); + } else if (this._accumulatedWheelDeltaY > 0) { + this._handleMouseButton(pos.x, pos.y, true, 1 << 4); + this._handleMouseButton(pos.x, pos.y, false, 1 << 4); + } + + this._accumulatedWheelDeltaY = 0; + } + } + + _fakeMouseMove(ev, elementX, elementY) { + this._handleMouseMove(elementX, elementY); + this._cursor.move(ev.detail.clientX, ev.detail.clientY); + } + + _handleTapEvent(ev, bmask) { + let pos = clientToElement(ev.detail.clientX, ev.detail.clientY, + this._canvas); + + // If the user quickly taps multiple times we assume they meant to + // hit the same spot, so slightly adjust coordinates + + if ((this._gestureLastTapTime !== null) && + ((Date.now() - this._gestureLastTapTime) < DOUBLE_TAP_TIMEOUT) && + (this._gestureFirstDoubleTapEv.detail.type === ev.detail.type)) { + let dx = this._gestureFirstDoubleTapEv.detail.clientX - ev.detail.clientX; + let dy = this._gestureFirstDoubleTapEv.detail.clientY - ev.detail.clientY; + let distance = Math.hypot(dx, dy); + + if (distance < DOUBLE_TAP_THRESHOLD) { + pos = clientToElement(this._gestureFirstDoubleTapEv.detail.clientX, + this._gestureFirstDoubleTapEv.detail.clientY, + this._canvas); + } else { + this._gestureFirstDoubleTapEv = ev; + } + } else { + this._gestureFirstDoubleTapEv = ev; + } + this._gestureLastTapTime = Date.now(); + + this._fakeMouseMove(this._gestureFirstDoubleTapEv, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, true, bmask); + this._handleMouseButton(pos.x, pos.y, false, bmask); + } + + _handleGesture(ev) { + let magnitude; + + let pos = clientToElement(ev.detail.clientX, ev.detail.clientY, + this._canvas); + switch (ev.type) { + case 'gesturestart': + switch (ev.detail.type) { + case 'onetap': + this._handleTapEvent(ev, 0x1); + break; + case 'twotap': + this._handleTapEvent(ev, 0x4); + break; + case 'threetap': + this._handleTapEvent(ev, 0x2); + break; + case 'drag': + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, true, 0x1); + break; + case 'longpress': + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, true, 0x4); + break; + + case 'twodrag': + this._gestureLastMagnitudeX = ev.detail.magnitudeX; + this._gestureLastMagnitudeY = ev.detail.magnitudeY; + this._fakeMouseMove(ev, pos.x, pos.y); + break; + case 'pinch': + this._gestureLastMagnitudeX = Math.hypot(ev.detail.magnitudeX, + ev.detail.magnitudeY); + this._fakeMouseMove(ev, pos.x, pos.y); + break; + } + break; + + case 'gesturemove': + switch (ev.detail.type) { + case 'onetap': + case 'twotap': + case 'threetap': + break; + case 'drag': + case 'longpress': + this._fakeMouseMove(ev, pos.x, pos.y); + break; + case 'twodrag': + // Always scroll in the same position. + // We don't know if the mouse was moved so we need to move it + // every update. + this._fakeMouseMove(ev, pos.x, pos.y); + while ((ev.detail.magnitudeY - this._gestureLastMagnitudeY) > GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, true, 0x8); + this._handleMouseButton(pos.x, pos.y, false, 0x8); + this._gestureLastMagnitudeY += GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeY - this._gestureLastMagnitudeY) < -GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, true, 0x10); + this._handleMouseButton(pos.x, pos.y, false, 0x10); + this._gestureLastMagnitudeY -= GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeX - this._gestureLastMagnitudeX) > GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, true, 0x20); + this._handleMouseButton(pos.x, pos.y, false, 0x20); + this._gestureLastMagnitudeX += GESTURE_SCRLSENS; + } + while ((ev.detail.magnitudeX - this._gestureLastMagnitudeX) < -GESTURE_SCRLSENS) { + this._handleMouseButton(pos.x, pos.y, true, 0x40); + this._handleMouseButton(pos.x, pos.y, false, 0x40); + this._gestureLastMagnitudeX -= GESTURE_SCRLSENS; + } + break; + case 'pinch': + // Always scroll in the same position. + // We don't know if the mouse was moved so we need to move it + // every update. + this._fakeMouseMove(ev, pos.x, pos.y); + magnitude = Math.hypot(ev.detail.magnitudeX, ev.detail.magnitudeY); + if (Math.abs(magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) { + this._handleKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true); + while ((magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) { + this._handleMouseButton(pos.x, pos.y, true, 0x8); + this._handleMouseButton(pos.x, pos.y, false, 0x8); + this._gestureLastMagnitudeX += GESTURE_ZOOMSENS; + } + while ((magnitude - this._gestureLastMagnitudeX) < -GESTURE_ZOOMSENS) { + this._handleMouseButton(pos.x, pos.y, true, 0x10); + this._handleMouseButton(pos.x, pos.y, false, 0x10); + this._gestureLastMagnitudeX -= GESTURE_ZOOMSENS; + } + } + this._handleKeyEvent(KeyTable.XK_Control_L, "ControlLeft", false); + break; + } + break; + + case 'gestureend': + switch (ev.detail.type) { + case 'onetap': + case 'twotap': + case 'threetap': + case 'pinch': + case 'twodrag': + break; + case 'drag': + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, false, 0x1); + break; + case 'longpress': + this._fakeMouseMove(ev, pos.x, pos.y); + this._handleMouseButton(pos.x, pos.y, false, 0x4); + break; + } + break; + } } // Message Handlers - _negotiate_protocol_version() { + _negotiateProtocolVersion() { if (this._sock.rQwait("version", 12)) { return false; } const sversion = this._sock.rQshiftStr(12).substr(4, 7); Log.Info("Server ProtocolVersion: " + sversion); - let is_repeater = 0; + let isRepeater = 0; switch (sversion) { case "000.000": // UltraVNC repeater - is_repeater = 1; + isRepeater = 1; break; case "003.003": case "003.006": // UltraVNC case "003.889": // Apple Remote Desktop - this._rfb_version = 3.3; + this._rfbVersion = 3.3; break; case "003.007": - this._rfb_version = 3.7; + this._rfbVersion = 3.7; break; case "003.008": case "004.000": // Intel AMT KVM case "004.001": // RealVNC 4.6 case "005.000": // RealVNC 5.3 - this._rfb_version = 3.8; + this._rfbVersion = 3.8; break; default: return this._fail("Invalid server version " + sversion); } - if (is_repeater) { + if (isRepeater) { let repeaterID = "ID:" + this._repeaterID; while (repeaterID.length < 250) { repeaterID += "\0"; } - this._sock.send_string(repeaterID); + this._sock.sendString(repeaterID); return true; } - if (this._rfb_version > this._rfb_max_version) { - this._rfb_version = this._rfb_max_version; + if (this._rfbVersion > this._rfbMaxVersion) { + this._rfbVersion = this._rfbMaxVersion; } - const cversion = "00" + parseInt(this._rfb_version, 10) + - ".00" + ((this._rfb_version * 10) % 10); - this._sock.send_string("RFB " + cversion + "\n"); + const cversion = "00" + parseInt(this._rfbVersion, 10) + + ".00" + ((this._rfbVersion * 10) % 10); + this._sock.sendString("RFB " + cversion + "\n"); Log.Debug('Sent ProtocolVersion: ' + cversion); - this._rfb_init_state = 'Security'; + this._rfbInitState = 'Security'; } - _negotiate_security() { + _negotiateSecurity() { // Polyfill since IE and PhantomJS doesn't have // TypedArray.includes() function includes(item, array) { @@ -847,55 +1274,57 @@ export default class RFB extends EventTargetMixin { return false; } - if (this._rfb_version >= 3.7) { + if (this._rfbVersion >= 3.7) { // Server sends supported list, client decides - const num_types = this._sock.rQshift8(); - if (this._sock.rQwait("security type", num_types, 1)) { return false; } - - if (num_types === 0) { - this._rfb_init_state = "SecurityReason"; - this._security_context = "no security types"; - this._security_status = 1; - return this._init_msg(); + const numTypes = this._sock.rQshift8(); + if (this._sock.rQwait("security type", numTypes, 1)) { return false; } + + if (numTypes === 0) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "no security types"; + this._securityStatus = 1; + return this._initMsg(); } - const types = this._sock.rQshiftBytes(num_types); + const types = this._sock.rQshiftBytes(numTypes); Log.Debug("Server security types: " + types); // Look for each auth in preferred order if (includes(1, types)) { - this._rfb_auth_scheme = 1; // None + this._rfbAuthScheme = 1; // None } else if (includes(22, types)) { - this._rfb_auth_scheme = 22; // XVP + this._rfbAuthScheme = 22; // XVP } else if (includes(16, types)) { - this._rfb_auth_scheme = 16; // Tight + this._rfbAuthScheme = 16; // Tight } else if (includes(2, types)) { - this._rfb_auth_scheme = 2; // VNC Auth + this._rfbAuthScheme = 2; // VNC Auth + } else if (includes(19, types)) { + this._rfbAuthScheme = 19; // VeNCrypt Auth } else { return this._fail("Unsupported security types (types: " + types + ")"); } - this._sock.send([this._rfb_auth_scheme]); + this._sock.send([this._rfbAuthScheme]); } else { // Server decides if (this._sock.rQwait("security scheme", 4)) { return false; } - this._rfb_auth_scheme = this._sock.rQshift32(); + this._rfbAuthScheme = this._sock.rQshift32(); - if (this._rfb_auth_scheme == 0) { - this._rfb_init_state = "SecurityReason"; - this._security_context = "authentication scheme"; - this._security_status = 1; - return this._init_msg(); + if (this._rfbAuthScheme == 0) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "authentication scheme"; + this._securityStatus = 1; + return this._initMsg(); } } - this._rfb_init_state = 'Authentication'; - Log.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme); + this._rfbInitState = 'Authentication'; + Log.Debug('Authenticating using scheme: ' + this._rfbAuthScheme); - return this._init_msg(); // jump to authentication + return this._initMsg(); // jump to authentication } - _handle_security_reason() { + _handleSecurityReason() { if (this._sock.rQwait("reason length", 4)) { return false; } @@ -910,46 +1339,134 @@ export default class RFB extends EventTargetMixin { if (reason !== "") { this.dispatchEvent(new CustomEvent( "securityfailure", - { detail: { status: this._security_status, + { detail: { status: this._securityStatus, reason: reason } })); return this._fail("Security negotiation failed on " + - this._security_context + + this._securityContext + " (reason: " + reason + ")"); } else { this.dispatchEvent(new CustomEvent( "securityfailure", - { detail: { status: this._security_status } })); + { detail: { status: this._securityStatus } })); return this._fail("Security negotiation failed on " + - this._security_context); + this._securityContext); } } // authentication - _negotiate_xvp_auth() { - if (!this._rfb_credentials.username || - !this._rfb_credentials.password || - !this._rfb_credentials.target) { + _negotiateXvpAuth() { + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined || + this._rfbCredentials.target === undefined) { this.dispatchEvent(new CustomEvent( "credentialsrequired", { detail: { types: ["username", "password", "target"] } })); return false; } - const xvp_auth_str = String.fromCharCode(this._rfb_credentials.username.length) + - String.fromCharCode(this._rfb_credentials.target.length) + - this._rfb_credentials.username + - this._rfb_credentials.target; - this._sock.send_string(xvp_auth_str); - this._rfb_auth_scheme = 2; - return this._negotiate_authentication(); + const xvpAuthStr = String.fromCharCode(this._rfbCredentials.username.length) + + String.fromCharCode(this._rfbCredentials.target.length) + + this._rfbCredentials.username + + this._rfbCredentials.target; + this._sock.sendString(xvpAuthStr); + this._rfbAuthScheme = 2; + return this._negotiateAuthentication(); + } + + // VeNCrypt authentication, currently only supports version 0.2 and only Plain subtype + _negotiateVeNCryptAuth() { + + // waiting for VeNCrypt version + if (this._rfbVeNCryptState == 0) { + if (this._sock.rQwait("vencrypt version", 2)) { return false; } + + const major = this._sock.rQshift8(); + const minor = this._sock.rQshift8(); + + if (!(major == 0 && minor == 2)) { + return this._fail("Unsupported VeNCrypt version " + major + "." + minor); + } + + this._sock.send([0, 2]); + this._rfbVeNCryptState = 1; + } + + // waiting for ACK + if (this._rfbVeNCryptState == 1) { + if (this._sock.rQwait("vencrypt ack", 1)) { return false; } + + const res = this._sock.rQshift8(); + + if (res != 0) { + return this._fail("VeNCrypt failure " + res); + } + + this._rfbVeNCryptState = 2; + } + // must fall through here (i.e. no "else if"), beacause we may have already received + // the subtypes length and won't be called again + + if (this._rfbVeNCryptState == 2) { // waiting for subtypes length + if (this._sock.rQwait("vencrypt subtypes length", 1)) { return false; } + + const subtypesLength = this._sock.rQshift8(); + if (subtypesLength < 1) { + return this._fail("VeNCrypt subtypes empty"); + } + + this._rfbVeNCryptSubtypesLength = subtypesLength; + this._rfbVeNCryptState = 3; + } + + // waiting for subtypes list + if (this._rfbVeNCryptState == 3) { + if (this._sock.rQwait("vencrypt subtypes", 4 * this._rfbVeNCryptSubtypesLength)) { return false; } + + const subtypes = []; + for (let i = 0; i < this._rfbVeNCryptSubtypesLength; i++) { + subtypes.push(this._sock.rQshift32()); + } + + // 256 = Plain subtype + if (subtypes.indexOf(256) != -1) { + // 0x100 = 256 + this._sock.send([0, 0, 1, 0]); + this._rfbVeNCryptState = 4; + } else { + return this._fail("VeNCrypt Plain subtype not offered by server"); + } + } + + // negotiated Plain subtype, server waits for password + if (this._rfbVeNCryptState == 4) { + if (!this._rfbCredentials.username || + !this._rfbCredentials.password) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + const user = encodeUTF8(this._rfbCredentials.username); + const pass = encodeUTF8(this._rfbCredentials.password); + + // XXX we assume lengths are <= 255 (should not be an issue in the real world) + this._sock.send([0, 0, 0, user.length]); + this._sock.send([0, 0, 0, pass.length]); + this._sock.sendString(user); + this._sock.sendString(pass); + + this._rfbInitState = "SecurityResult"; + return true; + } } - _negotiate_std_vnc_auth() { + _negotiateStdVNCAuth() { if (this._sock.rQwait("auth challenge", 16)) { return false; } - if (!this._rfb_credentials.password) { + if (this._rfbCredentials.password === undefined) { this.dispatchEvent(new CustomEvent( "credentialsrequired", { detail: { types: ["password"] } })); @@ -958,23 +1475,40 @@ export default class RFB extends EventTargetMixin { // TODO(directxman12): make genDES not require an Array const challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16)); - const response = RFB.genDES(this._rfb_credentials.password, challenge); + const response = RFB.genDES(this._rfbCredentials.password, challenge); this._sock.send(response); - this._rfb_init_state = "SecurityResult"; + this._rfbInitState = "SecurityResult"; return true; } - _negotiate_tight_tunnels(numTunnels) { + _negotiateTightUnixAuth() { + if (this._rfbCredentials.username === undefined || + this._rfbCredentials.password === undefined) { + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password"] } })); + return false; + } + + this._sock.send([0, 0, 0, this._rfbCredentials.username.length]); + this._sock.send([0, 0, 0, this._rfbCredentials.password.length]); + this._sock.sendString(this._rfbCredentials.username); + this._sock.sendString(this._rfbCredentials.password); + this._rfbInitState = "SecurityResult"; + return true; + } + + _negotiateTightTunnels(numTunnels) { const clientSupportedTunnelTypes = { 0: { vendor: 'TGHT', signature: 'NOTUNNEL' } }; const serverSupportedTunnelTypes = {}; // receive tunnel capabilities for (let i = 0; i < numTunnels; i++) { - const cap_code = this._sock.rQshift32(); - const cap_vendor = this._sock.rQshiftStr(4); - const cap_signature = this._sock.rQshiftStr(8); - serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature }; + const capCode = this._sock.rQshift32(); + const capVendor = this._sock.rQshiftStr(4); + const capSignature = this._sock.rQshiftStr(8); + serverSupportedTunnelTypes[capCode] = { vendor: capVendor, signature: capSignature }; } Log.Debug("Server Tight tunnel types: " + serverSupportedTunnelTypes); @@ -1005,16 +1539,16 @@ export default class RFB extends EventTargetMixin { } } - _negotiate_tight_auth() { - if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation + _negotiateTightAuth() { + if (!this._rfbTightVNC) { // first pass, do the tunnel negotiation if (this._sock.rQwait("num tunnels", 4)) { return false; } const numTunnels = this._sock.rQshift32(); if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; } - this._rfb_tightvnc = true; + this._rfbTightVNC = true; if (numTunnels > 0) { - this._negotiate_tight_tunnels(numTunnels); + this._negotiateTightTunnels(numTunnels); return false; // wait until we receive the sub auth to continue } } @@ -1023,7 +1557,7 @@ export default class RFB extends EventTargetMixin { if (this._sock.rQwait("sub auth count", 4)) { return false; } const subAuthCount = this._sock.rQshift32(); if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected - this._rfb_init_state = 'SecurityResult'; + this._rfbInitState = 'SecurityResult'; return true; } @@ -1031,7 +1565,8 @@ export default class RFB extends EventTargetMixin { const clientSupportedTypes = { 'STDVNOAUTH__': 1, - 'STDVVNCAUTH_': 2 + 'STDVVNCAUTH_': 2, + 'TGHTULGNAUTH': 129 }; const serverSupportedTypes = []; @@ -1051,11 +1586,14 @@ export default class RFB extends EventTargetMixin { switch (authType) { case 'STDVNOAUTH__': // no auth - this._rfb_init_state = 'SecurityResult'; + this._rfbInitState = 'SecurityResult'; return true; case 'STDVVNCAUTH_': // VNC auth - this._rfb_auth_scheme = 2; - return this._init_msg(); + this._rfbAuthScheme = 2; + return this._initMsg(); + case 'TGHTULGNAUTH': // UNIX auth + this._rfbAuthScheme = 129; + return this._initMsg(); default: return this._fail("Unsupported tiny auth scheme " + "(scheme: " + authType + ")"); @@ -1066,46 +1604,52 @@ export default class RFB extends EventTargetMixin { return this._fail("No supported sub-auth types!"); } - _negotiate_authentication() { - switch (this._rfb_auth_scheme) { + _negotiateAuthentication() { + switch (this._rfbAuthScheme) { case 1: // no auth - if (this._rfb_version >= 3.8) { - this._rfb_init_state = 'SecurityResult'; + if (this._rfbVersion >= 3.8) { + this._rfbInitState = 'SecurityResult'; return true; } - this._rfb_init_state = 'ClientInitialisation'; - return this._init_msg(); + this._rfbInitState = 'ClientInitialisation'; + return this._initMsg(); case 22: // XVP auth - return this._negotiate_xvp_auth(); + return this._negotiateXvpAuth(); case 2: // VNC authentication - return this._negotiate_std_vnc_auth(); + return this._negotiateStdVNCAuth(); case 16: // TightVNC Security Type - return this._negotiate_tight_auth(); + return this._negotiateTightAuth(); + + case 19: // VeNCrypt Security Type + return this._negotiateVeNCryptAuth(); + + case 129: // TightVNC UNIX Security Type + return this._negotiateTightUnixAuth(); default: return this._fail("Unsupported auth scheme (scheme: " + - this._rfb_auth_scheme + ")"); + this._rfbAuthScheme + ")"); } } - _handle_security_result() { + _handleSecurityResult() { if (this._sock.rQwait('VNC auth response ', 4)) { return false; } const status = this._sock.rQshift32(); if (status === 0) { // OK - this._rfb_init_state = 'ClientInitialisation'; + this._rfbInitState = 'ClientInitialisation'; Log.Debug('Authentication OK'); - return this._init_msg(); + return this._initMsg(); } else { - if (this._rfb_version >= 3.8) { - this._rfb_init_state = "SecurityReason"; - this._security_context = "security result"; - this._security_status = status; - return this._init_msg(); + if (this._rfbVersion >= 3.8) { + this._rfbInitState = "SecurityReason"; + this._securityContext = "security result"; + this._securityStatus = status; + return this._initMsg(); } else { this.dispatchEvent(new CustomEvent( "securityfailure", @@ -1116,7 +1660,7 @@ export default class RFB extends EventTargetMixin { } } - _negotiate_server_init() { + _negotiateServerInit() { if (this._sock.rQwait("server initialization", 24)) { return false; } /* Screen size */ @@ -1126,27 +1670,28 @@ export default class RFB extends EventTargetMixin { /* PIXEL_FORMAT */ const bpp = this._sock.rQshift8(); const depth = this._sock.rQshift8(); - const big_endian = this._sock.rQshift8(); - const true_color = this._sock.rQshift8(); - - const red_max = this._sock.rQshift16(); - const green_max = this._sock.rQshift16(); - const blue_max = this._sock.rQshift16(); - const red_shift = this._sock.rQshift8(); - const green_shift = this._sock.rQshift8(); - const blue_shift = this._sock.rQshift8(); + const bigEndian = this._sock.rQshift8(); + const trueColor = this._sock.rQshift8(); + + const redMax = this._sock.rQshift16(); + const greenMax = this._sock.rQshift16(); + const blueMax = this._sock.rQshift16(); + const redShift = this._sock.rQshift8(); + const greenShift = this._sock.rQshift8(); + const blueShift = this._sock.rQshift8(); this._sock.rQskipBytes(3); // padding // NB(directxman12): we don't want to call any callbacks or print messages until // *after* we're past the point where we could backtrack /* Connection name/title */ - const name_length = this._sock.rQshift32(); - if (this._sock.rQwait('server init name', name_length, 24)) { return false; } - this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length)); + const nameLength = this._sock.rQshift32(); + if (this._sock.rQwait('server init name', nameLength, 24)) { return false; } + let name = this._sock.rQshiftStr(nameLength); + name = decodeUTF8(name, true); - if (this._rfb_tightvnc) { - if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; } + if (this._rfbTightVNC) { + if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + nameLength)) { return false; } // In TightVNC mode, ServerInit message is extended const numServerMessages = this._sock.rQshift16(); const numClientMessages = this._sock.rQshift16(); @@ -1154,7 +1699,7 @@ export default class RFB extends EventTargetMixin { this._sock.rQskipBytes(2); // padding const totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16; - if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; } + if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + nameLength)) { return false; } // we don't actually do anything with the capability information that TIGHT sends, // so we just skip the all of this. @@ -1173,47 +1718,31 @@ export default class RFB extends EventTargetMixin { // if we backtrack Log.Info("Screen: " + width + "x" + height + ", bpp: " + bpp + ", depth: " + depth + - ", big_endian: " + big_endian + - ", true_color: " + true_color + - ", red_max: " + red_max + - ", green_max: " + green_max + - ", blue_max: " + blue_max + - ", red_shift: " + red_shift + - ", green_shift: " + green_shift + - ", blue_shift: " + blue_shift); - - if (big_endian !== 0) { - Log.Warn("Server native endian is not little endian"); - } - - if (red_shift !== 16) { - Log.Warn("Server native red-shift is not 16"); - } - - if (blue_shift !== 0) { - Log.Warn("Server native blue-shift is not 0"); - } + ", bigEndian: " + bigEndian + + ", trueColor: " + trueColor + + ", redMax: " + redMax + + ", greenMax: " + greenMax + + ", blueMax: " + blueMax + + ", redShift: " + redShift + + ", greenShift: " + greenShift + + ", blueShift: " + blueShift); // we're past the point where we could backtrack, so it's safe to call this - this.dispatchEvent(new CustomEvent( - "desktopname", - { detail: { name: this._fb_name } })); - + this._setDesktopName(name); this._resize(width, height); if (!this._viewOnly) { this._keyboard.grab(); } - if (!this._viewOnly) { this._mouse.grab(); } - this._fb_depth = 24; + this._fbDepth = 24; - if (this._fb_name === "Intel(r) AMT KVM") { + if (this._fbName === "Intel(r) AMT KVM") { Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode."); - this._fb_depth = 8; + this._fbDepth = 8; } - RFB.messages.pixelFormat(this._sock, this._fb_depth, true); + RFB.messages.pixelFormat(this._sock, this._fbDepth, true); this._sendEncodings(); - RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height); + RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fbWidth, this._fbHeight); this._updateConnectionState('connected'); return true; @@ -1225,7 +1754,7 @@ export default class RFB extends EventTargetMixin { // In preference order encs.push(encodings.encodingCopyRect); // Only supported with full depth support - if (this._fb_depth == 24) { + if (this._fbDepth == 24) { encs.push(encodings.encodingTight); encs.push(encodings.encodingTightPNG); encs.push(encodings.encodingHextile); @@ -1234,8 +1763,8 @@ export default class RFB extends EventTargetMixin { encs.push(encodings.encodingRaw); // Psuedo-encoding settings - encs.push(encodings.pseudoEncodingQualityLevel0 + 6); - encs.push(encodings.pseudoEncodingCompressLevel0 + 2); + encs.push(encodings.pseudoEncodingQualityLevel0 + this._qualityLevel); + encs.push(encodings.pseudoEncodingCompressLevel0 + this._compressionLevel); encs.push(encodings.pseudoEncodingDesktopSize); encs.push(encodings.pseudoEncodingLastRect); @@ -1244,8 +1773,11 @@ export default class RFB extends EventTargetMixin { encs.push(encodings.pseudoEncodingXvp); encs.push(encodings.pseudoEncodingFence); encs.push(encodings.pseudoEncodingContinuousUpdates); + encs.push(encodings.pseudoEncodingDesktopName); + encs.push(encodings.pseudoEncodingExtendedClipboard); - if (this._fb_depth == 24) { + if (this._fbDepth == 24) { + encs.push(encodings.pseudoEncodingVMwareCursor); encs.push(encodings.pseudoEncodingCursor); } @@ -1260,63 +1792,212 @@ export default class RFB extends EventTargetMixin { * ClientInitialization - not triggered by server message * ServerInitialization */ - _init_msg() { - switch (this._rfb_init_state) { + _initMsg() { + switch (this._rfbInitState) { case 'ProtocolVersion': - return this._negotiate_protocol_version(); + return this._negotiateProtocolVersion(); case 'Security': - return this._negotiate_security(); + return this._negotiateSecurity(); case 'Authentication': - return this._negotiate_authentication(); + return this._negotiateAuthentication(); case 'SecurityResult': - return this._handle_security_result(); + return this._handleSecurityResult(); case 'SecurityReason': - return this._handle_security_reason(); + return this._handleSecurityReason(); case 'ClientInitialisation': this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation - this._rfb_init_state = 'ServerInitialisation'; + this._rfbInitState = 'ServerInitialisation'; return true; case 'ServerInitialisation': - return this._negotiate_server_init(); + return this._negotiateServerInit(); default: return this._fail("Unknown init state (state: " + - this._rfb_init_state + ")"); + this._rfbInitState + ")"); } } - _handle_set_colour_map_msg() { + _handleSetColourMapMsg() { Log.Debug("SetColorMapEntries"); return this._fail("Unexpected SetColorMapEntries message"); } - _handle_server_cut_text() { + _handleServerCutText() { Log.Debug("ServerCutText"); if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; } + this._sock.rQskipBytes(3); // Padding - const length = this._sock.rQshift32(); - if (this._sock.rQwait("ServerCutText", length, 8)) { return false; } - const text = this._sock.rQshiftStr(length); + let length = this._sock.rQshift32(); + length = toSigned32bit(length); - if (this._viewOnly) { return true; } + if (this._sock.rQwait("ServerCutText content", Math.abs(length), 8)) { return false; } - this.dispatchEvent(new CustomEvent( - "clipboard", - { detail: { text: text } })); + if (length >= 0) { + //Standard msg + const text = this._sock.rQshiftStr(length); + if (this._viewOnly) { + return true; + } + + this.dispatchEvent(new CustomEvent( + "clipboard", + { detail: { text: text } })); + + } else { + //Extended msg. + length = Math.abs(length); + const flags = this._sock.rQshift32(); + let formats = flags & 0x0000FFFF; + let actions = flags & 0xFF000000; + + let isCaps = (!!(actions & extendedClipboardActionCaps)); + if (isCaps) { + this._clipboardServerCapabilitiesFormats = {}; + this._clipboardServerCapabilitiesActions = {}; + + // Update our server capabilities for Formats + for (let i = 0; i <= 15; i++) { + let index = 1 << i; + + // Check if format flag is set. + if ((formats & index)) { + this._clipboardServerCapabilitiesFormats[index] = true; + // We don't send unsolicited clipboard, so we + // ignore the size + this._sock.rQshift32(); + } + } + + // Update our server capabilities for Actions + for (let i = 24; i <= 31; i++) { + let index = 1 << i; + this._clipboardServerCapabilitiesActions[index] = !!(actions & index); + } + + /* Caps handling done, send caps with the clients + capabilities set as a response */ + let clientActions = [ + extendedClipboardActionCaps, + extendedClipboardActionRequest, + extendedClipboardActionPeek, + extendedClipboardActionNotify, + extendedClipboardActionProvide + ]; + RFB.messages.extendedClipboardCaps(this._sock, clientActions, {extendedClipboardFormatText: 0}); + + } else if (actions === extendedClipboardActionRequest) { + if (this._viewOnly) { + return true; + } + + // Check if server has told us it can handle Provide and there is clipboard data to send. + if (this._clipboardText != null && + this._clipboardServerCapabilitiesActions[extendedClipboardActionProvide]) { + + if (formats & extendedClipboardFormatText) { + RFB.messages.extendedClipboardProvide(this._sock, [extendedClipboardFormatText], [this._clipboardText]); + } + } + + } else if (actions === extendedClipboardActionPeek) { + if (this._viewOnly) { + return true; + } + if (this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) { + + if (this._clipboardText != null) { + RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]); + } else { + RFB.messages.extendedClipboardNotify(this._sock, []); + } + } + + } else if (actions === extendedClipboardActionNotify) { + if (this._viewOnly) { + return true; + } + + if (this._clipboardServerCapabilitiesActions[extendedClipboardActionRequest]) { + + if (formats & extendedClipboardFormatText) { + RFB.messages.extendedClipboardRequest(this._sock, [extendedClipboardFormatText]); + } + } + + } else if (actions === extendedClipboardActionProvide) { + if (this._viewOnly) { + return true; + } + + if (!(formats & extendedClipboardFormatText)) { + return true; + } + // Ignore what we had in our clipboard client side. + this._clipboardText = null; + + // FIXME: Should probably verify that this data was actually requested + let zlibStream = this._sock.rQshiftBytes(length - 4); + let streamInflator = new Inflator(); + let textData = null; + + streamInflator.setInput(zlibStream); + for (let i = 0; i <= 15; i++) { + let format = 1 << i; + + if (formats & format) { + + let size = 0x00; + let sizeArray = streamInflator.inflate(4); + + size |= (sizeArray[0] << 24); + size |= (sizeArray[1] << 16); + size |= (sizeArray[2] << 8); + size |= (sizeArray[3]); + let chunk = streamInflator.inflate(size); + + if (format === extendedClipboardFormatText) { + textData = chunk; + } + } + } + streamInflator.setInput(null); + + if (textData !== null) { + let tmpText = ""; + for (let i = 0; i < textData.length; i++) { + tmpText += String.fromCharCode(textData[i]); + } + textData = tmpText; + + textData = decodeUTF8(textData); + if ((textData.length > 0) && "\0" === textData.charAt(textData.length - 1)) { + textData = textData.slice(0, -1); + } + + textData = textData.replace("\r\n", "\n"); + + this.dispatchEvent(new CustomEvent( + "clipboard", + { detail: { text: textData } })); + } + } else { + return this._fail("Unexpected action in extended clipboard message: " + actions); + } + } return true; } - _handle_server_fence_msg() { + _handleServerFenceMsg() { if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; } this._sock.rQskipBytes(3); // Padding let flags = this._sock.rQshift32(); @@ -1358,49 +2039,49 @@ export default class RFB extends EventTargetMixin { return true; } - _handle_xvp_msg() { + _handleXvpMsg() { if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; } this._sock.rQskipBytes(1); // Padding - const xvp_ver = this._sock.rQshift8(); - const xvp_msg = this._sock.rQshift8(); + const xvpVer = this._sock.rQshift8(); + const xvpMsg = this._sock.rQshift8(); - switch (xvp_msg) { + switch (xvpMsg) { case 0: // XVP_FAIL Log.Error("XVP Operation Failed"); break; case 1: // XVP_INIT - this._rfb_xvp_ver = xvp_ver; - Log.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")"); + this._rfbXvpVer = xvpVer; + Log.Info("XVP extensions enabled (version " + this._rfbXvpVer + ")"); this._setCapability("power", true); break; default: - this._fail("Illegal server XVP message (msg: " + xvp_msg + ")"); + this._fail("Illegal server XVP message (msg: " + xvpMsg + ")"); break; } return true; } - _normal_msg() { - let msg_type; + _normalMsg() { + let msgType; if (this._FBU.rects > 0) { - msg_type = 0; + msgType = 0; } else { - msg_type = this._sock.rQshift8(); + msgType = this._sock.rQshift8(); } let first, ret; - switch (msg_type) { + switch (msgType) { case 0: // FramebufferUpdate ret = this._framebufferUpdate(); if (ret && !this._enabledContinuousUpdates) { RFB.messages.fbUpdateRequest(this._sock, true, 0, 0, - this._fb_width, this._fb_height); + this._fbWidth, this._fbHeight); } return ret; case 1: // SetColorMapEntries - return this._handle_set_colour_map_msg(); + return this._handleSetColourMapMsg(); case 2: // Bell Log.Debug("Bell"); @@ -1410,7 +2091,7 @@ export default class RFB extends EventTargetMixin { return true; case 3: // ServerCutText - return this._handle_server_cut_text(); + return this._handleServerCutText(); case 150: // EndOfContinuousUpdates first = !this._supportsContinuousUpdates; @@ -1427,13 +2108,13 @@ export default class RFB extends EventTargetMixin { return true; case 248: // ServerFence - return this._handle_server_fence_msg(); + return this._handleServerFenceMsg(); case 250: // XVP - return this._handle_xvp_msg(); + return this._handleXvpMsg(); default: - this._fail("Unexpected server message (type " + msg_type + ")"); + this._fail("Unexpected server message (type " + msgType + ")"); Log.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30)); return true; } @@ -1443,7 +2124,7 @@ export default class RFB extends EventTargetMixin { this._flushing = false; // Resume processing if (this._sock.rQlen > 0) { - this._handle_message(); + this._handleMessage(); } } @@ -1495,6 +2176,9 @@ export default class RFB extends EventTargetMixin { this._FBU.rects = 1; // Will be decreased when we return return true; + case encodings.pseudoEncodingVMwareCursor: + return this._handleVMwareCursor(); + case encodings.pseudoEncodingCursor: return this._handleCursor(); @@ -1510,6 +2194,9 @@ export default class RFB extends EventTargetMixin { } return true; + case encodings.pseudoEncodingDesktopName: + return this._handleDesktopName(); + case encodings.pseudoEncodingDesktopSize: this._resize(this._FBU.width, this._FBU.height); return true; @@ -1522,6 +2209,122 @@ export default class RFB extends EventTargetMixin { } } + _handleVMwareCursor() { + const hotx = this._FBU.x; // hotspot-x + const hoty = this._FBU.y; // hotspot-y + const w = this._FBU.width; + const h = this._FBU.height; + if (this._sock.rQwait("VMware cursor encoding", 1)) { + return false; + } + + const cursorType = this._sock.rQshift8(); + + this._sock.rQshift8(); //Padding + + let rgba; + const bytesPerPixel = 4; + + //Classic cursor + if (cursorType == 0) { + //Used to filter away unimportant bits. + //OR is used for correct conversion in js. + const PIXEL_MASK = 0xffffff00 | 0; + rgba = new Array(w * h * bytesPerPixel); + + if (this._sock.rQwait("VMware cursor classic encoding", + (w * h * bytesPerPixel) * 2, 2)) { + return false; + } + + let andMask = new Array(w * h); + for (let pixel = 0; pixel < (w * h); pixel++) { + andMask[pixel] = this._sock.rQshift32(); + } + + let xorMask = new Array(w * h); + for (let pixel = 0; pixel < (w * h); pixel++) { + xorMask[pixel] = this._sock.rQshift32(); + } + + for (let pixel = 0; pixel < (w * h); pixel++) { + if (andMask[pixel] == 0) { + //Fully opaque pixel + let bgr = xorMask[pixel]; + let r = bgr >> 8 & 0xff; + let g = bgr >> 16 & 0xff; + let b = bgr >> 24 & 0xff; + + rgba[(pixel * bytesPerPixel) ] = r; //r + rgba[(pixel * bytesPerPixel) + 1 ] = g; //g + rgba[(pixel * bytesPerPixel) + 2 ] = b; //b + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; //a + + } else if ((andMask[pixel] & PIXEL_MASK) == + PIXEL_MASK) { + //Only screen value matters, no mouse colouring + if (xorMask[pixel] == 0) { + //Transparent pixel + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0x00; + + } else if ((xorMask[pixel] & PIXEL_MASK) == + PIXEL_MASK) { + //Inverted pixel, not supported in browsers. + //Fully opaque instead. + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + + } else { + //Unhandled xorMask + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + } + + } else { + //Unhandled andMask + rgba[(pixel * bytesPerPixel) ] = 0x00; + rgba[(pixel * bytesPerPixel) + 1 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 2 ] = 0x00; + rgba[(pixel * bytesPerPixel) + 3 ] = 0xff; + } + } + + //Alpha cursor. + } else if (cursorType == 1) { + if (this._sock.rQwait("VMware cursor alpha encoding", + (w * h * 4), 2)) { + return false; + } + + rgba = new Array(w * h * bytesPerPixel); + + for (let pixel = 0; pixel < (w * h); pixel++) { + let data = this._sock.rQshift32(); + + rgba[(pixel * 4) ] = data >> 24 & 0xff; //r + rgba[(pixel * 4) + 1 ] = data >> 16 & 0xff; //g + rgba[(pixel * 4) + 2 ] = data >> 8 & 0xff; //b + rgba[(pixel * 4) + 3 ] = data & 0xff; //a + } + + } else { + Log.Warn("The given cursor type is not supported: " + + cursorType + " given."); + return false; + } + + this._updateCursor(rgba, hotx, hoty, w, h); + + return true; + } + _handleCursor() { const hotx = this._FBU.x; // hotspot-x const hoty = this._FBU.y; // hotspot-y @@ -1541,16 +2344,16 @@ export default class RFB extends EventTargetMixin { const mask = this._sock.rQshiftBytes(masklength); let rgba = new Uint8Array(w * h * 4); - let pix_idx = 0; + let pixIdx = 0; for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { - let mask_idx = y * Math.ceil(w / 8) + Math.floor(x / 8); - let alpha = (mask[mask_idx] << (x % 8)) & 0x80 ? 255 : 0; - rgba[pix_idx ] = pixels[pix_idx + 2]; - rgba[pix_idx + 1] = pixels[pix_idx + 1]; - rgba[pix_idx + 2] = pixels[pix_idx]; - rgba[pix_idx + 3] = alpha; - pix_idx += 4; + let maskIdx = y * Math.ceil(w / 8) + Math.floor(x / 8); + let alpha = (mask[maskIdx] << (x % 8)) & 0x80 ? 255 : 0; + rgba[pixIdx ] = pixels[pixIdx + 2]; + rgba[pixIdx + 1] = pixels[pixIdx + 1]; + rgba[pixIdx + 2] = pixels[pixIdx]; + rgba[pixIdx + 3] = alpha; + pixIdx += 4; } } @@ -1559,14 +2362,33 @@ export default class RFB extends EventTargetMixin { return true; } + _handleDesktopName() { + if (this._sock.rQwait("DesktopName", 4)) { + return false; + } + + let length = this._sock.rQshift32(); + + if (this._sock.rQwait("DesktopName", length, 4)) { + return false; + } + + let name = this._sock.rQshiftStr(length); + name = decodeUTF8(name, true); + + this._setDesktopName(name); + + return true; + } + _handleExtendedDesktopSize() { if (this._sock.rQwait("ExtendedDesktopSize", 4)) { return false; } - const number_of_screens = this._sock.rQpeek8(); + const numberOfScreens = this._sock.rQpeek8(); - let bytes = 4 + (number_of_screens * 16); + let bytes = 4 + (numberOfScreens * 16); if (this._sock.rQwait("ExtendedDesktopSize", bytes)) { return false; } @@ -1585,15 +2407,15 @@ export default class RFB extends EventTargetMixin { this._sock.rQskipBytes(1); // number-of-screens this._sock.rQskipBytes(3); // padding - for (let i = 0; i < number_of_screens; i += 1) { + for (let i = 0; i < numberOfScreens; i += 1) { // Save the id and flags of the first screen if (i === 0) { - this._screen_id = this._sock.rQshiftBytes(4); // id + this._screenID = this._sock.rQshiftBytes(4); // id this._sock.rQskipBytes(2); // x-position this._sock.rQskipBytes(2); // y-position this._sock.rQskipBytes(2); // width this._sock.rQskipBytes(2); // height - this._screen_flags = this._sock.rQshiftBytes(4); // flags + this._screenFlags = this._sock.rQshiftBytes(4); // flags } else { this._sock.rQskipBytes(16); } @@ -1646,7 +2468,7 @@ export default class RFB extends EventTargetMixin { return decoder.decodeRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, this._sock, this._display, - this._fb_depth); + this._fbDepth); } catch (err) { this._fail("Error decoding rect: " + err); return false; @@ -1657,14 +2479,14 @@ export default class RFB extends EventTargetMixin { if (!this._enabledContinuousUpdates) { return; } RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0, - this._fb_width, this._fb_height); + this._fbWidth, this._fbHeight); } _resize(width, height) { - this._fb_width = width; - this._fb_height = height; + this._fbWidth = width; + this._fbHeight = height; - this._display.resize(this._fb_width, this._fb_height); + this._display.resize(this._fbWidth, this._fbHeight); // Adjust the visible viewport based on the new dimensions this._updateClip(); @@ -1674,7 +2496,7 @@ export default class RFB extends EventTargetMixin { } _xvpOp(ver, op) { - if (this._rfb_xvp_ver < ver) { return; } + if (this._rfbXvpVer < ver) { return; } Log.Info("Sending XVP operation " + op + " (version " + ver + ")"); RFB.messages.xvpOp(this._sock, ver, op); } @@ -1710,6 +2532,10 @@ export default class RFB extends EventTargetMixin { } _refreshCursor() { + if (this._rfbConnectionState !== "connecting" && + this._rfbConnectionState !== "connected") { + return; + } const image = this._shouldShowDotCursor() ? RFB.cursors.dot : this._cursorImage; this._cursor.change(image.rgbaPixels, image.hotx, image.hoty, @@ -1745,13 +2571,13 @@ RFB.messages = { }, QEMUExtendedKeyEvent(sock, keysym, down, keycode) { - function getRFBkeycode(xt_scancode) { + function getRFBkeycode(xtScanCode) { const upperByte = (keycode >> 8); const lowerByte = (keycode & 0x00ff); if (upperByte === 0xe0 && lowerByte < 0x7f) { return lowerByte | 0x80; } - return xt_scancode; + return xtScanCode; } const buff = sock._sQ; @@ -1797,8 +2623,102 @@ RFB.messages = { sock.flush(); }, - // TODO(directxman12): make this unicode compatible? - clientCutText(sock, text) { + // Used to build Notify and Request data. + _buildExtendedClipboardFlags(actions, formats) { + let data = new Uint8Array(4); + let formatFlag = 0x00000000; + let actionFlag = 0x00000000; + + for (let i = 0; i < actions.length; i++) { + actionFlag |= actions[i]; + } + + for (let i = 0; i < formats.length; i++) { + formatFlag |= formats[i]; + } + + data[0] = actionFlag >> 24; // Actions + data[1] = 0x00; // Reserved + data[2] = 0x00; // Reserved + data[3] = formatFlag; // Formats + + return data; + }, + + extendedClipboardProvide(sock, formats, inData) { + // Deflate incomming data and their sizes + let deflator = new Deflator(); + let dataToDeflate = []; + + for (let i = 0; i < formats.length; i++) { + // We only support the format Text at this time + if (formats[i] != extendedClipboardFormatText) { + throw new Error("Unsupported extended clipboard format for Provide message."); + } + + // Change lone \r or \n into \r\n as defined in rfbproto + inData[i] = inData[i].replace(/\r\n|\r|\n/gm, "\r\n"); + + // Check if it already has \0 + let text = encodeUTF8(inData[i] + "\0"); + + dataToDeflate.push( (text.length >> 24) & 0xFF, + (text.length >> 16) & 0xFF, + (text.length >> 8) & 0xFF, + (text.length & 0xFF)); + + for (let j = 0; j < text.length; j++) { + dataToDeflate.push(text.charCodeAt(j)); + } + } + + let deflatedData = deflator.deflate(new Uint8Array(dataToDeflate)); + + // Build data to send + let data = new Uint8Array(4 + deflatedData.length); + data.set(RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionProvide], + formats)); + data.set(deflatedData, 4); + + RFB.messages.clientCutText(sock, data, true); + }, + + extendedClipboardNotify(sock, formats) { + let flags = RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionNotify], + formats); + RFB.messages.clientCutText(sock, flags, true); + }, + + extendedClipboardRequest(sock, formats) { + let flags = RFB.messages._buildExtendedClipboardFlags([extendedClipboardActionRequest], + formats); + RFB.messages.clientCutText(sock, flags, true); + }, + + extendedClipboardCaps(sock, actions, formats) { + let formatKeys = Object.keys(formats); + let data = new Uint8Array(4 + (4 * formatKeys.length)); + + formatKeys.map(x => parseInt(x)); + formatKeys.sort((a, b) => a - b); + + data.set(RFB.messages._buildExtendedClipboardFlags(actions, [])); + + let loopOffset = 4; + for (let i = 0; i < formatKeys.length; i++) { + data[loopOffset] = formats[formatKeys[i]] >> 24; + data[loopOffset + 1] = formats[formatKeys[i]] >> 16; + data[loopOffset + 2] = formats[formatKeys[i]] >> 8; + data[loopOffset + 3] = formats[formatKeys[i]] >> 0; + + loopOffset += 4; + data[3] |= (1 << formatKeys[i]); // Update our format flags + } + + RFB.messages.clientCutText(sock, data, true); + }, + + clientCutText(sock, data, extended = false) { const buff = sock._sQ; const offset = sock._sQlen; @@ -1808,7 +2728,12 @@ RFB.messages = { buff[offset + 2] = 0; // padding buff[offset + 3] = 0; // padding - let length = text.length; + let length; + if (extended) { + length = toUnsigned32bit(-data.length); + } else { + length = data.length; + } buff[offset + 4] = length >> 24; buff[offset + 5] = length >> 16; @@ -1817,24 +2742,25 @@ RFB.messages = { sock._sQlen += 8; - // We have to keep track of from where in the text we begin creating the + // We have to keep track of from where in the data we begin creating the // buffer for the flush in the next iteration. - let textOffset = 0; + let dataOffset = 0; - let remaining = length; + let remaining = data.length; while (remaining > 0) { let flushSize = Math.min(remaining, (sock._sQbufferSize - sock._sQlen)); for (let i = 0; i < flushSize; i++) { - buff[sock._sQlen + i] = text.charCodeAt(textOffset + i); + buff[sock._sQlen + i] = data[dataOffset + i]; } sock._sQlen += flushSize; sock.flush(); remaining -= flushSize; - textOffset += flushSize; + dataOffset += flushSize; } + }, setDesktopSize(sock, width, height, id, flags) { @@ -1920,7 +2846,7 @@ RFB.messages = { sock.flush(); }, - pixelFormat(sock, depth, true_color) { + pixelFormat(sock, depth, trueColor) { const buff = sock._sQ; const offset = sock._sQlen; @@ -1945,7 +2871,7 @@ RFB.messages = { buff[offset + 4] = bpp; // bits-per-pixel buff[offset + 5] = depth; // depth buff[offset + 6] = 0; // little-endian - buff[offset + 7] = true_color ? 1 : 0; // true-color + buff[offset + 7] = trueColor ? 1 : 0; // true-color buff[offset + 8] = 0; // red-max buff[offset + 9] = (1 << bits) - 1; // red-max diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/browser.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/browser.js index 8996cfed..15548014 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/browser.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/browser.js @@ -1,9 +1,11 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. + * + * Browser feature support detection */ import * as Log from './logging.js'; @@ -31,7 +33,7 @@ try { const target = document.createElement('canvas'); target.style.cursor = 'url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default'; - if (target.style.cursor) { + if (target.style.cursor.indexOf("url") === 0) { Log.Info("Data URI scheme cursor supported"); _supportsCursorURIs = true; } else { @@ -52,6 +54,38 @@ try { } export const supportsImageMetadata = _supportsImageMetadata; +let _hasScrollbarGutter = true; +try { + // Create invisible container + const container = document.createElement('div'); + container.style.visibility = 'hidden'; + container.style.overflow = 'scroll'; // forcing scrollbars + document.body.appendChild(container); + + // Create a div and place it in the container + const child = document.createElement('div'); + container.appendChild(child); + + // Calculate the difference between the container's full width + // and the child's width - the difference is the scrollbars + const scrollbarWidth = (container.offsetWidth - child.offsetWidth); + + // Clean up + container.parentNode.removeChild(container); + + _hasScrollbarGutter = scrollbarWidth != 0; +} catch (exc) { + Log.Error("Scrollbar test exception: " + exc); +} +export const hasScrollbarGutter = _hasScrollbarGutter; + +/* + * The functions for detection of platforms and browsers below are exported + * but the use of these should be minimized as much as possible. + * + * It's better to use feature detection than platform detection. + */ + export function isMac() { return navigator && !!(/mac/i).exec(navigator.platform); } @@ -67,10 +101,6 @@ export function isIOS() { !!(/ipod/i).exec(navigator.platform)); } -export function isAndroid() { - return navigator && !!(/android/i).exec(navigator.userAgent); -} - export function isSafari() { return navigator && (navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/cursor.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/cursor.js index 0d0b754a..4db1dab2 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/cursor.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/cursor.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 or any later version (see LICENSE.txt) */ @@ -20,7 +20,6 @@ export default class Cursor { this._canvas.style.pointerEvents = 'none'; // Can't use "display" because of Firefox bug #1445997 this._canvas.style.visibility = 'hidden'; - document.body.appendChild(this._canvas); } this._position = { x: 0, y: 0 }; @@ -31,9 +30,6 @@ export default class Cursor { 'mouseleave': this._handleMouseLeave.bind(this), 'mousemove': this._handleMouseMove.bind(this), 'mouseup': this._handleMouseUp.bind(this), - 'touchstart': this._handleTouchStart.bind(this), - 'touchmove': this._handleTouchMove.bind(this), - 'touchend': this._handleTouchEnd.bind(this), }; } @@ -45,6 +41,8 @@ export default class Cursor { this._target = target; if (useFallback) { + document.body.appendChild(this._canvas); + // FIXME: These don't fire properly except for mouse /// movement in IE. We want to also capture element // movement, size changes, visibility, etc. @@ -53,17 +51,16 @@ export default class Cursor { this._target.addEventListener('mouseleave', this._eventHandlers.mouseleave, options); this._target.addEventListener('mousemove', this._eventHandlers.mousemove, options); this._target.addEventListener('mouseup', this._eventHandlers.mouseup, options); - - // There is no "touchleave" so we monitor touchstart globally - window.addEventListener('touchstart', this._eventHandlers.touchstart, options); - this._target.addEventListener('touchmove', this._eventHandlers.touchmove, options); - this._target.addEventListener('touchend', this._eventHandlers.touchend, options); } this.clear(); } detach() { + if (!this._target) { + return; + } + if (useFallback) { const options = { capture: true, passive: true }; this._target.removeEventListener('mouseover', this._eventHandlers.mouseover, options); @@ -71,9 +68,7 @@ export default class Cursor { this._target.removeEventListener('mousemove', this._eventHandlers.mousemove, options); this._target.removeEventListener('mouseup', this._eventHandlers.mouseup, options); - window.removeEventListener('touchstart', this._eventHandlers.touchstart, options); - this._target.removeEventListener('touchmove', this._eventHandlers.touchmove, options); - this._target.removeEventListener('touchend', this._eventHandlers.touchend, options); + document.body.removeChild(this._canvas); } this._target = null; @@ -124,6 +119,27 @@ export default class Cursor { this._hotSpot.y = 0; } + // Mouse events might be emulated, this allows + // moving the cursor in such cases + move(clientX, clientY) { + if (!useFallback) { + return; + } + // clientX/clientY are relative the _visual viewport_, + // but our position is relative the _layout viewport_, + // so try to compensate when we can + if (window.visualViewport) { + this._position.x = clientX + window.visualViewport.offsetLeft; + this._position.y = clientY + window.visualViewport.offsetTop; + } else { + this._position.x = clientX; + this._position.y = clientY; + } + this._updatePosition(); + let target = document.elementFromPoint(clientX, clientY); + this._updateVisibility(target); + } + _handleMouseOver(event) { // This event could be because we're entering the target, or // moving around amongst its sub elements. Let the move handler @@ -132,7 +148,8 @@ export default class Cursor { } _handleMouseLeave(event) { - this._hideCursor(); + // Check if we should show the cursor on the element we are leaving to + this._updateVisibility(event.relatedTarget); } _handleMouseMove(event) { @@ -150,27 +167,29 @@ export default class Cursor { // now and adjust visibility based on that. let target = document.elementFromPoint(event.clientX, event.clientY); this._updateVisibility(target); - } - _handleTouchStart(event) { - // Just as for mouseover, we let the move handler deal with it - this._handleTouchMove(event); - } - - _handleTouchMove(event) { - this._updateVisibility(event.target); - - this._position.x = event.changedTouches[0].clientX - this._hotSpot.x; - this._position.y = event.changedTouches[0].clientY - this._hotSpot.y; - - this._updatePosition(); - } - - _handleTouchEnd(event) { - // Same principle as for mouseup - let target = document.elementFromPoint(event.changedTouches[0].clientX, - event.changedTouches[0].clientY); - this._updateVisibility(target); + // Captures end with a mouseup but we can't know the event order of + // mouseup vs releaseCapture. + // + // In the cases when releaseCapture comes first, the code above is + // enough. + // + // In the cases when the mouseup comes first, we need wait for the + // browser to flush all events and then check again if the cursor + // should be visible. + if (this._captureIsActive()) { + window.setTimeout(() => { + // We might have detached at this point + if (!this._target) { + return; + } + // Refresh the target from elementFromPoint since queued events + // might have altered the DOM + target = document.elementFromPoint(event.clientX, + event.clientY); + this._updateVisibility(target); + }, 0); + } } _showCursor() { @@ -189,6 +208,9 @@ export default class Cursor { // (i.e. are we over the target, or a child of the target without a // different cursor set) _shouldShowCursor(target) { + if (!target) { + return false; + } // Easy case if (target === this._target) { return true; @@ -207,6 +229,11 @@ export default class Cursor { } _updateVisibility(target) { + // When the cursor target has capture we want to show the cursor. + // So, if a capture is active - look at the captured element instead. + if (this._captureIsActive()) { + target = document.captureElement; + } if (this._shouldShowCursor(target)) { this._showCursor(); } else { @@ -218,4 +245,9 @@ export default class Cursor { this._canvas.style.left = this._position.x + "px"; this._canvas.style.top = this._position.y + "px"; } + + _captureIsActive() { + return document.captureElement && + document.documentElement.contains(document.captureElement); + } } diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/element.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/element.js new file mode 100644 index 00000000..466a7453 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/element.js @@ -0,0 +1,32 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC Authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +/* + * HTML element utility functions + */ + +export function clientToElement(x, y, elem) { + const bounds = elem.getBoundingClientRect(); + let pos = { x: 0, y: 0 }; + // Clip to target bounds + if (x < bounds.left) { + pos.x = 0; + } else if (x >= bounds.right) { + pos.x = bounds.width - 1; + } else { + pos.x = x - bounds.left; + } + if (y < bounds.top) { + pos.y = 0; + } else if (y >= bounds.bottom) { + pos.y = bounds.height - 1; + } else { + pos.y = y - bounds.top; + } + return pos; +} diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/events.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/events.js index f1222796..39eefd45 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/events.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/events.js @@ -21,7 +21,8 @@ export function stopEvent(e) { // Emulate Element.setCapture() when not supported let _captureRecursion = false; -let _captureElem = null; +let _elementForUnflushedEvents = null; +document.captureElement = null; function _captureProxy(e) { // Recursion protection as we'll see our own event if (_captureRecursion) return; @@ -30,7 +31,11 @@ function _captureProxy(e) { const newEv = new e.constructor(e.type, e); _captureRecursion = true; - _captureElem.dispatchEvent(newEv); + if (document.captureElement) { + document.captureElement.dispatchEvent(newEv); + } else { + _elementForUnflushedEvents.dispatchEvent(newEv); + } _captureRecursion = false; // Avoid double events @@ -48,58 +53,56 @@ function _captureProxy(e) { } // Follow cursor style of target element -function _captureElemChanged() { - const captureElem = document.getElementById("noVNC_mouse_capture_elem"); - captureElem.style.cursor = window.getComputedStyle(_captureElem).cursor; +function _capturedElemChanged() { + const proxyElem = document.getElementById("noVNC_mouse_capture_elem"); + proxyElem.style.cursor = window.getComputedStyle(document.captureElement).cursor; } -const _captureObserver = new MutationObserver(_captureElemChanged); - -let _captureIndex = 0; +const _captureObserver = new MutationObserver(_capturedElemChanged); -export function setCapture(elem) { - if (elem.setCapture) { +export function setCapture(target) { + if (target.setCapture) { - elem.setCapture(); + target.setCapture(); + document.captureElement = target; // IE releases capture on 'click' events which might not trigger - elem.addEventListener('mouseup', releaseCapture); + target.addEventListener('mouseup', releaseCapture); } else { // Release any existing capture in case this method is // called multiple times without coordination releaseCapture(); - let captureElem = document.getElementById("noVNC_mouse_capture_elem"); + let proxyElem = document.getElementById("noVNC_mouse_capture_elem"); - if (captureElem === null) { - captureElem = document.createElement("div"); - captureElem.id = "noVNC_mouse_capture_elem"; - captureElem.style.position = "fixed"; - captureElem.style.top = "0px"; - captureElem.style.left = "0px"; - captureElem.style.width = "100%"; - captureElem.style.height = "100%"; - captureElem.style.zIndex = 10000; - captureElem.style.display = "none"; - document.body.appendChild(captureElem); + if (proxyElem === null) { + proxyElem = document.createElement("div"); + proxyElem.id = "noVNC_mouse_capture_elem"; + proxyElem.style.position = "fixed"; + proxyElem.style.top = "0px"; + proxyElem.style.left = "0px"; + proxyElem.style.width = "100%"; + proxyElem.style.height = "100%"; + proxyElem.style.zIndex = 10000; + proxyElem.style.display = "none"; + document.body.appendChild(proxyElem); // This is to make sure callers don't get confused by having // our blocking element as the target - captureElem.addEventListener('contextmenu', _captureProxy); + proxyElem.addEventListener('contextmenu', _captureProxy); - captureElem.addEventListener('mousemove', _captureProxy); - captureElem.addEventListener('mouseup', _captureProxy); + proxyElem.addEventListener('mousemove', _captureProxy); + proxyElem.addEventListener('mouseup', _captureProxy); } - _captureElem = elem; - _captureIndex++; + document.captureElement = target; // Track cursor and get initial cursor - _captureObserver.observe(elem, {attributes: true}); - _captureElemChanged(); + _captureObserver.observe(target, {attributes: true}); + _capturedElemChanged(); - captureElem.style.display = ""; + proxyElem.style.display = ""; // We listen to events on window in order to keep tracking if it // happens to leave the viewport @@ -112,26 +115,26 @@ export function releaseCapture() { if (document.releaseCapture) { document.releaseCapture(); + document.captureElement = null; } else { - if (!_captureElem) { + if (!document.captureElement) { return; } - // There might be events already queued, so we need to wait for - // them to flush. E.g. contextmenu in Microsoft Edge - window.setTimeout((expected) => { - // Only clear it if it's the expected grab (i.e. no one - // else has initiated a new grab) - if (_captureIndex === expected) { - _captureElem = null; - } - }, 0, _captureIndex); + // There might be events already queued. The event proxy needs + // access to the captured element for these queued events. + // E.g. contextmenu (right-click) in Microsoft Edge + // + // Before removing the capturedElem pointer we save it to a + // temporary variable that the unflushed events can use. + _elementForUnflushedEvents = document.captureElement; + document.captureElement = null; _captureObserver.disconnect(); - const captureElem = document.getElementById("noVNC_mouse_capture_elem"); - captureElem.style.display = "none"; + const proxyElem = document.getElementById("noVNC_mouse_capture_elem"); + proxyElem.style.display = "none"; window.removeEventListener('mousemove', _captureProxy); window.removeEventListener('mouseup', _captureProxy); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/eventtarget.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/eventtarget.js index f54ca9bf..a21aa549 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/eventtarget.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/eventtarget.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/int.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/int.js new file mode 100644 index 00000000..001f40f2 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/int.js @@ -0,0 +1,15 @@ +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2020 The noVNC Authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ + +export function toUnsigned32bit(toConvert) { + return toConvert >>> 0; +} + +export function toSigned32bit(toConvert) { + return toConvert | 0; +} diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/logging.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/logging.js index 4c8943d0..fe449e93 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/logging.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/logging.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -10,18 +10,18 @@ * Logging/debug routines */ -let _log_level = 'warn'; +let _logLevel = 'warn'; let Debug = () => {}; let Info = () => {}; let Warn = () => {}; let Error = () => {}; -export function init_logging(level) { +export function initLogging(level) { if (typeof level === 'undefined') { - level = _log_level; + level = _logLevel; } else { - _log_level = level; + _logLevel = level; } Debug = Info = Warn = Error = () => {}; @@ -46,11 +46,11 @@ export function init_logging(level) { } } -export function get_logging() { - return _log_level; +export function getLogging() { + return _logLevel; } export { Debug, Info, Warn, Error }; // Initialize logging level -init_logging(); +initLogging(); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/polyfill.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/polyfill.js index 648ceebc..0e458c86 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/polyfill.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/polyfill.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2020 The noVNC Authors * Licensed under MPL 2.0 or any later version (see LICENSE.txt) */ @@ -52,3 +52,10 @@ if (typeof Object.assign != 'function') { window.CustomEvent = CustomEvent; } })(); + +/* Number.isInteger() (taken from MDN) */ +Number.isInteger = Number.isInteger || function isInteger(value) { + return typeof value === 'number' && + isFinite(value) && + Math.floor(value) === value; +}; diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/strings.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/strings.js index 61f4f237..3dd4b29f 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/util/strings.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/util/strings.js @@ -1,14 +1,28 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. */ -/* - * Decode from UTF-8 - */ -export function decodeUTF8(utf8string) { - return decodeURIComponent(escape(utf8string)); +// Decode from UTF-8 +export function decodeUTF8(utf8string, allowLatin1=false) { + try { + return decodeURIComponent(escape(utf8string)); + } catch (e) { + if (e instanceof URIError) { + if (allowLatin1) { + // If we allow Latin1 we can ignore any decoding fails + // and in these cases return the original string + return utf8string; + } + } + throw e; + } +} + +// Encode to UTF-8 +export function encodeUTF8(DOMString) { + return unescape(encodeURIComponent(DOMString)); } diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/core/websock.js b/jupyter_desktop/share/web/noVNC-1.2.0/core/websock.js index 51b9a66f..3156aed6 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/core/websock.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/core/websock.js @@ -1,6 +1,6 @@ /* * Websock: high-performance binary WebSockets - * Copyright (C) 2018 The noVNC Authors + * Copyright (C) 2019 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * Websock is similar to the standard WebSocket object but with extra @@ -17,6 +17,8 @@ import * as Log from './util/logging.js'; // this has performance issues in some versions Chromium, and // doesn't gain a tremendous amount of performance increase in Firefox // at the moment. It may be valuable to turn it on in the future. +// Also copyWithin() for TypedArrays is not supported in IE 11 or +// Safari 13 (at the moment we want to support Safari 11). const ENABLE_COPYWITHIN = false; const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB @@ -27,7 +29,6 @@ export default class Websock { this._rQi = 0; // Receive queue index this._rQlen = 0; // Next write position in the receive queue this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB) - this._rQmax = this._rQbufferSize / 8; // called in init: this._rQ = new Uint8Array(this._rQbufferSize); this._rQ = null; // Receive queue @@ -143,7 +144,7 @@ export default class Websock { flush() { if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) { - this._websocket.send(this._encode_message()); + this._websocket.send(this._encodeMessage()); this._sQlen = 0; } } @@ -154,7 +155,7 @@ export default class Websock { this.flush(); } - send_string(str) { + sendString(str) { this.send(str.split('').map(chr => chr.charCodeAt(0))); } @@ -167,13 +168,13 @@ export default class Websock { this._eventHandlers[evt] = handler; } - _allocate_buffers() { + _allocateBuffers() { this._rQ = new Uint8Array(this._rQbufferSize); this._sQ = new Uint8Array(this._sQbufferSize); } init() { - this._allocate_buffers(); + this._allocateBuffers(); this._rQi = 0; this._websocket = null; } @@ -184,7 +185,7 @@ export default class Websock { this._websocket = new WebSocket(uri, protocols); this._websocket.binaryType = 'arraybuffer'; - this._websocket.onmessage = this._recv_message.bind(this); + this._websocket.onmessage = this._recvMessage.bind(this); this._websocket.onopen = () => { Log.Debug('>> WebSock.onopen'); if (this._websocket.protocol) { @@ -219,42 +220,46 @@ export default class Websock { } // private methods - _encode_message() { + _encodeMessage() { // Put in a binary arraybuffer // according to the spec, you can send ArrayBufferViews with the send method return new Uint8Array(this._sQ.buffer, 0, this._sQlen); } - _expand_compact_rQ(min_fit) { - const resizeNeeded = min_fit || this.rQlen > this._rQbufferSize / 2; + // We want to move all the unread data to the start of the queue, + // e.g. compacting. + // The function also expands the receive que if needed, and for + // performance reasons we combine these two actions to avoid + // unneccessary copying. + _expandCompactRQ(minFit) { + // if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place + // instead of resizing + const requiredBufferSize = (this._rQlen - this._rQi + minFit) * 8; + const resizeNeeded = this._rQbufferSize < requiredBufferSize; + if (resizeNeeded) { - if (!min_fit) { - // just double the size if we need to do compaction - this._rQbufferSize *= 2; - } else { - // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8 - this._rQbufferSize = (this.rQlen + min_fit) * 8; - } + // Make sure we always *at least* double the buffer size, and have at least space for 8x + // the current amount of data + this._rQbufferSize = Math.max(this._rQbufferSize * 2, requiredBufferSize); } // we don't want to grow unboundedly if (this._rQbufferSize > MAX_RQ_GROW_SIZE) { this._rQbufferSize = MAX_RQ_GROW_SIZE; - if (this._rQbufferSize - this.rQlen < min_fit) { + if (this._rQbufferSize - this.rQlen < minFit) { throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit"); } } if (resizeNeeded) { - const old_rQbuffer = this._rQ.buffer; - this._rQmax = this._rQbufferSize / 8; + const oldRQbuffer = this._rQ.buffer; this._rQ = new Uint8Array(this._rQbufferSize); - this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi)); + this._rQ.set(new Uint8Array(oldRQbuffer, this._rQi, this._rQlen - this._rQi)); } else { if (ENABLE_COPYWITHIN) { - this._rQ.copyWithin(0, this._rQi); + this._rQ.copyWithin(0, this._rQi, this._rQlen); } else { - this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi)); + this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi, this._rQlen - this._rQi)); } } @@ -262,26 +267,25 @@ export default class Websock { this._rQi = 0; } - _decode_message(data) { - // push arraybuffer values onto the end + // push arraybuffer values onto the end of the receive que + _DecodeMessage(data) { const u8 = new Uint8Array(data); if (u8.length > this._rQbufferSize - this._rQlen) { - this._expand_compact_rQ(u8.length); + this._expandCompactRQ(u8.length); } this._rQ.set(u8, this._rQlen); this._rQlen += u8.length; } - _recv_message(e) { - this._decode_message(e.data); + _recvMessage(e) { + this._DecodeMessage(e.data); if (this.rQlen > 0) { this._eventHandlers.message(); - // Compact the receive queue if (this._rQlen == this._rQi) { + // All data has now been processed, this means we + // can reset the receive queue. this._rQlen = 0; this._rQi = 0; - } else if (this._rQlen > this._rQmax) { - this._expand_compact_rQ(); } } else { Log.Debug("Ignoring empty message"); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/docs/API-internal.md b/jupyter_desktop/share/web/noVNC-1.2.0/docs/API-internal.md index 0b29afb6..cb4cc396 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/docs/API-internal.md +++ b/jupyter_desktop/share/web/noVNC-1.2.0/docs/API-internal.md @@ -11,9 +11,6 @@ official external API. ## 1.1 Module List -* __Mouse__ (core/input/mouse.js): Mouse input event handler with -limited touch support. - * __Keyboard__ (core/input/keyboard.js): Keyboard input event handler with non-US keyboard support. Translates keyDown and keyUp events to X11 keysym values. @@ -23,7 +20,7 @@ layered on the HTML5 canvas element. * __Websock__ (core/websock.js): Websock client from websockify with transparent binary data support. -[Websock API](https://github.com/novnc/websockify/wiki/websock.js) wiki page. +[Websock API](https://github.com/novnc/websockify-js/wiki/websock.js) wiki page. ## 1.2 Callbacks @@ -35,62 +32,38 @@ callback event name, and the callback function. ## 2. Modules -## 2.1 Mouse Module +## 2.1 Keyboard Module ### 2.1.1 Configuration Attributes -| name | type | mode | default | description -| ----------- | ---- | ---- | -------- | ------------ -| touchButton | int | RW | 1 | Button mask (1, 2, 4) for which click to send on touch devices. 0 means ignore clicks. - -### 2.1.2 Methods - -| name | parameters | description -| ------ | ---------- | ------------ -| grab | () | Begin capturing mouse events -| ungrab | () | Stop capturing mouse events - -### 2.1.2 Callbacks - -| name | parameters | description -| ------------- | ------------------- | ------------ -| onmousebutton | (x, y, down, bmask) | Handler for mouse button click/release -| onmousemove | (x, y) | Handler for mouse movement - - -## 2.2 Keyboard Module - -### 2.2.1 Configuration Attributes - None -### 2.2.2 Methods +### 2.1.2 Methods | name | parameters | description | ------ | ---------- | ------------ | grab | () | Begin capturing keyboard events | ungrab | () | Stop capturing keyboard events -### 2.2.3 Callbacks +### 2.1.3 Callbacks | name | parameters | description | ---------- | -------------------- | ------------ | onkeypress | (keysym, code, down) | Handler for key press/release -## 2.3 Display Module +## 2.2 Display Module -### 2.3.1 Configuration Attributes +### 2.2.1 Configuration Attributes | name | type | mode | default | description | ------------ | ----- | ---- | ------- | ------------ -| logo | raw | RW | | Logo to display when cleared: {"width": width, "height": height, "type": mime-type, "data": data} | scale | float | RW | 1.0 | Display area scale factor 0.0 - 1.0 | clipViewport | bool | RW | false | Use viewport clipping | width | int | RO | | Display area width | height | int | RO | | Display area height -### 2.3.2 Methods +### 2.2.2 Methods | name | parameters | description | ------------------ | ------------------------------------------------------- | ------------ @@ -100,12 +73,11 @@ None | absY | (y) | Return Y relative to the remote display | resize | (width, height) | Set width and height | flip | (from_queue) | Update the visible canvas with the contents of the rendering canvas -| clear | () | Clear the display (show logo if set) | pending | () | Check if there are waiting items in the render queue | flush | () | Resume processing the render queue unless it's empty | fillRect | (x, y, width, height, color, from_queue) | Draw a filled in rectangle | copyImage | (old_x, old_y, new_x, new_y, width, height, from_queue) | Copy a rectangular area -| imageRect | (x, y, mime, arr) | Draw a rectangle with an image +| imageRect | (x, y, width, height, mime, arr) | Draw a rectangle with an image | startTile | (x, y, width, height, color) | Begin updating a tile | subTile | (tile, x, y, w, h, color) | Update a sub-rectangle within the given tile | finishTile | () | Draw the current tile to the display @@ -115,7 +87,7 @@ None | drawImage | (img, x, y) | Draw image and track damage | autoscale | (containerWidth, containerHeight) | Scale the display -### 2.3.3 Callbacks +### 2.2.3 Callbacks | name | parameters | description | ------- | ---------- | ------------ diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/docs/API.md b/jupyter_desktop/share/web/noVNC-1.2.0/docs/API.md index d587429c..d78360a2 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/docs/API.md +++ b/jupyter_desktop/share/web/noVNC-1.2.0/docs/API.md @@ -24,13 +24,7 @@ protocol stream. `focusOnClick` - Is a `boolean` indicating if keyboard focus should automatically be moved to the remote session when a `mousedown` or `touchstart` - event is received. - -`touchButton` - - Is a `long` controlling the button mask that should be simulated - when a touch event is recieved. Uses the same values as - [`MouseEvent.button`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button). - Is set to `1` by default. + event is received. Enabled by default. `clipViewport` - Is a `boolean` indicating if the remote session should be clipped @@ -64,6 +58,19 @@ protocol stream. to the element containing the remote session screen. The default value is `rgb(40, 40, 40)` (solid gray color). +`qualityLevel` + - Is an `int` in range `[0-9]` controlling the desired JPEG quality. + Value `0` implies low quality and `9` implies high quality. + Default value is `6`. + +`compressionLevel` + - Is an `int` in range `[0-9]` controlling the desired compression + level. Value `0` means no compression. Level 1 uses a minimum of CPU + resources and achieves weak compression ratios, while level 9 offers + best compression but is slow in terms of CPU consumption on the server + side. Use high levels with very slow network connections. + Default value is `2`. + `capabilities` *Read only* - Is an `Object` indicating which optional extensions are available on the server. Some methods may only be called if the corresponding @@ -187,6 +194,10 @@ connection to a specified VNC server. - A `DOMString` specifying the ID to provide to any VNC repeater encountered. + `wsProtocols` + - An `Array` of `DOMString`s specifying the sub-protocols to use + in the WebSocket connection. Empty by default. + #### connect The `connect` event is fired after all the handshaking with the server @@ -371,5 +382,4 @@ to the remote server. ###### Parameters **`text`** - - A `DOMString` specifying the clipboard data to send. Currently only - characters from ISO 8859-1 are supported. + - A `DOMString` specifying the clipboard data to send. diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/docs/EMBEDDING.md b/jupyter_desktop/share/web/noVNC-1.2.0/docs/EMBEDDING.md index 5399b48b..6a5dcd80 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/docs/EMBEDDING.md +++ b/jupyter_desktop/share/web/noVNC-1.2.0/docs/EMBEDDING.md @@ -61,6 +61,10 @@ query string. Currently the following options are available: * `resize` - How to resize the remote session if it is not the same size as the browser window. Can be one of `off`, `scale` and `remote`. +* `quality` - The session JPEG quality level. Can be `0` to `9`. + +* `compression` - The session compression level. Can be `0` to `9`. + * `show_dot` - If a dot cursor should be shown when the remote server provides no local cursor, or provides a fully-transparent (invisible) cursor. diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/karma.conf.js b/jupyter_desktop/share/web/noVNC-1.2.0/karma.conf.js index 5cbd7a5d..c295b1f9 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/karma.conf.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/karma.conf.js @@ -1,48 +1,23 @@ // Karma configuration +// The Safari launcher is broken, so construct our own +function SafariBrowser(id, baseBrowserDecorator, args) { + baseBrowserDecorator(this); + + this._start = function(url) { + this._execCommand('/usr/bin/open', ['-W', '-n', '-a', 'Safari', url]); + } +} + +SafariBrowser.prototype = { + name: 'Safari' +} + module.exports = (config) => { - const customLaunchers = {}; let browsers = []; - let useSauce = false; - - // use Sauce when running on Travis - if (process.env.TRAVIS_JOB_NUMBER) { - useSauce = true; - } - - if (useSauce && process.env.TEST_BROWSER_NAME && process.env.TEST_BROWSER_NAME != 'PhantomJS') { - const names = process.env.TEST_BROWSER_NAME.split(','); - const platforms = process.env.TEST_BROWSER_OS.split(','); - const versions = process.env.TEST_BROWSER_VERSION - ? process.env.TEST_BROWSER_VERSION.split(',') - : [null]; - - for (let i = 0; i < names.length; i++) { - for (let j = 0; j < platforms.length; j++) { - for (let k = 0; k < versions.length; k++) { - let launcher_name = 'sl_' + platforms[j].replace(/[^a-zA-Z0-9]/g, '') + '_' + names[i]; - if (versions[k]) { - launcher_name += '_' + versions[k]; - } - - customLaunchers[launcher_name] = { - base: 'SauceLabs', - browserName: names[i], - platform: platforms[j], - }; - - if (versions[i]) { - customLaunchers[launcher_name].version = versions[k]; - } - } - } - } - browsers = Object.keys(customLaunchers); - } else { - useSauce = false; - //browsers = ['PhantomJS']; - browsers = []; + if (process.env.TEST_BROWSER_NAME) { + browsers = process.env.TEST_BROWSER_NAME.split(','); } const my_conf = { @@ -80,7 +55,11 @@ module.exports = (config) => { exclude: [ ], - customLaunchers: customLaunchers, + plugins: [ + 'karma-*', + '@chiragrupani/karma-chromium-edge-launcher', + { 'launcher:Safari': [ 'type', SafariBrowser ] }, + ], // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher @@ -92,14 +71,6 @@ module.exports = (config) => { reporters: ['mocha'], - // web server port - port: 9876, - - - // enable / disable colors in the output (reporters and logs) - colors: true, - - // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, @@ -111,24 +82,7 @@ module.exports = (config) => { // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, - - // Increase timeout in case connection is slow/we run more browsers than possible - // (we currently get 3 for free, and we try to run 7, so it can take a while) - captureTimeout: 240000, - - // similarly to above - browserNoActivityTimeout: 100000, }; - if (useSauce) { - my_conf.reporters.push('saucelabs'); - my_conf.captureTimeout = 0; // use SL timeout - my_conf.sauceLabs = { - testName: 'noVNC Tests (all)', - startConnect: false, - tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER - }; - } - config.set(my_conf); }; diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/package.json b/jupyter_desktop/share/web/noVNC-1.2.0/package.json index 2d84a5f3..8fc04e50 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/package.json +++ b/jupyter_desktop/share/web/noVNC-1.2.0/package.json @@ -1,6 +1,6 @@ { "name": "@novnc/novnc", - "version": "1.1.0", + "version": "1.2.0", "description": "An HTML5 VNC client", "browser": "lib/rfb", "directories": { @@ -19,7 +19,7 @@ "vendor/pako" ], "scripts": { - "lint": "eslint app core po tests utils", + "lint": "eslint app core po/po2js po/xgettext-html tests utils", "test": "karma start karma.conf.js", "prepublish": "node ./utils/use_require.js --as commonjs --clean" }, @@ -40,36 +40,42 @@ }, "homepage": "https://github.com/novnc/noVNC", "devDependencies": { - "babel-core": "^6.22.1", - "babel-plugin-add-module-exports": "^0.2.1", + "@babel/core": "*", + "@babel/plugin-syntax-dynamic-import": "*", + "@babel/plugin-transform-modules-amd": "*", + "@babel/plugin-transform-modules-commonjs": "*", + "@babel/plugin-transform-modules-systemjs": "*", + "@babel/plugin-transform-modules-umd": "*", + "@babel/preset-env": "*", + "@babel/cli": "*", "babel-plugin-import-redirect": "*", - "babel-plugin-syntax-dynamic-import": "^6.18.0", - "babel-plugin-transform-es2015-modules-amd": "^6.22.0", - "babel-plugin-transform-es2015-modules-commonjs": "^6.18.0", - "babel-plugin-transform-es2015-modules-systemjs": "^6.22.0", - "babel-plugin-transform-es2015-modules-umd": "^6.22.0", - "babel-preset-es2015": "^6.24.1", - "babelify": "^7.3.0", - "browserify": "^13.1.0", - "chai": "^3.5.0", - "commander": "^2.9.0", - "es-module-loader": "^2.1.0", - "eslint": "^4.16.0", - "fs-extra": "^1.0.0", + "browserify": "*", + "babelify": "*", + "core-js": "*", + "chai": "*", + "commander": "*", + "es-module-loader": "*", + "eslint": "*", + "fs-extra": "*", "jsdom": "*", - "karma": "^1.3.0", - "karma-mocha": "^1.3.0", - "karma-mocha-reporter": "^2.2.0", - "karma-sauce-launcher": "^1.0.0", - "karma-sinon-chai": "^2.0.0", - "mocha": "^3.1.2", + "karma": "*", + "karma-mocha": "*", + "karma-chrome-launcher": "*", + "@chiragrupani/karma-chromium-edge-launcher": "*", + "karma-firefox-launcher": "*", + "karma-ie-launcher": "*", + "karma-mocha-reporter": "*", + "karma-safari-launcher": "*", + "karma-script-launcher": "*", + "karma-sinon-chai": "*", + "mocha": "*", "node-getopt": "*", "po2json": "*", - "requirejs": "^2.3.2", - "rollup": "^0.41.4", - "rollup-plugin-node-resolve": "^2.0.0", - "sinon": "^4.0.0", - "sinon-chai": "^2.8.0" + "requirejs": "*", + "rollup": "*", + "rollup-plugin-node-resolve": "*", + "sinon": "*", + "sinon-chai": "*" }, "dependencies": {}, "keywords": [ diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/po/.eslintrc b/jupyter_desktop/share/web/noVNC-1.2.0/po/.eslintrc new file mode 100644 index 00000000..a0157e2a --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/po/.eslintrc @@ -0,0 +1,5 @@ +{ + "env": { + "node": true, + }, +} diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/po/Makefile b/jupyter_desktop/share/web/noVNC-1.2.0/po/Makefile index 6dbd8304..cce293d7 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/po/Makefile +++ b/jupyter_desktop/share/web/noVNC-1.2.0/po/Makefile @@ -1,7 +1,7 @@ all: .PHONY: update-po update-js update-pot -LINGUAS := cs de el es ko nl pl ru sv tr zh_CN zh_TW +LINGUAS := cs de el es ja ko nl pl ru sv tr zh_CN zh_TW VERSION := $(shell grep '"version"' ../package.json | cut -d '"' -f 4) diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/po/ja.po b/jupyter_desktop/share/web/noVNC-1.2.0/po/ja.po new file mode 100644 index 00000000..7fc53ed5 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/po/ja.po @@ -0,0 +1,303 @@ +# Japanese translations for noVNC package +# noVNC パッケージに対する日訳 +# Copyright (C) 2019 The noVNC Authors +# This file is distributed under the same license as the noVNC package. +# nnn1590 , 2019-2020. +# +msgid "" +msgstr "" +"Project-Id-Version: noVNC 1.1.0\n" +"Report-Msgid-Bugs-To: novnc@googlegroups.com\n" +"POT-Creation-Date: 2019-01-16 11:06+0100\n" +"PO-Revision-Date: 2020-06-15 17:44+0900\n" +"Last-Translator: nnn1590 \n" +"Language-Team: Japanese\n" +"Language: ja\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: ../app/ui.js:387 +msgid "Connecting..." +msgstr "接続しています..." + +#: ../app/ui.js:394 +msgid "Disconnecting..." +msgstr "切断しています..." + +#: ../app/ui.js:400 +msgid "Reconnecting..." +msgstr "再接続しています..." + +#: ../app/ui.js:405 +msgid "Internal error" +msgstr "内部エラー" + +#: ../app/ui.js:995 +msgid "Must set host" +msgstr "ホストを設定する必要があります" + +#: ../app/ui.js:1077 +msgid "Connected (encrypted) to " +msgstr "接続しました (暗号化済み): " + +#: ../app/ui.js:1079 +msgid "Connected (unencrypted) to " +msgstr "接続しました (暗号化されていません): " + +#: ../app/ui.js:1102 +msgid "Something went wrong, connection is closed" +msgstr "何かが問題で、接続が閉じられました" + +#: ../app/ui.js:1105 +msgid "Failed to connect to server" +msgstr "サーバーへの接続に失敗しました" + +#: ../app/ui.js:1115 +msgid "Disconnected" +msgstr "切断しました" + +#: ../app/ui.js:1128 +msgid "New connection has been rejected with reason: " +msgstr "新規接続は次の理由で拒否されました: " + +#: ../app/ui.js:1131 +msgid "New connection has been rejected" +msgstr "新規接続は拒否されました" + +#: ../app/ui.js:1151 +msgid "Password is required" +msgstr "パスワードが必要です" + +#: ../vnc.html:84 +msgid "noVNC encountered an error:" +msgstr "noVNC でエラーが発生しました:" + +#: ../vnc.html:94 +msgid "Hide/Show the control bar" +msgstr "コントロールバーを隠す/表示する" + +#: ../vnc.html:101 +msgid "Move/Drag Viewport" +msgstr "ビューポートを移動/ドラッグ" + +#: ../vnc.html:101 +msgid "viewport drag" +msgstr "ビューポートをドラッグ" + +#: ../vnc.html:107 ../vnc.html:110 ../vnc.html:113 ../vnc.html:116 +msgid "Active Mouse Button" +msgstr "アクティブなマウスボタン" + +#: ../vnc.html:107 +msgid "No mousebutton" +msgstr "マウスボタンなし" + +#: ../vnc.html:110 +msgid "Left mousebutton" +msgstr "左マウスボタン" + +#: ../vnc.html:113 +msgid "Middle mousebutton" +msgstr "中マウスボタン" + +#: ../vnc.html:116 +msgid "Right mousebutton" +msgstr "右マウスボタン" + +#: ../vnc.html:119 +msgid "Keyboard" +msgstr "キーボード" + +#: ../vnc.html:119 +msgid "Show Keyboard" +msgstr "キーボードを表示" + +#: ../vnc.html:126 +msgid "Extra keys" +msgstr "追加キー" + +#: ../vnc.html:126 +msgid "Show Extra Keys" +msgstr "追加キーを表示" + +#: ../vnc.html:131 +msgid "Ctrl" +msgstr "Ctrl" + +#: ../vnc.html:131 +msgid "Toggle Ctrl" +msgstr "Ctrl キーを切り替え" + +#: ../vnc.html:134 +msgid "Alt" +msgstr "Alt" + +#: ../vnc.html:134 +msgid "Toggle Alt" +msgstr "Alt キーを切り替え" + +#: ../vnc.html:137 +msgid "Toggle Windows" +msgstr "Windows キーを切り替え" + +#: ../vnc.html:137 +msgid "Windows" +msgstr "Windows" + +#: ../vnc.html:140 +msgid "Send Tab" +msgstr "Tab キーを送信" + +#: ../vnc.html:140 +msgid "Tab" +msgstr "Tab" + +#: ../vnc.html:143 +msgid "Esc" +msgstr "Esc" + +#: ../vnc.html:143 +msgid "Send Escape" +msgstr "Escape キーを送信" + +#: ../vnc.html:146 +msgid "Ctrl+Alt+Del" +msgstr "Ctrl+Alt+Del" + +#: ../vnc.html:146 +msgid "Send Ctrl-Alt-Del" +msgstr "Ctrl-Alt-Del を送信" + +#: ../vnc.html:154 +msgid "Shutdown/Reboot" +msgstr "シャットダウン/再起動" + +#: ../vnc.html:154 +msgid "Shutdown/Reboot..." +msgstr "シャットダウン/再起動..." + +#: ../vnc.html:160 +msgid "Power" +msgstr "電源" + +#: ../vnc.html:162 +msgid "Shutdown" +msgstr "シャットダウン" + +#: ../vnc.html:163 +msgid "Reboot" +msgstr "再起動" + +#: ../vnc.html:164 +msgid "Reset" +msgstr "リセット" + +#: ../vnc.html:169 ../vnc.html:175 +msgid "Clipboard" +msgstr "クリップボード" + +#: ../vnc.html:179 +msgid "Clear" +msgstr "クリア" + +#: ../vnc.html:185 +msgid "Fullscreen" +msgstr "全画面表示" + +#: ../vnc.html:190 ../vnc.html:197 +msgid "Settings" +msgstr "設定" + +#: ../vnc.html:200 +msgid "Shared Mode" +msgstr "共有モード" + +#: ../vnc.html:203 +msgid "View Only" +msgstr "表示のみ" + +#: ../vnc.html:207 +msgid "Clip to Window" +msgstr "ウィンドウにクリップ" + +#: ../vnc.html:210 +msgid "Scaling Mode:" +msgstr "スケーリングモード:" + +#: ../vnc.html:212 +msgid "None" +msgstr "なし" + +#: ../vnc.html:213 +msgid "Local Scaling" +msgstr "ローカルスケーリング" + +#: ../vnc.html:214 +msgid "Remote Resizing" +msgstr "リモートでリサイズ" + +#: ../vnc.html:219 +msgid "Advanced" +msgstr "高度" + +#: ../vnc.html:222 +msgid "Repeater ID:" +msgstr "リピーター ID:" + +#: ../vnc.html:226 +msgid "WebSocket" +msgstr "WebSocket" + +#: ../vnc.html:229 +msgid "Encrypt" +msgstr "暗号化" + +#: ../vnc.html:232 +msgid "Host:" +msgstr "ホスト:" + +#: ../vnc.html:236 +msgid "Port:" +msgstr "ポート:" + +#: ../vnc.html:240 +msgid "Path:" +msgstr "パス:" + +#: ../vnc.html:247 +msgid "Automatic Reconnect" +msgstr "自動再接続" + +#: ../vnc.html:250 +msgid "Reconnect Delay (ms):" +msgstr "再接続する遅延 (ミリ秒):" + +#: ../vnc.html:255 +msgid "Show Dot when No Cursor" +msgstr "カーソルがないときにドットを表示" + +#: ../vnc.html:260 +msgid "Logging:" +msgstr "ロギング:" + +#: ../vnc.html:272 +msgid "Disconnect" +msgstr "切断" + +#: ../vnc.html:291 +msgid "Connect" +msgstr "接続" + +#: ../vnc.html:301 +msgid "Password:" +msgstr "パスワード:" + +#: ../vnc.html:305 +msgid "Send Password" +msgstr "パスワードを送信" + +#: ../vnc.html:315 +msgid "Cancel" +msgstr "キャンセル" diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/po/noVNC.pot b/jupyter_desktop/share/web/noVNC-1.2.0/po/noVNC.pot index 200be01d..01db78f0 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/po/noVNC.pot +++ b/jupyter_desktop/share/web/noVNC-1.2.0/po/noVNC.pot @@ -6,9 +6,9 @@ #, fuzzy msgid "" msgstr "" -"Project-Id-Version: noVNC 1.1.0\n" +"Project-Id-Version: noVNC 1.2.0\n" "Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2019-01-16 11:06+0100\n" +"POT-Creation-Date: 2020-07-03 16:11+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -17,286 +17,282 @@ msgstr "" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" -#: ../app/ui.js:387 +#: ../app/ui.js:394 msgid "Connecting..." msgstr "" -#: ../app/ui.js:394 +#: ../app/ui.js:401 msgid "Disconnecting..." msgstr "" -#: ../app/ui.js:400 +#: ../app/ui.js:407 msgid "Reconnecting..." msgstr "" -#: ../app/ui.js:405 +#: ../app/ui.js:412 msgid "Internal error" msgstr "" -#: ../app/ui.js:995 +#: ../app/ui.js:1008 msgid "Must set host" msgstr "" -#: ../app/ui.js:1077 +#: ../app/ui.js:1090 msgid "Connected (encrypted) to " msgstr "" -#: ../app/ui.js:1079 +#: ../app/ui.js:1092 msgid "Connected (unencrypted) to " msgstr "" -#: ../app/ui.js:1102 +#: ../app/ui.js:1115 msgid "Something went wrong, connection is closed" msgstr "" -#: ../app/ui.js:1105 +#: ../app/ui.js:1118 msgid "Failed to connect to server" msgstr "" -#: ../app/ui.js:1115 +#: ../app/ui.js:1128 msgid "Disconnected" msgstr "" -#: ../app/ui.js:1128 +#: ../app/ui.js:1143 msgid "New connection has been rejected with reason: " msgstr "" -#: ../app/ui.js:1131 +#: ../app/ui.js:1146 msgid "New connection has been rejected" msgstr "" -#: ../app/ui.js:1151 -msgid "Password is required" +#: ../app/ui.js:1181 +msgid "Credentials are required" msgstr "" -#: ../vnc.html:84 +#: ../vnc.html:74 msgid "noVNC encountered an error:" msgstr "" -#: ../vnc.html:94 +#: ../vnc.html:84 msgid "Hide/Show the control bar" msgstr "" -#: ../vnc.html:101 -msgid "Move/Drag Viewport" -msgstr "" - -#: ../vnc.html:101 -msgid "viewport drag" +#: ../vnc.html:91 +msgid "Drag" msgstr "" -#: ../vnc.html:107 ../vnc.html:110 ../vnc.html:113 ../vnc.html:116 -msgid "Active Mouse Button" -msgstr "" - -#: ../vnc.html:107 -msgid "No mousebutton" -msgstr "" - -#: ../vnc.html:110 -msgid "Left mousebutton" -msgstr "" - -#: ../vnc.html:113 -msgid "Middle mousebutton" -msgstr "" - -#: ../vnc.html:116 -msgid "Right mousebutton" +#: ../vnc.html:91 +msgid "Move/Drag Viewport" msgstr "" -#: ../vnc.html:119 +#: ../vnc.html:97 msgid "Keyboard" msgstr "" -#: ../vnc.html:119 +#: ../vnc.html:97 msgid "Show Keyboard" msgstr "" -#: ../vnc.html:126 +#: ../vnc.html:102 msgid "Extra keys" msgstr "" -#: ../vnc.html:126 +#: ../vnc.html:102 msgid "Show Extra Keys" msgstr "" -#: ../vnc.html:131 +#: ../vnc.html:107 msgid "Ctrl" msgstr "" -#: ../vnc.html:131 +#: ../vnc.html:107 msgid "Toggle Ctrl" msgstr "" -#: ../vnc.html:134 +#: ../vnc.html:110 msgid "Alt" msgstr "" -#: ../vnc.html:134 +#: ../vnc.html:110 msgid "Toggle Alt" msgstr "" -#: ../vnc.html:137 +#: ../vnc.html:113 msgid "Toggle Windows" msgstr "" -#: ../vnc.html:137 +#: ../vnc.html:113 msgid "Windows" msgstr "" -#: ../vnc.html:140 +#: ../vnc.html:116 msgid "Send Tab" msgstr "" -#: ../vnc.html:140 +#: ../vnc.html:116 msgid "Tab" msgstr "" -#: ../vnc.html:143 +#: ../vnc.html:119 msgid "Esc" msgstr "" -#: ../vnc.html:143 +#: ../vnc.html:119 msgid "Send Escape" msgstr "" -#: ../vnc.html:146 +#: ../vnc.html:122 msgid "Ctrl+Alt+Del" msgstr "" -#: ../vnc.html:146 +#: ../vnc.html:122 msgid "Send Ctrl-Alt-Del" msgstr "" -#: ../vnc.html:154 +#: ../vnc.html:129 msgid "Shutdown/Reboot" msgstr "" -#: ../vnc.html:154 +#: ../vnc.html:129 msgid "Shutdown/Reboot..." msgstr "" -#: ../vnc.html:160 +#: ../vnc.html:135 msgid "Power" msgstr "" -#: ../vnc.html:162 +#: ../vnc.html:137 msgid "Shutdown" msgstr "" -#: ../vnc.html:163 +#: ../vnc.html:138 msgid "Reboot" msgstr "" -#: ../vnc.html:164 +#: ../vnc.html:139 msgid "Reset" msgstr "" -#: ../vnc.html:169 ../vnc.html:175 +#: ../vnc.html:144 ../vnc.html:150 msgid "Clipboard" msgstr "" -#: ../vnc.html:179 +#: ../vnc.html:154 msgid "Clear" msgstr "" -#: ../vnc.html:185 +#: ../vnc.html:160 msgid "Fullscreen" msgstr "" -#: ../vnc.html:190 ../vnc.html:197 +#: ../vnc.html:165 ../vnc.html:172 msgid "Settings" msgstr "" -#: ../vnc.html:200 +#: ../vnc.html:175 msgid "Shared Mode" msgstr "" -#: ../vnc.html:203 +#: ../vnc.html:178 msgid "View Only" msgstr "" -#: ../vnc.html:207 +#: ../vnc.html:182 msgid "Clip to Window" msgstr "" -#: ../vnc.html:210 +#: ../vnc.html:185 msgid "Scaling Mode:" msgstr "" -#: ../vnc.html:212 +#: ../vnc.html:187 msgid "None" msgstr "" -#: ../vnc.html:213 +#: ../vnc.html:188 msgid "Local Scaling" msgstr "" -#: ../vnc.html:214 +#: ../vnc.html:189 msgid "Remote Resizing" msgstr "" -#: ../vnc.html:219 +#: ../vnc.html:194 msgid "Advanced" msgstr "" -#: ../vnc.html:222 +#: ../vnc.html:197 +msgid "Quality:" +msgstr "" + +#: ../vnc.html:201 +msgid "Compression level:" +msgstr "" + +#: ../vnc.html:206 msgid "Repeater ID:" msgstr "" -#: ../vnc.html:226 +#: ../vnc.html:210 msgid "WebSocket" msgstr "" -#: ../vnc.html:229 +#: ../vnc.html:213 msgid "Encrypt" msgstr "" -#: ../vnc.html:232 +#: ../vnc.html:216 msgid "Host:" msgstr "" -#: ../vnc.html:236 +#: ../vnc.html:220 msgid "Port:" msgstr "" -#: ../vnc.html:240 +#: ../vnc.html:224 msgid "Path:" msgstr "" -#: ../vnc.html:247 +#: ../vnc.html:231 msgid "Automatic Reconnect" msgstr "" -#: ../vnc.html:250 +#: ../vnc.html:234 msgid "Reconnect Delay (ms):" msgstr "" -#: ../vnc.html:255 +#: ../vnc.html:239 msgid "Show Dot when No Cursor" msgstr "" -#: ../vnc.html:260 +#: ../vnc.html:244 msgid "Logging:" msgstr "" -#: ../vnc.html:272 +#: ../vnc.html:253 +msgid "Version:" +msgstr "" + +#: ../vnc.html:261 msgid "Disconnect" msgstr "" -#: ../vnc.html:291 +#: ../vnc.html:280 msgid "Connect" msgstr "" -#: ../vnc.html:301 +#: ../vnc.html:290 +msgid "Username:" +msgstr "" + +#: ../vnc.html:294 msgid "Password:" msgstr "" -#: ../vnc.html:305 -msgid "Send Password" +#: ../vnc.html:298 +msgid "Send Credentials" msgstr "" -#: ../vnc.html:315 +#: ../vnc.html:308 msgid "Cancel" msgstr "" diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/po/po2js b/jupyter_desktop/share/web/noVNC-1.2.0/po/po2js index 03c14900..fc6e8810 100755 --- a/jupyter_desktop/share/web/noVNC-1.2.0/po/po2js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/po/po2js @@ -22,17 +22,17 @@ const fs = require('fs'); const po2json = require("po2json"); const opt = getopt.create([ - ['h' , 'help' , 'display this help'], + ['h', 'help', 'display this help'], ]).bindHelp().parseSystem(); if (opt.argv.length != 2) { - console.error("Incorrect number of arguments given"); - process.exit(1); + console.error("Incorrect number of arguments given"); + process.exit(1); } const data = po2json.parseFileSync(opt.argv[0]); -const bodyPart = Object.keys(data).filter((msgid) => msgid !== "").map((msgid) => { +const bodyPart = Object.keys(data).filter(msgid => msgid !== "").map((msgid) => { if (msgid === "") return; const msgstr = data[msgid][1]; return " " + JSON.stringify(msgid) + ": " + JSON.stringify(msgstr); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/po/sv.po b/jupyter_desktop/share/web/noVNC-1.2.0/po/sv.po index f7955662..53e33f76 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/po/sv.po +++ b/jupyter_desktop/share/web/noVNC-1.2.0/po/sv.po @@ -1,15 +1,15 @@ # Swedish translations for noVNC package -# Svenska översättningar för paket noVNC. -# Copyright (C) 2018 The noVNC Authors +# Svenska översättningar för paketet noVNC. +# Copyright (C) 2020 The noVNC Authors # This file is distributed under the same license as the noVNC package. -# Samuel Mannehed , 2019. +# Samuel Mannehed , 2020. # msgid "" msgstr "" -"Project-Id-Version: noVNC 1.1.0\n" +"Project-Id-Version: noVNC 1.2.0\n" "Report-Msgid-Bugs-To: novnc@googlegroups.com\n" -"POT-Creation-Date: 2019-01-16 11:06+0100\n" -"PO-Revision-Date: 2019-04-08 10:18+0200\n" +"POT-Creation-Date: 2020-07-03 16:11+0200\n" +"PO-Revision-Date: 2020-07-08 23:18+0200\n" "Last-Translator: Samuel Mannehed \n" "Language-Team: none\n" "Language: sv\n" @@ -19,298 +19,282 @@ msgstr "" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Poedit 2.0.3\n" -#: ../app/ui.js:387 +#: ../app/ui.js:394 msgid "Connecting..." msgstr "Ansluter..." -#: ../app/ui.js:394 +#: ../app/ui.js:401 msgid "Disconnecting..." msgstr "Kopplar ner..." -#: ../app/ui.js:400 +#: ../app/ui.js:407 msgid "Reconnecting..." msgstr "Återansluter..." -#: ../app/ui.js:405 +#: ../app/ui.js:412 msgid "Internal error" msgstr "Internt fel" -#: ../app/ui.js:995 +#: ../app/ui.js:1008 msgid "Must set host" msgstr "Du måste specifiera en värd" -#: ../app/ui.js:1077 +#: ../app/ui.js:1090 msgid "Connected (encrypted) to " msgstr "Ansluten (krypterat) till " -#: ../app/ui.js:1079 +#: ../app/ui.js:1092 msgid "Connected (unencrypted) to " msgstr "Ansluten (okrypterat) till " -#: ../app/ui.js:1102 +#: ../app/ui.js:1115 msgid "Something went wrong, connection is closed" msgstr "Något gick fel, anslutningen avslutades" -#: ../app/ui.js:1105 +#: ../app/ui.js:1118 msgid "Failed to connect to server" msgstr "Misslyckades att ansluta till servern" -#: ../app/ui.js:1115 +#: ../app/ui.js:1128 msgid "Disconnected" msgstr "Frånkopplad" -#: ../app/ui.js:1128 +#: ../app/ui.js:1143 msgid "New connection has been rejected with reason: " msgstr "Ny anslutning har blivit nekad med följande skäl: " -#: ../app/ui.js:1131 +#: ../app/ui.js:1146 msgid "New connection has been rejected" msgstr "Ny anslutning har blivit nekad" -#: ../app/ui.js:1151 -msgid "Password is required" -msgstr "Lösenord krävs" +#: ../app/ui.js:1181 +msgid "Credentials are required" +msgstr "Användaruppgifter krävs" -#: ../vnc.html:84 +#: ../vnc.html:74 msgid "noVNC encountered an error:" msgstr "noVNC stötte på ett problem:" -#: ../vnc.html:94 +#: ../vnc.html:84 msgid "Hide/Show the control bar" msgstr "Göm/Visa kontrollbaren" -#: ../vnc.html:101 +#: ../vnc.html:91 +msgid "Drag" +msgstr "Dra" + +#: ../vnc.html:91 msgid "Move/Drag Viewport" msgstr "Flytta/Dra Vyn" -#: ../vnc.html:101 -msgid "viewport drag" -msgstr "dra vy" - -#: ../vnc.html:107 ../vnc.html:110 ../vnc.html:113 ../vnc.html:116 -msgid "Active Mouse Button" -msgstr "Aktiv musknapp" - -#: ../vnc.html:107 -msgid "No mousebutton" -msgstr "Ingen musknapp" - -#: ../vnc.html:110 -msgid "Left mousebutton" -msgstr "Vänster musknapp" - -#: ../vnc.html:113 -msgid "Middle mousebutton" -msgstr "Mitten-musknapp" - -#: ../vnc.html:116 -msgid "Right mousebutton" -msgstr "Höger musknapp" - -#: ../vnc.html:119 +#: ../vnc.html:97 msgid "Keyboard" msgstr "Tangentbord" -#: ../vnc.html:119 +#: ../vnc.html:97 msgid "Show Keyboard" msgstr "Visa Tangentbord" -#: ../vnc.html:126 +#: ../vnc.html:102 msgid "Extra keys" msgstr "Extraknappar" -#: ../vnc.html:126 +#: ../vnc.html:102 msgid "Show Extra Keys" msgstr "Visa Extraknappar" -#: ../vnc.html:131 +#: ../vnc.html:107 msgid "Ctrl" msgstr "Ctrl" -#: ../vnc.html:131 +#: ../vnc.html:107 msgid "Toggle Ctrl" msgstr "Växla Ctrl" -#: ../vnc.html:134 +#: ../vnc.html:110 msgid "Alt" msgstr "Alt" -#: ../vnc.html:134 +#: ../vnc.html:110 msgid "Toggle Alt" msgstr "Växla Alt" -#: ../vnc.html:137 +#: ../vnc.html:113 msgid "Toggle Windows" msgstr "Växla Windows" -#: ../vnc.html:137 +#: ../vnc.html:113 msgid "Windows" msgstr "Windows" -#: ../vnc.html:140 +#: ../vnc.html:116 msgid "Send Tab" msgstr "Skicka Tab" -#: ../vnc.html:140 +#: ../vnc.html:116 msgid "Tab" msgstr "Tab" -#: ../vnc.html:143 +#: ../vnc.html:119 msgid "Esc" msgstr "Esc" -#: ../vnc.html:143 +#: ../vnc.html:119 msgid "Send Escape" msgstr "Skicka Escape" -#: ../vnc.html:146 +#: ../vnc.html:122 msgid "Ctrl+Alt+Del" msgstr "Ctrl+Alt+Del" -#: ../vnc.html:146 +#: ../vnc.html:122 msgid "Send Ctrl-Alt-Del" msgstr "Skicka Ctrl-Alt-Del" -#: ../vnc.html:154 +#: ../vnc.html:129 msgid "Shutdown/Reboot" msgstr "Stäng av/Boota om" -#: ../vnc.html:154 +#: ../vnc.html:129 msgid "Shutdown/Reboot..." msgstr "Stäng av/Boota om..." -#: ../vnc.html:160 +#: ../vnc.html:135 msgid "Power" msgstr "Ström" -#: ../vnc.html:162 +#: ../vnc.html:137 msgid "Shutdown" msgstr "Stäng av" -#: ../vnc.html:163 +#: ../vnc.html:138 msgid "Reboot" msgstr "Boota om" -#: ../vnc.html:164 +#: ../vnc.html:139 msgid "Reset" msgstr "Återställ" -#: ../vnc.html:169 ../vnc.html:175 +#: ../vnc.html:144 ../vnc.html:150 msgid "Clipboard" msgstr "Urklipp" -#: ../vnc.html:179 +#: ../vnc.html:154 msgid "Clear" msgstr "Rensa" -#: ../vnc.html:185 +#: ../vnc.html:160 msgid "Fullscreen" msgstr "Fullskärm" -#: ../vnc.html:190 ../vnc.html:197 +#: ../vnc.html:165 ../vnc.html:172 msgid "Settings" msgstr "Inställningar" -#: ../vnc.html:200 +#: ../vnc.html:175 msgid "Shared Mode" msgstr "Delat Läge" -#: ../vnc.html:203 +#: ../vnc.html:178 msgid "View Only" msgstr "Endast Visning" -#: ../vnc.html:207 +#: ../vnc.html:182 msgid "Clip to Window" msgstr "Begränsa till Fönster" -#: ../vnc.html:210 +#: ../vnc.html:185 msgid "Scaling Mode:" msgstr "Skalningsläge:" -#: ../vnc.html:212 +#: ../vnc.html:187 msgid "None" msgstr "Ingen" -#: ../vnc.html:213 +#: ../vnc.html:188 msgid "Local Scaling" msgstr "Lokal Skalning" -#: ../vnc.html:214 +#: ../vnc.html:189 msgid "Remote Resizing" msgstr "Ändra Storlek" -#: ../vnc.html:219 +#: ../vnc.html:194 msgid "Advanced" msgstr "Avancerat" -#: ../vnc.html:222 +#: ../vnc.html:197 +msgid "Quality:" +msgstr "Kvalitet:" + +#: ../vnc.html:201 +msgid "Compression level:" +msgstr "Kompressionsnivå:" + +#: ../vnc.html:206 msgid "Repeater ID:" msgstr "Repeater-ID:" -#: ../vnc.html:226 +#: ../vnc.html:210 msgid "WebSocket" msgstr "WebSocket" -#: ../vnc.html:229 +#: ../vnc.html:213 msgid "Encrypt" msgstr "Kryptera" -#: ../vnc.html:232 +#: ../vnc.html:216 msgid "Host:" msgstr "Värd:" -#: ../vnc.html:236 +#: ../vnc.html:220 msgid "Port:" msgstr "Port:" -#: ../vnc.html:240 +#: ../vnc.html:224 msgid "Path:" msgstr "Sökväg:" -#: ../vnc.html:247 +#: ../vnc.html:231 msgid "Automatic Reconnect" msgstr "Automatisk Återanslutning" -#: ../vnc.html:250 +#: ../vnc.html:234 msgid "Reconnect Delay (ms):" msgstr "Fördröjning (ms):" -#: ../vnc.html:255 +#: ../vnc.html:239 msgid "Show Dot when No Cursor" msgstr "Visa prick när ingen muspekare finns" -#: ../vnc.html:260 +#: ../vnc.html:244 msgid "Logging:" msgstr "Loggning:" -#: ../vnc.html:272 +#: ../vnc.html:253 +msgid "Version:" +msgstr "Version:" + +#: ../vnc.html:261 msgid "Disconnect" msgstr "Koppla från" -#: ../vnc.html:291 +#: ../vnc.html:280 msgid "Connect" msgstr "Anslut" -#: ../vnc.html:301 +#: ../vnc.html:290 +msgid "Username:" +msgstr "Användarnamn:" + +#: ../vnc.html:294 msgid "Password:" msgstr "Lösenord:" -#: ../vnc.html:305 -msgid "Send Password" -msgstr "Skicka lösenord" +#: ../vnc.html:298 +msgid "Send Credentials" +msgstr "Skicka Användaruppgifter" -#: ../vnc.html:315 +#: ../vnc.html:308 msgid "Cancel" -msgstr "Avbryt" - -#~ msgid "Disconnect timeout" -#~ msgstr "Det tog för lång tid att koppla ner" - -#~ msgid "Local Downscaling" -#~ msgstr "Lokal Nedskalning" - -#~ msgid "Local Cursor" -#~ msgstr "Lokal Muspekare" - -#~ msgid "Canvas not supported." -#~ msgstr "Canvas stöds ej" +msgstr "Avbryt" \ No newline at end of file diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/po/xgettext-html b/jupyter_desktop/share/web/noVNC-1.2.0/po/xgettext-html index 547f5687..bb30d3bc 100755 --- a/jupyter_desktop/share/web/noVNC-1.2.0/po/xgettext-html +++ b/jupyter_desktop/share/web/noVNC-1.2.0/po/xgettext-html @@ -10,8 +10,8 @@ const jsdom = require("jsdom"); const fs = require("fs"); const opt = getopt.create([ - ['o' , 'output=FILE' , 'write output to specified file'], - ['h' , 'help' , 'display this help'], + ['o', 'output=FILE', 'write output to specified file'], + ['h', 'help', 'display this help'], ]).bindHelp().parseSystem(); const strings = {}; @@ -22,7 +22,7 @@ function addString(str, location) { } if (strings[str] === undefined) { - strings[str] = {} + strings[str] = {}; } strings[str][location] = null; } @@ -74,7 +74,7 @@ function process(elem, locator, enabled) { } for (let i = 0; i < elem.childNodes.length; i++) { - node = elem.childNodes[i]; + let node = elem.childNodes[i]; if (node.nodeType === node.ELEMENT_NODE) { process(node, locator, enabled); } else if (node.nodeType === node.TEXT_NODE && enabled) { @@ -89,18 +89,18 @@ for (let i = 0; i < opt.argv.length; i++) { const dom = new jsdom.JSDOM(file, { includeNodeLocations: true }); const body = dom.window.document.body; - function locator(elem) { + let locator = (elem) => { const offset = dom.nodeLocation(elem).startOffset; const line = file.slice(0, offset).split("\n").length; return fn + ":" + line; - } + }; process(body, locator, true); } let output = ""; -for (str in strings) { +for (let str in strings) { output += "#:"; for (location in strings[str]) { output += " " + location; diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/po/zh_CN.po b/jupyter_desktop/share/web/noVNC-1.2.0/po/zh_CN.po index 78bfb958..ede9d441 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/po/zh_CN.po +++ b/jupyter_desktop/share/web/noVNC-1.2.0/po/zh_CN.po @@ -1,14 +1,14 @@ # Simplified Chinese translations for noVNC package. -# Copyright (C) 2018 The noVNC Authors +# Copyright (C) 2020 The noVNC Authors # This file is distributed under the same license as the noVNC package. # Peter Dave Hello , 2018. # msgid "" msgstr "" -"Project-Id-Version: noVNC 1.0.0-testing.2\n" +"Project-Id-Version: noVNC 1.1.0\n" "Report-Msgid-Bugs-To: novnc@googlegroups.com\n" "POT-Creation-Date: 2018-01-10 00:53+0800\n" -"PO-Revision-Date: 2018-04-06 21:33+0800\n" +"PO-Revision-Date: 2020-01-02 13:19+0800\n" "Last-Translator: CUI Wei \n" "Language: zh_CN\n" "MIME-Version: 1.0\n" @@ -17,15 +17,15 @@ msgstr "" #: ../app/ui.js:395 msgid "Connecting..." -msgstr "链接中..." +msgstr "连接中..." #: ../app/ui.js:402 msgid "Disconnecting..." -msgstr "正在中断连接..." +msgstr "正在断开连接..." #: ../app/ui.js:408 msgid "Reconnecting..." -msgstr "重新链接中..." +msgstr "重新连接中..." #: ../app/ui.js:413 msgid "Internal error" @@ -37,31 +37,31 @@ msgstr "请提供主机名" #: ../app/ui.js:1097 msgid "Connected (encrypted) to " -msgstr "已加密链接到" +msgstr "已连接到(加密)" #: ../app/ui.js:1099 msgid "Connected (unencrypted) to " -msgstr "未加密链接到" +msgstr "已连接到(未加密)" #: ../app/ui.js:1120 msgid "Something went wrong, connection is closed" -msgstr "发生错误,链接已关闭" +msgstr "发生错误,连接已关闭" #: ../app/ui.js:1123 msgid "Failed to connect to server" -msgstr "无法链接到服务器" +msgstr "无法连接到服务器" #: ../app/ui.js:1133 msgid "Disconnected" -msgstr "链接已中断" +msgstr "已断开连接" #: ../app/ui.js:1146 msgid "New connection has been rejected with reason: " -msgstr "链接被拒绝,原因:" +msgstr "连接被拒绝,原因:" #: ../app/ui.js:1149 msgid "New connection has been rejected" -msgstr "链接被拒绝" +msgstr "连接被拒绝" #: ../app/ui.js:1170 msgid "Password is required" @@ -73,7 +73,7 @@ msgstr "noVNC 遇到一个错误:" #: ../vnc.html:99 msgid "Hide/Show the control bar" -msgstr "显示/隐藏控制列" +msgstr "显示/隐藏控制栏" #: ../vnc.html:106 msgid "Move/Drag Viewport" @@ -193,7 +193,7 @@ msgstr "清除" #: ../vnc.html:187 msgid "Fullscreen" -msgstr "全屏幕" +msgstr "全屏" #: ../vnc.html:192 ../vnc.html:199 msgid "Settings" @@ -205,7 +205,7 @@ msgstr "分享模式" #: ../vnc.html:205 msgid "View Only" -msgstr "仅检视" +msgstr "仅查看" #: ../vnc.html:209 msgid "Clip to Window" @@ -257,11 +257,11 @@ msgstr "路径:" #: ../vnc.html:249 msgid "Automatic Reconnect" -msgstr "自动重新链接" +msgstr "自动重新连接" #: ../vnc.html:252 msgid "Reconnect Delay (ms):" -msgstr "重新链接间隔 (ms):" +msgstr "重新连接间隔 (ms):" #: ../vnc.html:258 msgid "Logging:" @@ -269,11 +269,11 @@ msgstr "日志级别:" #: ../vnc.html:270 msgid "Disconnect" -msgstr "终端链接" +msgstr "中断连接" #: ../vnc.html:289 msgid "Connect" -msgstr "链接" +msgstr "连接" #: ../vnc.html:299 msgid "Password:" diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/snap/hooks/configure b/jupyter_desktop/share/web/noVNC-1.2.0/snap/hooks/configure new file mode 100644 index 00000000..ff4f8047 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/snap/hooks/configure @@ -0,0 +1,3 @@ +#!/bin/sh -e + +snapctl restart novnc.novncsvc diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/snap/local/svc_wrapper.sh b/jupyter_desktop/share/web/noVNC-1.2.0/snap/local/svc_wrapper.sh new file mode 100644 index 00000000..7b0be232 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/snap/local/svc_wrapper.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +# `snapctl get services` returns a JSON array, example: +#{ +#"n6801": { +# "listen": 6801, +# "vnc": "localhost:5901" +#}, +#"n6802": { +# "listen": 6802, +# "vnc": "localhost:5902" +#} +#} +snapctl get services | jq -c '.[]' | while read service; do # for each service the user sepcified.. + # get the important data for the service (listen port, VNC host:port) + listen_port="$(echo $service | jq --raw-output '.listen')" + vnc_host_port="$(echo $service | jq --raw-output '.vnc')" # --raw-output removes any quotation marks from the output + + # check whether those values are valid + expr "$listen_port" : '^[0-9]\+$' > /dev/null + listen_port_valid=$? + if [ ! $listen_port_valid ] || [ -z "$vnc_host_port" ]; then + # invalid values mean the service is disabled, do nothing except for printing a message (logged in /var/log/system or systemd journal) + echo "novnc: not starting service ${service} with listen_port ${listen_port} and vnc_host_port ${vnc_host_port}" + else + # start (and fork with '&') the service using the specified listen port and VNC host:port + $SNAP/launch.sh --listen $listen_port --vnc $vnc_host_port & + fi +done diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/snap/snapcraft.yaml b/jupyter_desktop/share/web/noVNC-1.2.0/snap/snapcraft.yaml new file mode 100644 index 00000000..d1bb9dc8 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/snap/snapcraft.yaml @@ -0,0 +1,36 @@ +name: novnc +base: core18 # the base snap is the execution environment for this snap +version: '@VERSION@' +summary: Open Source VNC client using HTML5 (WebSockets, Canvas) +description: | + Open Source VNC client using HTML5 (WebSockets, Canvas). + noVNC is both a VNC client JavaScript library as well as an + application built on top of that library. noVNC runs well in any + modern browser including mobile browsers (iOS and Android). + +grade: stable +confinement: strict + +parts: + novnc: + source: build/ + plugin: dump + stage-packages: + - websockify + - bash + - jq + - python-numpy + - python3-numpy + +hooks: + configure: + plugs: [network, network-bind] + +apps: + novnc: + command: ./launch.sh + plugs: [network, network-bind] + novncsvc: + command: ./svc_wrapper.sh + daemon: forking + plugs: [network, network-bind] diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/assertions.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/assertions.js index 07a5c297..05957c08 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/assertions.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/assertions.js @@ -1,32 +1,32 @@ // noVNC specific assertions chai.use(function (_chai, utils) { - _chai.Assertion.addMethod('displayed', function (target_data) { + _chai.Assertion.addMethod('displayed', function (targetData) { const obj = this._obj; const ctx = obj._target.getContext('2d'); - const data_cl = ctx.getImageData(0, 0, obj._target.width, obj._target.height).data; + const dataCl = ctx.getImageData(0, 0, obj._target.width, obj._target.height).data; // NB(directxman12): PhantomJS 1.x doesn't implement Uint8ClampedArray, so work around that - const data = new Uint8Array(data_cl); - const len = data_cl.length; - new chai.Assertion(len).to.be.equal(target_data.length, "unexpected display size"); + const data = new Uint8Array(dataCl); + const len = dataCl.length; + new chai.Assertion(len).to.be.equal(targetData.length, "unexpected display size"); let same = true; for (let i = 0; i < len; i++) { - if (data[i] != target_data[i]) { + if (data[i] != targetData[i]) { same = false; break; } } if (!same) { // eslint-disable-next-line no-console - console.log("expected data: %o, actual data: %o", target_data, data); + console.log("expected data: %o, actual data: %o", targetData, data); } this.assert(same, "expected #{this} to have displayed the image #{exp}, but instead it displayed #{act}", "expected #{this} not to have displayed the image #{act}", - target_data, + targetData, data); }); - _chai.Assertion.addMethod('sent', function (target_data) { + _chai.Assertion.addMethod('sent', function (targetData) { const obj = this._obj; obj.inspect = () => { const res = { _websocket: obj._websocket, rQi: obj._rQi, _rQ: new Uint8Array(obj._rQ.buffer, 0, obj._rQlen), @@ -34,13 +34,13 @@ chai.use(function (_chai, utils) { res.prototype = obj; return res; }; - const data = obj._websocket._get_sent_data(); + const data = obj._websocket._getSentData(); let same = true; - if (data.length != target_data.length) { + if (data.length != targetData.length) { same = false; } else { for (let i = 0; i < data.length; i++) { - if (data[i] != target_data[i]) { + if (data[i] != targetData[i]) { same = false; break; } @@ -48,12 +48,12 @@ chai.use(function (_chai, utils) { } if (!same) { // eslint-disable-next-line no-console - console.log("expected data: %o, actual data: %o", target_data, data); + console.log("expected data: %o, actual data: %o", targetData, data); } this.assert(same, "expected #{this} to have sent the data #{exp}, but it actually sent #{act}", "expected #{this} not to have sent the data #{act}", - Array.prototype.slice.call(target_data), + Array.prototype.slice.call(targetData), Array.prototype.slice.call(data)); }); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/fake.websocket.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/fake.websocket.js index 68ab3f84..623b25e4 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/fake.websocket.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/fake.websocket.js @@ -1,7 +1,7 @@ import Base64 from '../core/base64.js'; // PhantomJS can't create Event objects directly, so we need to use this -function make_event(name, props) { +function makeEvent(name, props) { const evt = document.createEvent('Event'); evt.initEvent(name, true, true); if (props) { @@ -24,18 +24,18 @@ export default class FakeWebSocket { this.protocol = protocols[0]; } - this._send_queue = new Uint8Array(20000); + this._sendQueue = new Uint8Array(20000); this.readyState = FakeWebSocket.CONNECTING; this.bufferedAmount = 0; - this.__is_fake = true; + this._isFake = true; } close(code, reason) { this.readyState = FakeWebSocket.CLOSED; if (this.onclose) { - this.onclose(make_event("close", { 'code': code, 'reason': reason, 'wasClean': true })); + this.onclose(makeEvent("close", { 'code': code, 'reason': reason, 'wasClean': true })); } } @@ -45,12 +45,12 @@ export default class FakeWebSocket { } else { data = new Uint8Array(data); } - this._send_queue.set(data, this.bufferedAmount); + this._sendQueue.set(data, this.bufferedAmount); this.bufferedAmount += data.length; } - _get_sent_data() { - const res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount); + _getSentData() { + const res = new Uint8Array(this._sendQueue.buffer, 0, this.bufferedAmount); this.bufferedAmount = 0; return res; } @@ -58,16 +58,16 @@ export default class FakeWebSocket { _open() { this.readyState = FakeWebSocket.OPEN; if (this.onopen) { - this.onopen(make_event('open')); + this.onopen(makeEvent('open')); } } - _receive_data(data) { + _receiveData(data) { // Break apart the data to expose bugs where we assume data is // neatly packaged for (let i = 0;i < data.length;i++) { let buf = data.subarray(i, i+1); - this.onmessage(make_event("message", { 'data': buf })); + this.onmessage(makeEvent("message", { 'data': buf })); } } } @@ -77,20 +77,20 @@ FakeWebSocket.CONNECTING = WebSocket.CONNECTING; FakeWebSocket.CLOSING = WebSocket.CLOSING; FakeWebSocket.CLOSED = WebSocket.CLOSED; -FakeWebSocket.__is_fake = true; +FakeWebSocket._isFake = true; FakeWebSocket.replace = () => { - if (!WebSocket.__is_fake) { - const real_version = WebSocket; + if (!WebSocket._isFake) { + const realVersion = WebSocket; // eslint-disable-next-line no-global-assign WebSocket = FakeWebSocket; - FakeWebSocket.__real_version = real_version; + FakeWebSocket._realVersion = realVersion; } }; FakeWebSocket.restore = () => { - if (WebSocket.__is_fake) { + if (WebSocket._isFake) { // eslint-disable-next-line no-global-assign - WebSocket = WebSocket.__real_version; + WebSocket = WebSocket._realVersion; } }; diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/playback-ui.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/playback-ui.js index 65c715a9..2cecb14c 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/playback-ui.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/playback-ui.js @@ -1,4 +1,4 @@ -/* global VNC_frame_data, VNC_frame_encoding */ +/* global vncFrameData, vncFrameEncoding */ import * as WebUtil from '../app/webutil.js'; import RecordingPlayer from './playback.js'; @@ -41,7 +41,7 @@ function enableUI() { document.getElementById('mode1').checked = true; } - message("Loaded " + VNC_frame_data.length + " frames"); + message("Loaded " + vncFrameData.length + " frames"); const startButton = document.getElementById('startButton'); startButton.disabled = false; @@ -49,12 +49,12 @@ function enableUI() { message("Converting..."); - frames = VNC_frame_data; + frames = vncFrameData; let encoding; // Only present in older recordings - if (window.VNC_frame_encoding) { - encoding = VNC_frame_encoding; + if (window.vncFrameEncoding) { + encoding = vncFrameEncoding; } else { let frame = frames[0]; let start = frame.indexOf('{', 1) + 1; @@ -102,7 +102,7 @@ class IterationPlayer { this._iteration = undefined; this._player = undefined; - this._start_time = undefined; + this._startTime = undefined; this._frames = frames; @@ -115,7 +115,7 @@ class IterationPlayer { start(realtime) { this._iteration = 0; - this._start_time = (new Date()).getTime(); + this._startTime = (new Date()).getTime(); this._realtime = realtime; @@ -139,7 +139,7 @@ class IterationPlayer { _finish() { const endTime = (new Date()).getTime(); - const totalDuration = endTime - this._start_time; + const totalDuration = endTime - this._startTime; const evt = new CustomEvent('finish', { detail: diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/playback.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/playback.js index 5bd8103a..d8d84c2c 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/playback.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/playback.js @@ -49,10 +49,10 @@ export default class RecordingPlayer { this._disconnected = disconnected; this._rfb = undefined; - this._frame_length = this._frames.length; + this._frameLength = this._frames.length; - this._frame_index = 0; - this._start_time = undefined; + this._frameIndex = 0; + this._startTime = undefined; this._realtime = true; this._trafficManagement = true; @@ -72,8 +72,8 @@ export default class RecordingPlayer { this._enablePlaybackMode(); // reset the frame index and timer - this._frame_index = 0; - this._start_time = (new Date()).getTime(); + this._frameIndex = 0; + this._startTime = (new Date()).getTime(); this._realtime = realtime; this._trafficManagement = (trafficManagement === undefined) ? !realtime : trafficManagement; @@ -97,22 +97,22 @@ export default class RecordingPlayer { _queueNextPacket() { if (!this._running) { return; } - let frame = this._frames[this._frame_index]; + let frame = this._frames[this._frameIndex]; // skip send frames - while (this._frame_index < this._frame_length && frame.fromClient) { - this._frame_index++; - frame = this._frames[this._frame_index]; + while (this._frameIndex < this._frameLength && frame.fromClient) { + this._frameIndex++; + frame = this._frames[this._frameIndex]; } - if (this._frame_index >= this._frame_length) { + if (this._frameIndex >= this._frameLength) { Log.Debug('Finished, no more frames'); this._finish(); return; } if (this._realtime) { - const toffset = (new Date()).getTime() - this._start_time; + const toffset = (new Date()).getTime() - this._startTime; let delay = frame.timestamp - toffset; if (delay < 1) delay = 1; @@ -134,10 +134,10 @@ export default class RecordingPlayer { return; } - const frame = this._frames[this._frame_index]; + const frame = this._frames[this._frameIndex]; this._rfb._sock._recv_message({'data': frame.data}); - this._frame_index++; + this._frameIndex++; this._queueNextPacket(); } @@ -155,13 +155,13 @@ export default class RecordingPlayer { this._running = false; this._rfb._sock._eventHandlers.close({code: 1000, reason: ""}); delete this._rfb; - this.onfinish((new Date()).getTime() - this._start_time); + this.onfinish((new Date()).getTime() - this._startTime); } } _handleDisconnect(evt) { this._running = false; - this._disconnected(evt.detail.clean, this._frame_index); + this._disconnected(evt.detail.clean, this._frameIndex); } _handleCredentials(evt) { diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.deflator.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.deflator.js new file mode 100644 index 00000000..12e8a46b --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.deflator.js @@ -0,0 +1,82 @@ +/* eslint-disable no-console */ +const expect = chai.expect; + +import { inflateInit, inflate } from "../vendor/pako/lib/zlib/inflate.js"; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; +import Deflator from "../core/deflator.js"; + +function _inflator(compText, expected) { + let strm = new ZStream(); + let chunkSize = 1024 * 10 * 10; + strm.output = new Uint8Array(chunkSize); + + inflateInit(strm, 5); + + if (expected > chunkSize) { + chunkSize = expected; + strm.output = new Uint8Array(chunkSize); + } + + /* eslint-disable camelcase */ + strm.input = compText; + strm.avail_in = strm.input.length; + strm.next_in = 0; + + strm.next_out = 0; + strm.avail_out = expected.length; + /* eslint-enable camelcase */ + + let ret = inflate(strm, 0); + + // Check that return code is not an error + expect(ret).to.be.greaterThan(-1); + + return new Uint8Array(strm.output.buffer, 0, strm.next_out); +} + +describe('Deflate data', function () { + + it('should be able to deflate messages', function () { + let deflator = new Deflator(); + + let text = "123asdf"; + let preText = new Uint8Array(text.length); + for (let i = 0; i < preText.length; i++) { + preText[i] = text.charCodeAt(i); + } + + let compText = deflator.deflate(preText); + + let inflatedText = _inflator(compText, text.length); + expect(inflatedText).to.array.equal(preText); + + }); + + it('should be able to deflate large messages', function () { + let deflator = new Deflator(); + + /* Generate a big string with random characters. Used because + repetition of letters might be deflated more effectively than + random ones. */ + let text = ""; + let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + for (let i = 0; i < 300000; i++) { + text += characters.charAt(Math.floor(Math.random() * characters.length)); + } + + let preText = new Uint8Array(text.length); + for (let i = 0; i < preText.length; i++) { + preText[i] = text.charCodeAt(i); + } + + let compText = deflator.deflate(preText); + + //Check that the compressed size is expected size + expect(compText.length).to.be.greaterThan((1024 * 10 * 10) * 2); + + let inflatedText = _inflator(compText, text.length); + + expect(inflatedText).to.array.equal(preText); + + }); +}); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.display.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.display.js index b3595503..a853778a 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.display.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.display.js @@ -4,28 +4,28 @@ import Base64 from '../core/base64.js'; import Display from '../core/display.js'; describe('Display/Canvas Helper', function () { - const checked_data = new Uint8Array([ + const checkedData = new Uint8Array([ 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 ]); - const basic_data = new Uint8Array([0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0xff, 0xff, 0xff, 255]); + const basicData = new Uint8Array([0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0xff, 0xff, 0xff, 255]); - function make_image_canvas(input_data) { + function makeImageCanvas(inputData) { const canvas = document.createElement('canvas'); canvas.width = 4; canvas.height = 4; const ctx = canvas.getContext('2d'); const data = ctx.createImageData(4, 4); - for (let i = 0; i < checked_data.length; i++) { data.data[i] = input_data[i]; } + for (let i = 0; i < checkedData.length; i++) { data.data[i] = inputData[i]; } ctx.putImageData(data, 0, 0); return canvas; } - function make_image_png(input_data) { - const canvas = make_image_canvas(input_data); + function makeImagePng(inputData) { + const canvas = makeImageCanvas(inputData); const url = canvas.toDataURL(); const data = url.split(",")[1]; return Base64.decode(data); @@ -44,11 +44,11 @@ describe('Display/Canvas Helper', function () { it('should take viewport location into consideration when drawing images', function () { display.resize(4, 4); display.viewportChangeSize(2, 2); - display.drawImage(make_image_canvas(basic_data), 1, 1); + display.drawImage(makeImageCanvas(basicData), 1, 1); display.flip(); const expected = new Uint8Array(16); - for (let i = 0; i < 8; i++) { expected[i] = basic_data[i]; } + for (let i = 0; i < 8; i++) { expected[i] = basicData[i]; } for (let i = 8; i < 16; i++) { expected[i] = 0; } expect(display).to.have.displayed(expected); }); @@ -123,8 +123,8 @@ describe('Display/Canvas Helper', function () { it('should change the size of the logical canvas', function () { display.resize(5, 7); - expect(display._fb_width).to.equal(5); - expect(display._fb_height).to.equal(7); + expect(display._fbWidth).to.equal(5); + expect(display._fbHeight).to.equal(7); }); it('should keep the framebuffer data', function () { @@ -223,6 +223,7 @@ describe('Display/Canvas Helper', function () { display = new Display(canvas); display.clipViewport = true; display.resize(4, 3); + display.viewportChangeSize(4, 3); document.body.appendChild(canvas); }); @@ -269,34 +270,12 @@ describe('Display/Canvas Helper', function () { display.resize(4, 4); }); - it('should clear the screen on #clear without a logo set', function () { - display.fillRect(0, 0, 4, 4, [0x00, 0x00, 0xff]); - display._logo = null; - display.clear(); - display.resize(4, 4); - const empty = []; - for (let i = 0; i < 4 * display._fb_width * display._fb_height; i++) { empty[i] = 0; } - expect(display).to.have.displayed(new Uint8Array(empty)); - }); - - it('should draw the logo on #clear with a logo set', function (done) { - display._logo = { width: 4, height: 4, type: "image/png", data: make_image_png(checked_data) }; - display.clear(); - display.onflush = () => { - expect(display).to.have.displayed(checked_data); - expect(display._fb_width).to.equal(4); - expect(display._fb_height).to.equal(4); - done(); - }; - display.flush(); - }); - it('should not draw directly on the target canvas', function () { display.fillRect(0, 0, 4, 4, [0, 0, 0xff]); display.flip(); display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); const expected = []; - for (let i = 0; i < 4 * display._fb_width * display._fb_height; i += 4) { + for (let i = 0; i < 4 * display._fbWidth * display._fbHeight; i += 4) { expected[i] = 0xff; expected[i+1] = expected[i+2] = 0; expected[i+3] = 0xff; @@ -309,7 +288,7 @@ describe('Display/Canvas Helper', function () { display.fillRect(0, 0, 2, 2, [0xff, 0, 0]); display.fillRect(2, 2, 2, 2, [0xff, 0, 0]); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); it('should support copying an portion of the canvas via #copyImage', function () { @@ -317,14 +296,14 @@ describe('Display/Canvas Helper', function () { display.fillRect(0, 0, 2, 2, [0xff, 0, 0x00]); display.copyImage(0, 0, 2, 2, 2, 2); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); it('should support drawing images via #imageRect', function (done) { - display.imageRect(0, 0, "image/png", make_image_png(checked_data)); + display.imageRect(0, 0, 4, 4, "image/png", makeImagePng(checkedData)); display.flip(); display.onflush = () => { - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); done(); }; display.flush(); @@ -336,12 +315,12 @@ describe('Display/Canvas Helper', function () { display.subTile(2, 2, 2, 2, [0xff, 0, 0]); display.finishTile(); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); // We have a special cache for 16x16 tiles that we need to test it('should support drawing a 16x16 tile', function () { - const large_checked_data = new Uint8Array(16*16*4); + const largeCheckedData = new Uint8Array(16*16*4); display.resize(16, 16); for (let y = 0;y < 16;y++) { @@ -349,11 +328,11 @@ describe('Display/Canvas Helper', function () { let pixel; if ((x < 4) && (y < 4)) { // NB: of course IE11 doesn't support #slice on ArrayBufferViews... - pixel = Array.prototype.slice.call(checked_data, (y*4+x)*4, (y*4+x+1)*4); + pixel = Array.prototype.slice.call(checkedData, (y*4+x)*4, (y*4+x+1)*4); } else { pixel = [0, 0xff, 0, 255]; } - large_checked_data.set(pixel, (y*16+x)*4); + largeCheckedData.set(pixel, (y*16+x)*4); } } @@ -362,39 +341,39 @@ describe('Display/Canvas Helper', function () { display.subTile(2, 2, 2, 2, [0xff, 0, 0]); display.finishTile(); display.flip(); - expect(display).to.have.displayed(large_checked_data); + expect(display).to.have.displayed(largeCheckedData); }); it('should support drawing BGRX blit images with true color via #blitImage', function () { const data = []; for (let i = 0; i < 16; i++) { - data[i * 4] = checked_data[i * 4 + 2]; - data[i * 4 + 1] = checked_data[i * 4 + 1]; - data[i * 4 + 2] = checked_data[i * 4]; - data[i * 4 + 3] = checked_data[i * 4 + 3]; + data[i * 4] = checkedData[i * 4 + 2]; + data[i * 4 + 1] = checkedData[i * 4 + 1]; + data[i * 4 + 2] = checkedData[i * 4]; + data[i * 4 + 3] = checkedData[i * 4 + 3]; } display.blitImage(0, 0, 4, 4, data, 0); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); it('should support drawing RGB blit images with true color via #blitRgbImage', function () { const data = []; for (let i = 0; i < 16; i++) { - data[i * 3] = checked_data[i * 4]; - data[i * 3 + 1] = checked_data[i * 4 + 1]; - data[i * 3 + 2] = checked_data[i * 4 + 2]; + data[i * 3] = checkedData[i * 4]; + data[i * 3 + 1] = checkedData[i * 4 + 1]; + data[i * 3 + 2] = checkedData[i * 4 + 2]; } display.blitRgbImage(0, 0, 4, 4, data, 0); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); it('should support drawing an image object via #drawImage', function () { - const img = make_image_canvas(checked_data); + const img = makeImageCanvas(checkedData); display.drawImage(img, 0, 0); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); }); @@ -403,38 +382,55 @@ describe('Display/Canvas Helper', function () { beforeEach(function () { display = new Display(document.createElement('canvas')); display.resize(4, 4); - sinon.spy(display, '_scan_renderQ'); - }); - - afterEach(function () { - window.requestAnimationFrame = this.old_requestAnimationFrame; + sinon.spy(display, '_scanRenderQ'); }); it('should try to process an item when it is pushed on, if nothing else is on the queue', function () { - display._renderQ_push({ type: 'noop' }); // does nothing - expect(display._scan_renderQ).to.have.been.calledOnce; + display._renderQPush({ type: 'noop' }); // does nothing + expect(display._scanRenderQ).to.have.been.calledOnce; }); it('should not try to process an item when it is pushed on if we are waiting for other items', function () { display._renderQ.length = 2; - display._renderQ_push({ type: 'noop' }); - expect(display._scan_renderQ).to.not.have.been.called; + display._renderQPush({ type: 'noop' }); + expect(display._scanRenderQ).to.not.have.been.called; }); it('should wait until an image is loaded to attempt to draw it and the rest of the queue', function () { - const img = { complete: false, addEventListener: sinon.spy() }; - display._renderQ = [{ type: 'img', x: 3, y: 4, img: img }, + const img = { complete: false, width: 4, height: 4, addEventListener: sinon.spy() }; + display._renderQ = [{ type: 'img', x: 3, y: 4, width: 4, height: 4, img: img }, + { type: 'fill', x: 1, y: 2, width: 3, height: 4, color: 5 }]; + display.drawImage = sinon.spy(); + display.fillRect = sinon.spy(); + + display._scanRenderQ(); + expect(display.drawImage).to.not.have.been.called; + expect(display.fillRect).to.not.have.been.called; + expect(img.addEventListener).to.have.been.calledOnce; + + display._renderQ[0].img.complete = true; + display._scanRenderQ(); + expect(display.drawImage).to.have.been.calledOnce; + expect(display.fillRect).to.have.been.calledOnce; + expect(img.addEventListener).to.have.been.calledOnce; + }); + + it('should wait if an image is incorrectly loaded', function () { + const img = { complete: true, width: 0, height: 0, addEventListener: sinon.spy() }; + display._renderQ = [{ type: 'img', x: 3, y: 4, width: 4, height: 4, img: img }, { type: 'fill', x: 1, y: 2, width: 3, height: 4, color: 5 }]; display.drawImage = sinon.spy(); display.fillRect = sinon.spy(); - display._scan_renderQ(); + display._scanRenderQ(); expect(display.drawImage).to.not.have.been.called; expect(display.fillRect).to.not.have.been.called; expect(img.addEventListener).to.have.been.calledOnce; display._renderQ[0].img.complete = true; - display._scan_renderQ(); + display._renderQ[0].img.width = 4; + display._renderQ[0].img.height = 4; + display._scanRenderQ(); expect(display.drawImage).to.have.been.calledOnce; expect(display.fillRect).to.have.been.calledOnce; expect(img.addEventListener).to.have.been.calledOnce; @@ -450,35 +446,35 @@ describe('Display/Canvas Helper', function () { it('should draw a blit image on type "blit"', function () { display.blitImage = sinon.spy(); - display._renderQ_push({ type: 'blit', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); + display._renderQPush({ type: 'blit', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); expect(display.blitImage).to.have.been.calledOnce; expect(display.blitImage).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9], 0); }); it('should draw a blit RGB image on type "blitRgb"', function () { display.blitRgbImage = sinon.spy(); - display._renderQ_push({ type: 'blitRgb', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); + display._renderQPush({ type: 'blitRgb', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); expect(display.blitRgbImage).to.have.been.calledOnce; expect(display.blitRgbImage).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9], 0); }); it('should copy a region on type "copy"', function () { display.copyImage = sinon.spy(); - display._renderQ_push({ type: 'copy', x: 3, y: 4, width: 5, height: 6, old_x: 7, old_y: 8 }); + display._renderQPush({ type: 'copy', x: 3, y: 4, width: 5, height: 6, oldX: 7, oldY: 8 }); expect(display.copyImage).to.have.been.calledOnce; expect(display.copyImage).to.have.been.calledWith(7, 8, 3, 4, 5, 6); }); it('should fill a rect with a given color on type "fill"', function () { display.fillRect = sinon.spy(); - display._renderQ_push({ type: 'fill', x: 3, y: 4, width: 5, height: 6, color: [7, 8, 9]}); + display._renderQPush({ type: 'fill', x: 3, y: 4, width: 5, height: 6, color: [7, 8, 9]}); expect(display.fillRect).to.have.been.calledOnce; expect(display.fillRect).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9]); }); it('should draw an image from an image object on type "img" (if complete)', function () { display.drawImage = sinon.spy(); - display._renderQ_push({ type: 'img', x: 3, y: 4, img: { complete: true } }); + display._renderQPush({ type: 'img', x: 3, y: 4, img: { complete: true } }); expect(display.drawImage).to.have.been.calledOnce; expect(display.drawImage).to.have.been.calledWith({ complete: true }, 3, 4); }); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.gesturehandler.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.gesturehandler.js new file mode 100644 index 00000000..ba2f7991 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.gesturehandler.js @@ -0,0 +1,1033 @@ +const expect = chai.expect; + +import EventTargetMixin from '../core/util/eventtarget.js'; + +import GestureHandler from '../core/input/gesturehandler.js'; +import * as browser from '../core/util/browser.js'; + +class DummyTarget extends EventTargetMixin { +} + +describe('Gesture handler', function () { + let target, handler; + let gestures; + let clock; + let touches; + + before(function () { + clock = sinon.useFakeTimers(); + }); + + after(function () { + clock.restore(); + }); + + beforeEach(function () { + // Touch events and gestures are not supported on IE + if (browser.isIE()) { + this.skip(); + return; + } + + target = new DummyTarget(); + gestures = sinon.spy(); + target.addEventListener('gesturestart', gestures); + target.addEventListener('gesturemove', gestures); + target.addEventListener('gestureend', gestures); + touches = []; + handler = new GestureHandler(); + handler.attach(target); + }); + + afterEach(function () { + if (handler) { + handler.detach(); + } + target = null; + gestures = null; + }); + + function touchStart(id, x, y) { + let touch = { identifier: id, + clientX: x, clientY: y }; + touches.push(touch); + let ev = { type: 'touchstart', + touches: touches, + targetTouches: touches, + changedTouches: [ touch ], + stopPropagation: sinon.spy(), + preventDefault: sinon.spy() }; + target.dispatchEvent(ev); + } + + function touchMove(id, x, y) { + let touch = touches.find(t => t.identifier === id); + touch.clientX = x; + touch.clientY = y; + let ev = { type: 'touchmove', + touches: touches, + targetTouches: touches, + changedTouches: [ touch ], + stopPropagation: sinon.spy(), + preventDefault: sinon.spy() }; + target.dispatchEvent(ev); + } + + function touchEnd(id) { + let idx = touches.findIndex(t => t.identifier === id); + let touch = touches.splice(idx, 1)[0]; + let ev = { type: 'touchend', + touches: touches, + targetTouches: touches, + changedTouches: [ touch ], + stopPropagation: sinon.spy(), + preventDefault: sinon.spy() }; + target.dispatchEvent(ev); + } + + describe('Single finger tap', function () { + it('should handle single finger tap', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(1); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'onetap', + clientX: 20.0, + clientY: 30.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'onetap', + clientX: 20.0, + clientY: 30.0 } })); + }); + }); + + describe('Two finger tap', function () { + it('should handle two finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(1); + + expect(gestures).to.not.have.been.called; + + touchEnd(2); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twotap', + clientX: 25.0, + clientY: 40.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twotap', + clientX: 25.0, + clientY: 40.0 } })); + }); + + it('should ignore slow starting two finger tap', function () { + touchStart(1, 20.0, 30.0); + + clock.tick(500); + + touchStart(2, 30.0, 50.0); + touchEnd(1); + touchEnd(2); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore slow ending two finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchEnd(1); + + clock.tick(500); + + touchEnd(2); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore slow two finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + + clock.tick(1500); + + touchEnd(1); + touchEnd(2); + + expect(gestures).to.not.have.been.called; + }); + }); + + describe('Three finger tap', function () { + it('should handle three finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchStart(3, 40.0, 40.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(1); + + expect(gestures).to.not.have.been.called; + + touchEnd(2); + + expect(gestures).to.not.have.been.called; + + touchEnd(3); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'threetap', + clientX: 30.0, + clientY: 40.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'threetap', + clientX: 30.0, + clientY: 40.0 } })); + }); + + it('should ignore slow starting three finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + + clock.tick(500); + + touchStart(3, 40.0, 40.0); + touchEnd(1); + touchEnd(2); + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore slow ending three finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchStart(3, 40.0, 40.0); + touchEnd(1); + touchEnd(2); + + clock.tick(500); + + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore three finger drag', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchStart(3, 40.0, 40.0); + + touchMove(1, 120.0, 130.0); + touchMove(2, 130.0, 150.0); + touchMove(3, 140.0, 140.0); + + touchEnd(1); + touchEnd(2); + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore slow three finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchStart(3, 40.0, 40.0); + + clock.tick(1500); + + touchEnd(1); + touchEnd(2); + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + }); + + describe('Single finger drag', function () { + it('should handle horizontal single finger drag', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 40.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag', + clientX: 20.0, + clientY: 30.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag', + clientX: 80.0, + clientY: 30.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag', + clientX: 80.0, + clientY: 30.0 } })); + }); + + it('should handle vertical single finger drag', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 20.0, 50.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 20.0, 90.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag', + clientX: 20.0, + clientY: 30.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag', + clientX: 20.0, + clientY: 90.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag', + clientX: 20.0, + clientY: 90.0 } })); + }); + + it('should handle diagonal single finger drag', function () { + touchStart(1, 120.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 90.0, 100.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 60.0, 70.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag', + clientX: 120.0, + clientY: 130.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag', + clientX: 60.0, + clientY: 70.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag', + clientX: 60.0, + clientY: 70.0 } })); + }); + }); + + describe('Long press', function () { + it('should handle long press', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(1500); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'longpress', + clientX: 20.0, + clientY: 30.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'longpress', + clientX: 20.0, + clientY: 30.0 } })); + }); + + it('should handle long press drag', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(1500); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'longpress', + clientX: 20.0, + clientY: 30.0 } })); + + gestures.resetHistory(); + + touchMove(1, 120.0, 50.0); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'longpress', + clientX: 120.0, + clientY: 50.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'longpress', + clientX: 120.0, + clientY: 50.0 } })); + }); + }); + + describe('Two finger drag', function () { + it('should handle fast and distinct horizontal two finger drag', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 40.0, 30.0); + touchMove(2, 50.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(2, 90.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 60.0, + magnitudeY: 0.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 60.0, + magnitudeY: 0.0 } })); + }); + + it('should handle fast and distinct vertical two finger drag', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 20.0, 100.0); + touchMove(2, 30.0, 40.0); + + expect(gestures).to.not.have.been.called; + + touchMove(2, 30.0, 90.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 0.0, + magnitudeY: 65.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 0.0, + magnitudeY: 65.0 } })); + }); + + it('should handle fast and distinct diagonal two finger drag', function () { + touchStart(1, 120.0, 130.0); + touchStart(2, 130.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 80.0, 90.0); + touchMove(2, 100.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(2, 60.0, 70.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 125.0, + clientY: 130.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 125.0, + clientY: 130.0, + magnitudeX: -55.0, + magnitudeY: -50.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twodrag', + clientX: 125.0, + clientY: 130.0, + magnitudeX: -55.0, + magnitudeY: -50.0 } })); + }); + + it('should ignore fast almost two finger dragging', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 30.0); + touchMove(1, 80.0, 30.0); + touchMove(2, 70.0, 30.0); + touchEnd(1); + touchEnd(2); + + expect(gestures).to.not.have.been.called; + + clock.tick(1500); + + expect(gestures).to.not.have.been.called; + }); + + it('should handle slow horizontal two finger drag', function () { + touchStart(1, 50.0, 40.0); + touchStart(2, 60.0, 40.0); + touchMove(1, 80.0, 40.0); + touchMove(2, 110.0, 40.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 55.0, + clientY: 40.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 55.0, + clientY: 40.0, + magnitudeX: 40.0, + magnitudeY: 0.0 } })); + }); + + it('should handle slow vertical two finger drag', function () { + touchStart(1, 40.0, 40.0); + touchStart(2, 40.0, 60.0); + touchMove(2, 40.0, 80.0); + touchMove(1, 40.0, 100.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 40.0, + clientY: 50.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 40.0, + clientY: 50.0, + magnitudeX: 0.0, + magnitudeY: 40.0 } })); + }); + + it('should handle slow diagonal two finger drag', function () { + touchStart(1, 50.0, 40.0); + touchStart(2, 40.0, 60.0); + touchMove(1, 70.0, 60.0); + touchMove(2, 90.0, 110.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 45.0, + clientY: 50.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 45.0, + clientY: 50.0, + magnitudeX: 35.0, + magnitudeY: 35.0 } })); + }); + + it('should ignore too slow two finger drag', function () { + touchStart(1, 20.0, 30.0); + + clock.tick(500); + + touchStart(2, 30.0, 30.0); + touchMove(1, 40.0, 30.0); + touchMove(2, 50.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.not.have.been.called; + }); + }); + + describe('Pinch', function () { + it('should handle pinching distinctly and fast inwards', function () { + touchStart(1, 0.0, 0.0); + touchStart(2, 130.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 50.0, 40.0); + touchMove(2, 100.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(2, 60.0, 70.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 130.0, + magnitudeY: 130.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 10.0, + magnitudeY: 30.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 10.0, + magnitudeY: 30.0 } })); + }); + + it('should handle pinching fast and distinctly outwards', function () { + touchStart(1, 100.0, 100.0); + touchStart(2, 110.0, 100.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 130.0, 70.0); + touchMove(2, 0.0, 200.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 180.0, 20.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 100.0, + magnitudeX: 10.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 100.0, + magnitudeX: 180.0, + magnitudeY: 180.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 100.0, + magnitudeX: 180.0, + magnitudeY: 180.0 } })); + }); + + it('should ignore fast almost pinching', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 130.0, 130.0); + touchMove(1, 80.0, 70.0); + touchEnd(1); + touchEnd(2); + + expect(gestures).to.not.have.been.called; + + clock.tick(1500); + + expect(gestures).to.not.have.been.called; + }); + + it('should handle pinching inwards slowly', function () { + touchStart(1, 0.0, 0.0); + touchStart(2, 130.0, 130.0); + touchMove(1, 50.0, 40.0); + touchMove(2, 100.0, 130.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 130.0, + magnitudeY: 130.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 50.0, + magnitudeY: 90.0 } })); + }); + + it('should handle pinching outwards slowly', function () { + touchStart(1, 100.0, 130.0); + touchStart(2, 110.0, 130.0); + touchMove(2, 200.0, 130.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 130.0, + magnitudeX: 10.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 130.0, + magnitudeX: 100.0, + magnitudeY: 0.0 } })); + }); + + it('should ignore pinching too slowly', function () { + touchStart(1, 0.0, 0.0); + + clock.tick(500); + + touchStart(2, 130.0, 130.0); + touchMove(2, 100.0, 130.0); + touchMove(1, 50.0, 40.0); + + expect(gestures).to.not.have.been.called; + }); + }); + + describe('Ignoring', function () { + it('should ignore extra touches during gesture', function () { + touchStart(1, 20.0, 30.0); + touchMove(1, 40.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag' } })); + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag' } })); + + gestures.resetHistory(); + + touchStart(2, 10.0, 10.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 100.0, 50.0); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag', + clientX: 100.0, + clientY: 50.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag', + clientX: 100.0, + clientY: 50.0 } })); + }); + + it('should ignore extra touches when waiting for gesture to end', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 30.0); + touchMove(1, 40.0, 30.0); + touchMove(2, 90.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag' } })); + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag' } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twodrag' } })); + + gestures.resetHistory(); + + touchStart(3, 10.0, 10.0); + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore extra touches after gesture', function () { + touchStart(1, 20.0, 30.0); + touchMove(1, 40.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag' } })); + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag' } })); + + gestures.resetHistory(); + + touchStart(2, 10.0, 10.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 100.0, 50.0); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag' } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag' } })); + + gestures.resetHistory(); + + touchEnd(2); + + expect(gestures).to.not.have.been.called; + + // Check that everything is reseted after trailing ignores are released + + touchStart(3, 20.0, 30.0); + touchEnd(3); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'onetap' } })); + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'onetap' } })); + }); + + it('should properly reset after a gesture', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(1); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'onetap', + clientX: 20.0, + clientY: 30.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'onetap', + clientX: 20.0, + clientY: 30.0 } })); + + gestures.resetHistory(); + + touchStart(2, 70.0, 80.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(2); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'onetap', + clientX: 70.0, + clientY: 80.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'onetap', + clientX: 70.0, + clientY: 80.0 } })); + }); + }); +}); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.helper.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.helper.js index d44bab0f..b1f438ee 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.helper.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.helper.js @@ -86,7 +86,9 @@ describe('Helpers', function () { window.navigator.platform = "Mac x86_64"; }); afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); + if (origNavigator !== undefined) { + Object.defineProperty(window, "navigator", origNavigator); + } }); it('should respect ContextMenu on modern browser', function () { @@ -110,6 +112,9 @@ describe('Helpers', function () { expect(KeyboardUtil.getKey({key: 'Win'})).to.be.equal('Meta'); expect(KeyboardUtil.getKey({key: 'UIKeyInputLeftArrow'})).to.be.equal('ArrowLeft'); }); + it('should handle broken Delete', function () { + expect(KeyboardUtil.getKey({key: '\x00', code: 'NumpadDecimal'})).to.be.equal('Delete'); + }); it('should use code if no key', function () { expect(KeyboardUtil.getKey({code: 'NumpadBackspace'})).to.be.equal('Backspace'); }); @@ -147,7 +152,9 @@ describe('Helpers', function () { } }); afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); + if (origNavigator !== undefined) { + Object.defineProperty(window, "navigator", origNavigator); + } }); it('should ignore printable character key on IE', function () { @@ -166,6 +173,16 @@ describe('Helpers', function () { window.navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"; expect(KeyboardUtil.getKey({key: 'Shift'})).to.be.equal('Shift'); }); + it('should allow printable character key with charCode on IE', function () { + window.navigator.userAgent = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"; + expect(KeyboardUtil.getKey({key: 'a', charCode: 0x61})).to.be.equal('a'); + expect(KeyboardUtil.getKey({key: 'Unidentified', charCode: 0x61})).to.be.equal('a'); + }); + it('should allow printable character key with charCode on Edge', function () { + window.navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"; + expect(KeyboardUtil.getKey({key: 'a', charCode: 0x61})).to.be.equal('a'); + expect(KeyboardUtil.getKey({key: 'Unidentified', charCode: 0x61})).to.be.equal('a'); + }); }); }); @@ -192,6 +209,22 @@ describe('Helpers', function () { expect(KeyboardUtil.getKeysym({code: 'AltRight', key: 'Alt', location: 2})).to.be.equal(0xFFEA); expect(KeyboardUtil.getKeysym({code: 'AltRight', key: 'AltGraph', location: 2})).to.be.equal(0xFE03); }); + it('should handle Windows key with incorrect location', function () { + expect(KeyboardUtil.getKeysym({key: 'Meta', location: 0})).to.be.equal(0xFFEC); + }); + it('should handle Clear/NumLock key with incorrect location', function () { + this.skip(); // Broken because of Clear/NumLock override + expect(KeyboardUtil.getKeysym({key: 'Clear', code: 'NumLock', location: 3})).to.be.equal(0xFF0B); + }); + it('should handle Meta/Windows distinction', function () { + expect(KeyboardUtil.getKeysym({code: 'AltLeft', key: 'Meta', location: 1})).to.be.equal(0xFFE7); + expect(KeyboardUtil.getKeysym({code: 'AltRight', key: 'Meta', location: 2})).to.be.equal(0xFFE8); + expect(KeyboardUtil.getKeysym({code: 'MetaLeft', key: 'Meta', location: 1})).to.be.equal(0xFFEB); + expect(KeyboardUtil.getKeysym({code: 'MetaRight', key: 'Meta', location: 2})).to.be.equal(0xFFEC); + }); + it('should send NumLock even if key is Clear', function () { + expect(KeyboardUtil.getKeysym({key: 'Clear', code: 'NumLock'})).to.be.equal(0xFF7F); + }); it('should return null for unknown keys', function () { expect(KeyboardUtil.getKeysym({key: 'Semicolon'})).to.be.null; expect(KeyboardUtil.getKeysym({key: 'BracketRight'})).to.be.null; diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.int.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.int.js new file mode 100644 index 00000000..954fd279 --- /dev/null +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.int.js @@ -0,0 +1,16 @@ +/* eslint-disable no-console */ +const expect = chai.expect; + +import { toUnsigned32bit, toSigned32bit } from '../core/util/int.js'; + +describe('Integer casting', function () { + it('should cast unsigned to signed', function () { + let expected = 4294967286; + expect(toUnsigned32bit(-10)).to.equal(expected); + }); + + it('should cast signed to unsigned', function () { + let expected = -10; + expect(toSigned32bit(4294967286)).to.equal(expected); + }); +}); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.keyboard.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.keyboard.js index 77fe3f6f..3571d39c 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.keyboard.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.keyboard.js @@ -175,54 +175,6 @@ describe('Key Event Handling', function () { }; kbd._handleKeyDown(keyevent('keydown', {code: 'Unidentified', key: 'a'})); }); - - describe('iOS', function () { - let origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - - window.navigator.platform = "iPhone 9.0"; - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - }); - - it('should fake keyup events on iOS', function (done) { - if (browser.isIE() || browser.isEdge()) this.skip(); - let count = 0; - const kbd = new Keyboard(document); - kbd.onkeyevent = (keysym, code, down) => { - switch (count++) { - case 0: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - break; - case 1: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(false); - done(); - } - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - }); - }); }); describe('Track Key State', function () { @@ -320,7 +272,9 @@ describe('Key Event Handling', function () { window.navigator.platform = "Mac x86_64"; }); afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); + if (origNavigator !== undefined) { + Object.defineProperty(window, "navigator", origNavigator); + } }); it('should change Alt to AltGraph', function () { @@ -362,6 +316,82 @@ describe('Key Event Handling', function () { }); }); + describe('Caps Lock on iOS and macOS', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + if (origNavigator === undefined) { + // Object.getOwnPropertyDescriptor() doesn't work + // properly in any version of IE + this.skip(); + } + + Object.defineProperty(window, "navigator", {value: {}}); + if (window.navigator.platform !== undefined) { + // Object.defineProperty() doesn't work properly in old + // versions of Chrome + this.skip(); + } + }); + + afterEach(function () { + if (origNavigator !== undefined) { + Object.defineProperty(window, "navigator", origNavigator); + } + }); + + it('should toggle caps lock on key press on iOS', function (done) { + window.navigator.platform = "iPad"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'CapsLock', key: 'CapsLock'})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xFFE5, "CapsLock", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xFFE5, "CapsLock", false); + done(); + }); + + it('should toggle caps lock on key press on mac', function (done) { + window.navigator.platform = "Mac"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'CapsLock', key: 'CapsLock'})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xFFE5, "CapsLock", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xFFE5, "CapsLock", false); + done(); + }); + + it('should toggle caps lock on key release on iOS', function (done) { + window.navigator.platform = "iPad"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyUp(keyevent('keyup', {code: 'CapsLock', key: 'CapsLock'})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xFFE5, "CapsLock", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xFFE5, "CapsLock", false); + done(); + }); + + it('should toggle caps lock on key release on mac', function (done) { + window.navigator.platform = "Mac"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyUp(keyevent('keyup', {code: 'CapsLock', key: 'CapsLock'})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xFFE5, "CapsLock", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xFFE5, "CapsLock", false); + done(); + }); + }); + describe('Escape AltGraph on Windows', function () { let origNavigator; beforeEach(function () { @@ -387,8 +417,12 @@ describe('Key Event Handling', function () { this.clock = sinon.useFakeTimers(); }); afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - this.clock.restore(); + if (origNavigator !== undefined) { + Object.defineProperty(window, "navigator", origNavigator); + } + if (this.clock !== undefined) { + this.clock.restore(); + } }); it('should supress ControlLeft until it knows if it is AltGr', function () { @@ -437,7 +471,7 @@ describe('Key Event Handling', function () { expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0x61, "KeyA", true); // Check that the timer is properly dead - kbd.onkeyevent.reset(); + kbd.onkeyevent.resetHistory(); this.clock.tick(100); expect(kbd.onkeyevent).to.not.have.been.called; }); @@ -455,7 +489,7 @@ describe('Key Event Handling', function () { expect(kbd.onkeyevent.thirdCall).to.have.been.calledWith(0x61, "KeyA", false); // Check that the timer is properly dead - kbd.onkeyevent.reset(); + kbd.onkeyevent.resetHistory(); this.clock.tick(100); expect(kbd.onkeyevent).to.not.have.been.called; }); @@ -470,7 +504,7 @@ describe('Key Event Handling', function () { expect(kbd.onkeyevent).to.have.been.calledWith(0xfe03, 'AltRight', true); // Check that the timer is properly dead - kbd.onkeyevent.reset(); + kbd.onkeyevent.resetHistory(); this.clock.tick(100); expect(kbd.onkeyevent).to.not.have.been.called; }); @@ -486,7 +520,7 @@ describe('Key Event Handling', function () { expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xffea, "AltRight", true); // Check that the timer is properly dead - kbd.onkeyevent.reset(); + kbd.onkeyevent.resetHistory(); this.clock.tick(100); expect(kbd.onkeyevent).to.not.have.been.called; }); @@ -507,4 +541,78 @@ describe('Key Event Handling', function () { expect(kbd.onkeyevent).to.have.been.calledWith(0xfe03, 'AltRight', true); }); }); + + describe('Missing Shift keyup on Windows', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + if (origNavigator === undefined) { + // Object.getOwnPropertyDescriptor() doesn't work + // properly in any version of IE + this.skip(); + } + + Object.defineProperty(window, "navigator", {value: {}}); + if (window.navigator.platform !== undefined) { + // Object.defineProperty() doesn't work properly in old + // versions of Chrome + this.skip(); + } + + window.navigator.platform = "Windows x86_64"; + + this.clock = sinon.useFakeTimers(); + }); + afterEach(function () { + if (origNavigator !== undefined) { + Object.defineProperty(window, "navigator", origNavigator); + } + if (this.clock !== undefined) { + this.clock.restore(); + } + }); + + it('should fake a left Shift keyup', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'ShiftLeft', key: 'Shift', location: 1})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe1, 'ShiftLeft', true); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'ShiftRight', key: 'Shift', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe2, 'ShiftRight', true); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyUp(keyevent('keyup', {code: 'ShiftLeft', key: 'Shift', location: 1})); + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe2, 'ShiftRight', false); + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe1, 'ShiftLeft', false); + }); + + it('should fake a right Shift keyup', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'ShiftLeft', key: 'Shift', location: 1})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe1, 'ShiftLeft', true); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'ShiftRight', key: 'Shift', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe2, 'ShiftRight', true); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyUp(keyevent('keyup', {code: 'ShiftRight', key: 'Shift', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe2, 'ShiftRight', false); + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe1, 'ShiftLeft', false); + }); + }); }); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.localization.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.localization.js index 9570c179..301ab79f 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.localization.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.localization.js @@ -27,7 +27,9 @@ describe('Localization', function () { window.navigator.languages = []; }); afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); + if (origNavigator !== undefined) { + Object.defineProperty(window, "navigator", origNavigator); + } }); it('should use English by default', function () { diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.mouse.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.mouse.js deleted file mode 100644 index 78c74f15..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.mouse.js +++ /dev/null @@ -1,304 +0,0 @@ -const expect = chai.expect; - -import Mouse from '../core/input/mouse.js'; - -describe('Mouse Event Handling', function () { - "use strict"; - - let target; - - beforeEach(function () { - // For these tests we can assume that the canvas is 100x100 - // located at coordinates 10x10 - target = document.createElement('canvas'); - target.style.position = "absolute"; - target.style.top = "10px"; - target.style.left = "10px"; - target.style.width = "100px"; - target.style.height = "100px"; - document.body.appendChild(target); - }); - afterEach(function () { - document.body.removeChild(target); - target = null; - }); - - // The real constructors might not work everywhere we - // want to run these tests - const mouseevent = (typeArg, MouseEventInit) => { - const e = { type: typeArg }; - for (let key in MouseEventInit) { - e[key] = MouseEventInit[key]; - } - e.stopPropagation = sinon.spy(); - e.preventDefault = sinon.spy(); - return e; - }; - const touchevent = mouseevent; - - describe('Decode Mouse Events', function () { - it('should decode mousedown events', function (done) { - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - expect(bmask).to.be.equal(0x01); - expect(down).to.be.equal(1); - done(); - }; - mouse._handleMouseDown(mouseevent('mousedown', { button: '0x01' })); - }); - it('should decode mouseup events', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - expect(bmask).to.be.equal(0x01); - if (calls++ === 1) { - expect(down).to.not.be.equal(1); - done(); - } - }; - mouse._handleMouseDown(mouseevent('mousedown', { button: '0x01' })); - mouse._handleMouseUp(mouseevent('mouseup', { button: '0x01' })); - }); - it('should decode mousemove events', function (done) { - const mouse = new Mouse(target); - mouse.onmousemove = (x, y) => { - // Note that target relative coordinates are sent - expect(x).to.be.equal(40); - expect(y).to.be.equal(10); - done(); - }; - mouse._handleMouseMove(mouseevent('mousemove', - { clientX: 50, clientY: 20 })); - }); - it('should decode mousewheel events', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - expect(bmask).to.be.equal(1<<6); - if (calls === 1) { - expect(down).to.be.equal(1); - } else if (calls === 2) { - expect(down).to.not.be.equal(1); - done(); - } - }; - mouse._handleMouseWheel(mouseevent('mousewheel', - { deltaX: 50, deltaY: 0, - deltaMode: 0})); - }); - }); - - describe('Double-click for Touch', function () { - - beforeEach(function () { this.clock = sinon.useFakeTimers(); }); - afterEach(function () { this.clock.restore(); }); - - it('should use same pos for 2nd tap if close enough', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - done(); - } - }; - // touch events are sent in an array of events - // with one item for each touch point - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(200); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 67, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 66, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if far apart', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(200); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 57, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 56, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if not soon enough', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(500); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 67, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 66, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if not touch', function (done) { - let calls = 0; - const mouse = new Mouse(target); - mouse.onmousebutton = (x, y, down, bmask) => { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(mouseevent( - 'mousedown', { button: '0x01', clientX: 78, clientY: 46 })); - this.clock.tick(10); - mouse._handleMouseUp(mouseevent( - 'mouseup', { button: '0x01', clientX: 79, clientY: 45 })); - this.clock.tick(200); - mouse._handleMouseDown(mouseevent( - 'mousedown', { button: '0x01', clientX: 67, clientY: 35 })); - this.clock.tick(10); - mouse._handleMouseUp(mouseevent( - 'mouseup', { button: '0x01', clientX: 66, clientY: 36 })); - }); - - }); - - describe('Accumulate mouse wheel events with small delta', function () { - - beforeEach(function () { this.clock = sinon.useFakeTimers(); }); - afterEach(function () { this.clock.restore(); }); - - it('should accumulate wheel events if small enough', function () { - const mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - - // threshold is 10 - expect(mouse._accumulatedWheelDeltaX).to.be.equal(8); - - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - - expect(mouse.onmousebutton).to.have.callCount(2); // mouse down and up - - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 9, deltaMode: 0 })); - - expect(mouse._accumulatedWheelDeltaX).to.be.equal(4); - expect(mouse._accumulatedWheelDeltaY).to.be.equal(9); - - expect(mouse.onmousebutton).to.have.callCount(2); // still - }); - - it('should not accumulate large wheel events', function () { - const mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 11, deltaY: 0, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 0, deltaY: 70, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 400, deltaY: 400, deltaMode: 0 })); - - expect(mouse.onmousebutton).to.have.callCount(8); // mouse down and up - }); - - it('should send even small wheel events after a timeout', function () { - const mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 1, deltaY: 0, deltaMode: 0 })); - this.clock.tick(51); // timeout on 50 ms - - expect(mouse.onmousebutton).to.have.callCount(2); // mouse down and up - }); - - it('should account for non-zero deltaMode', function () { - const mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 0, deltaY: 2, deltaMode: 1 })); - - this.clock.tick(10); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 1, deltaY: 0, deltaMode: 2 })); - - expect(mouse.onmousebutton).to.have.callCount(4); // mouse down and up - }); - }); - -}); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.rfb.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.rfb.js index 99c9c90c..db9340ab 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.rfb.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.rfb.js @@ -2,7 +2,13 @@ const expect = chai.expect; import RFB from '../core/rfb.js'; import Websock from '../core/websock.js'; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; +import { deflateInit, deflate } from "../vendor/pako/lib/zlib/deflate.js"; import { encodings } from '../core/encodings.js'; +import { toUnsigned32bit } from '../core/util/int.js'; +import { encodeUTF8 } from '../core/util/strings.js'; +import KeyTable from '../core/input/keysym.js'; +import * as browser from '../core/util/browser.js'; import FakeWebSocket from './fake.websocket.js'; @@ -41,6 +47,44 @@ function push32(arr, num) { num & 0xFF); } +function pushString(arr, string) { + let utf8 = unescape(encodeURIComponent(string)); + for (let i = 0; i < utf8.length; i++) { + arr.push(utf8.charCodeAt(i)); + } +} + +function deflateWithSize(data) { + // Adds the size of the string in front before deflating + + let unCompData = []; + unCompData.push((data.length >> 24) & 0xFF, + (data.length >> 16) & 0xFF, + (data.length >> 8) & 0xFF, + (data.length & 0xFF)); + + for (let i = 0; i < data.length; i++) { + unCompData.push(data.charCodeAt(i)); + } + + let strm = new ZStream(); + let chunkSize = 1024 * 10 * 10; + strm.output = new Uint8Array(chunkSize); + deflateInit(strm, 5); + + /* eslint-disable camelcase */ + strm.input = unCompData; + strm.avail_in = strm.input.length; + strm.next_in = 0; + strm.next_out = 0; + strm.avail_out = chunkSize; + /* eslint-enable camelcase */ + + deflate(strm, 3); + + return new Uint8Array(strm.output.buffer, 0, strm.next_out); +} + describe('Remote Frame Buffer Protocol Client', function () { let clock; let raf; @@ -49,7 +93,7 @@ describe('Remote Frame Buffer Protocol Client', function () { after(FakeWebSocket.restore); before(function () { - this.clock = clock = sinon.useFakeTimers(); + this.clock = clock = sinon.useFakeTimers(Date.now()); // sinon doesn't support this yet raf = window.requestAnimationFrame; window.requestAnimationFrame = setTimeout; @@ -59,16 +103,18 @@ describe('Remote Frame Buffer Protocol Client', function () { const _sQ = new Uint8Array(sock._sQbufferSize); const rQ = new Uint8Array(sock._rQbufferSize); - Websock.prototype._old_allocate_buffers = Websock.prototype._allocate_buffers; - Websock.prototype._allocate_buffers = function () { + Websock.prototype._oldAllocateBuffers = Websock.prototype._allocateBuffers; + Websock.prototype._allocateBuffers = function () { this._sQ = _sQ; this._rQ = rQ; }; + // Avoiding printing the entire Websock buffer on errors + Websock.prototype.toString = function () { return "[object Websock]"; }; }); after(function () { - Websock.prototype._allocate_buffers = Websock.prototype._old_allocate_buffers; + delete Websock.prototype.toString; this.clock.restore(); window.requestAnimationFrame = raf; }); @@ -99,12 +145,12 @@ describe('Remote Frame Buffer Protocol Client', function () { container = null; }); - function make_rfb(url, options) { + function makeRFB(url, options) { url = url || 'wss://host:8675'; const rfb = new RFB(container, url, options); clock.tick(); rfb._sock._websocket._open(); - rfb._rfb_connection_state = 'connected'; + rfb._rfbConnectionState = 'connected'; sinon.spy(rfb, "_disconnect"); rfbs.push(rfb); return rfb; @@ -114,9 +160,9 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('#RFB', function () { it('should set the current state to "connecting"', function () { const client = new RFB(document.createElement('div'), 'wss://host:8675'); - client._rfb_connection_state = ''; + client._rfbConnectionState = ''; this.clock.tick(); - expect(client._rfb_connection_state).to.equal('connecting'); + expect(client._rfbConnectionState).to.equal('connecting'); }); it('should actually connect to the websocket', function () { @@ -131,7 +177,7 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('#disconnect', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); }); it('should go to state "disconnecting" before "disconnected"', function () { @@ -142,7 +188,7 @@ describe('Remote Frame Buffer Protocol Client', function () { .to.equal('disconnecting'); expect(client._updateConnectionState.getCall(1).args[0]) .to.equal('disconnected'); - expect(client._rfb_connection_state).to.equal('disconnected'); + expect(client._rfbConnectionState).to.equal('disconnected'); }); it('should unregister error event handler', function () { @@ -167,20 +213,20 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('#sendCredentials', function () { let client; beforeEach(function () { - client = make_rfb(); - client._rfb_connection_state = 'connecting'; + client = makeRFB(); + client._rfbConnectionState = 'connecting'; }); it('should set the rfb credentials properly"', function () { client.sendCredentials({ password: 'pass' }); - expect(client._rfb_credentials).to.deep.equal({ password: 'pass' }); + expect(client._rfbCredentials).to.deep.equal({ password: 'pass' }); }); - it('should call init_msg "soon"', function () { - client._init_msg = sinon.spy(); + it('should call initMsg "soon"', function () { + client._initMsg = sinon.spy(); client.sendCredentials({ password: 'pass' }); this.clock.tick(5); - expect(client._init_msg).to.have.been.calledOnce; + expect(client._initMsg).to.have.been.calledOnce; }); }); }); @@ -188,7 +234,7 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('Public API Basic Behavior', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); }); describe('#sendCtrlAlDel', function () { @@ -207,7 +253,7 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should not send the keys if we are not in a normal state', function () { sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "connecting"; + client._rfbConnectionState = "connecting"; client.sendCtrlAltDel(); expect(client._sock.flush).to.not.have.been.called; }); @@ -238,7 +284,7 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should not send the key if we are not in a normal state', function () { sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "connecting"; + client._rfbConnectionState = "connecting"; client.sendKey(123, 'Key123'); expect(client._sock.flush).to.not.have.been.called; }); @@ -271,7 +317,7 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should move focus to canvas object', function () { client._canvas.focus = sinon.spy(); client.focus(); - expect(client._canvas.focus).to.have.been.called.once; + expect(client._canvas.focus).to.have.been.calledOnce; }); }); @@ -279,32 +325,59 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should remove focus from canvas object', function () { client._canvas.blur = sinon.spy(); client.blur(); - expect(client._canvas.blur).to.have.been.called.once; + expect(client._canvas.blur).to.have.been.calledOnce; }); }); describe('#clipboardPasteFrom', function () { - it('should send the given text in a paste event', function () { - const expected = {_sQ: new Uint8Array(11), _sQlen: 0, - _sQbufferSize: 11, flush: () => {}}; - RFB.messages.clientCutText(expected, 'abc'); - client.clipboardPasteFrom('abc'); - expect(client._sock).to.have.sent(expected._sQ); + describe('Clipboard update handling', function () { + beforeEach(function () { + sinon.spy(RFB.messages, 'clientCutText'); + sinon.spy(RFB.messages, 'extendedClipboardNotify'); + }); + + afterEach(function () { + RFB.messages.clientCutText.restore(); + RFB.messages.extendedClipboardNotify.restore(); + }); + + it('should send the given text in an clipboard update', function () { + client.clipboardPasteFrom('abc'); + + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(client._sock, + new Uint8Array([97, 98, 99])); + }); + + it('should send an notify if extended clipboard is supported by server', function () { + // Send our capabilities + let data = [3, 0, 0, 0]; + const flags = [0x1F, 0x00, 0x00, 0x01]; + let fileSizes = [0x00, 0x00, 0x00, 0x1E]; + + push32(data, toUnsigned32bit(-8)); + data = data.concat(flags); + data = data.concat(fileSizes); + client._sock._websocket._receiveData(new Uint8Array(data)); + + client.clipboardPasteFrom('extended test'); + expect(RFB.messages.extendedClipboardNotify).to.have.been.calledOnce; + }); }); it('should flush multiple times for large clipboards', function () { sinon.spy(client._sock, 'flush'); - let long_text = ""; + let longText = ""; for (let i = 0; i < client._sock._sQbufferSize + 100; i++) { - long_text += 'a'; + longText += 'a'; } - client.clipboardPasteFrom(long_text); + client.clipboardPasteFrom(longText); expect(client._sock.flush).to.have.been.calledTwice; }); it('should not send the text if we are not in a normal state', function () { sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "connecting"; + client._rfbConnectionState = "connecting"; client.clipboardPasteFrom('abc'); expect(client._sock.flush).to.not.have.been.called; }); @@ -312,7 +385,7 @@ describe('Remote Frame Buffer Protocol Client', function () { describe("XVP operations", function () { beforeEach(function () { - client._rfb_xvp_ver = 1; + client._rfbXvpVer = 1; }); it('should send the shutdown signal on #machineShutdown', function () { @@ -341,7 +414,7 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('Clipping', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); container.style.width = '70px'; container.style.height = '80px'; client.clipViewport = true; @@ -353,7 +426,7 @@ describe('Remote Frame Buffer Protocol Client', function () { client.clipViewport = false; expect(spy.set).to.have.been.calledOnce; expect(spy.set).to.have.been.calledWith(false); - spy.set.reset(); + spy.set.resetHistory(); client.clipViewport = true; expect(spy.set).to.have.been.calledOnce; @@ -383,7 +456,7 @@ describe('Remote Frame Buffer Protocol Client', function () { sinon.spy(client._display, "viewportChangeSize"); - client._sock._websocket._receive_data(new Uint8Array(incoming)); + client._sock._websocket._receiveData(new Uint8Array(incoming)); // FIXME: Display implicitly calls viewportChangeSize() when // resizing the framebuffer, hence calledTwice. @@ -438,7 +511,7 @@ describe('Remote Frame Buffer Protocol Client', function () { client._handleMouseButton(13, 9, 0x000); expect(RFB.messages.pointerEvent).to.have.been.calledTwice; - RFB.messages.pointerEvent.reset(); + RFB.messages.pointerEvent.resetHistory(); // Small movement client._handleMouseButton(13, 9, 0x001); @@ -447,6 +520,13 @@ describe('Remote Frame Buffer Protocol Client', function () { expect(RFB.messages.pointerEvent).to.have.been.calledTwice; }); + it('should not send button messages when in view only', function () { + client._viewOnly = true; + client._handleMouseButton(13, 9, 0x001); + client._handleMouseButton(13, 9, 0x000); + expect(RFB.messages.pointerEvent).to.not.have.been.called; + }); + it('should send button message directly when drag is disabled', function () { client.dragViewport = false; client._handleMouseButton(13, 9, 0x001); @@ -472,7 +552,7 @@ describe('Remote Frame Buffer Protocol Client', function () { expect(client._display.viewportChangePos).to.have.been.calledOnce; expect(client._display.viewportChangePos).to.have.been.calledWith(-30, 0); - client._display.viewportChangePos.reset(); + client._display.viewportChangePos.resetHistory(); // Now a small movement should move right away @@ -514,7 +594,7 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('Scaling', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); container.style.width = '70px'; container.style.height = '80px'; client.scaleViewport = true; @@ -543,7 +623,7 @@ describe('Remote Frame Buffer Protocol Client', function () { expect(spy.set).to.have.been.calledOnce; expect(spy.set).to.have.been.calledWith(true); - spy.set.reset(); + spy.set.resetHistory(); client.scaleViewport = true; expect(spy.set).to.have.been.calledOnce; @@ -573,7 +653,7 @@ describe('Remote Frame Buffer Protocol Client', function () { sinon.spy(client._display, "autoscale"); - client._sock._websocket._receive_data(new Uint8Array(incoming)); + client._sock._websocket._receiveData(new Uint8Array(incoming)); expect(client._display.autoscale).to.have.been.calledOnce; expect(client._display.autoscale).to.have.been.calledWith(70, 80); @@ -597,7 +677,7 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('Remote resize', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); client._supportsSetDesktopSize = true; client.resizeSession = true; container.style.width = '70px'; @@ -628,16 +708,16 @@ describe('Remote Frame Buffer Protocol Client', function () { client._supportsSetDesktopSize = false; - client._sock._websocket._receive_data(new Uint8Array(incoming)); + client._sock._websocket._receiveData(new Uint8Array(incoming)); expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; expect(RFB.messages.setDesktopSize).to.have.been.calledWith(sinon.match.object, 70, 80, 0, 0); - RFB.messages.setDesktopSize.reset(); + RFB.messages.setDesktopSize.resetHistory(); // Second message should not trigger a resize - client._sock._websocket._receive_data(new Uint8Array(incoming)); + client._sock._websocket._receiveData(new Uint8Array(incoming)); expect(RFB.messages.setDesktopSize).to.not.have.been.called; }); @@ -720,7 +800,7 @@ describe('Remote Frame Buffer Protocol Client', function () { 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00 ]; - client._sock._websocket._receive_data(new Uint8Array(incoming)); + client._sock._websocket._receiveData(new Uint8Array(incoming)); expect(RFB.messages.setDesktopSize).to.not.have.been.called; }); @@ -730,37 +810,37 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('#_updateConnectionState', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); }); it('should clear the disconnect timer if the state is not "disconnecting"', function () { const spy = sinon.spy(); client._disconnTimer = setTimeout(spy, 50); - client._rfb_connection_state = 'connecting'; + client._rfbConnectionState = 'connecting'; client._updateConnectionState('connected'); this.clock.tick(51); expect(spy).to.not.have.been.called; expect(client._disconnTimer).to.be.null; }); - it('should set the rfb_connection_state', function () { - client._rfb_connection_state = 'connecting'; + it('should set the rfbConnectionState', function () { + client._rfbConnectionState = 'connecting'; client._updateConnectionState('connected'); - expect(client._rfb_connection_state).to.equal('connected'); + expect(client._rfbConnectionState).to.equal('connected'); }); it('should not change the state when we are disconnected', function () { client.disconnect(); - expect(client._rfb_connection_state).to.equal('disconnected'); + expect(client._rfbConnectionState).to.equal('disconnected'); client._updateConnectionState('connecting'); - expect(client._rfb_connection_state).to.not.equal('connecting'); + expect(client._rfbConnectionState).to.not.equal('connecting'); }); it('should ignore state changes to the same state', function () { const connectSpy = sinon.spy(); client.addEventListener("connect", connectSpy); - expect(client._rfb_connection_state).to.equal('connected'); + expect(client._rfbConnectionState).to.equal('connected'); client._updateConnectionState('connected'); expect(connectSpy).to.not.have.been.called; @@ -769,7 +849,7 @@ describe('Remote Frame Buffer Protocol Client', function () { const disconnectSpy = sinon.spy(); client.addEventListener("disconnect", disconnectSpy); - expect(client._rfb_connection_state).to.equal('disconnected'); + expect(client._rfbConnectionState).to.equal('disconnected'); client._updateConnectionState('disconnected'); expect(disconnectSpy).to.not.have.been.called; }); @@ -778,7 +858,7 @@ describe('Remote Frame Buffer Protocol Client', function () { const spy = sinon.spy(); client.addEventListener("disconnect", spy); client._updateConnectionState('disconnected'); - expect(client._rfb_connection_state).to.not.equal('disconnected'); + expect(client._rfbConnectionState).to.not.equal('disconnected'); expect(spy).to.not.have.been.called; }); }); @@ -786,7 +866,7 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('#_fail', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); }); it('should close the WebSocket connection', function () { @@ -800,18 +880,18 @@ describe('Remote Frame Buffer Protocol Client', function () { client._fail(); this.clock.tick(2000); expect(client._updateConnectionState).to.have.been.called; - expect(client._rfb_connection_state).to.equal('disconnected'); + expect(client._rfbConnectionState).to.equal('disconnected'); }); it('should set clean_disconnect variable', function () { - client._rfb_clean_disconnect = true; - client._rfb_connection_state = 'connected'; + client._rfbCleanDisconnect = true; + client._rfbConnectionState = 'connected'; client._fail(); - expect(client._rfb_clean_disconnect).to.be.false; + expect(client._rfbCleanDisconnect).to.be.false; }); it('should result in disconnect event with clean set to false', function () { - client._rfb_connection_state = 'connected'; + client._rfbConnectionState = 'connected'; const spy = sinon.spy(); client.addEventListener("disconnect", spy); client._fail(); @@ -837,13 +917,13 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('connected', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); }); it('should result in a connect event if state becomes connected', function () { const spy = sinon.spy(); client.addEventListener("connect", spy); - client._rfb_connection_state = 'connecting'; + client._rfbConnectionState = 'connecting'; client._updateConnectionState('connected'); expect(spy).to.have.been.calledOnce; }); @@ -860,7 +940,7 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('disconnecting', function () { let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); }); it('should force disconnect if we do not call Websock.onclose within the disconnection timeout', function () { @@ -869,8 +949,8 @@ describe('Remote Frame Buffer Protocol Client', function () { client._updateConnectionState('disconnecting'); this.clock.tick(3 * 1000); expect(client._updateConnectionState).to.have.been.calledTwice; - expect(client._rfb_disconnect_reason).to.not.equal(""); - expect(client._rfb_connection_state).to.equal("disconnected"); + expect(client._rfbDisconnectReason).to.not.equal(""); + expect(client._rfbConnectionState).to.equal("disconnected"); }); it('should not fail if Websock.onclose gets called within the disconnection timeout', function () { @@ -878,7 +958,7 @@ describe('Remote Frame Buffer Protocol Client', function () { this.clock.tick(3 * 1000 / 2); client._sock._websocket.close(); this.clock.tick(3 * 1000 / 2 + 1); - expect(client._rfb_connection_state).to.equal('disconnected'); + expect(client._rfbConnectionState).to.equal('disconnected'); }); it('should close the WebSocket connection', function () { @@ -905,7 +985,7 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should result in a disconnect event if state becomes "disconnected"', function () { const spy = sinon.spy(); client.addEventListener("disconnect", spy); - client._rfb_connection_state = 'disconnecting'; + client._rfbConnectionState = 'disconnecting'; client._updateConnectionState('disconnected'); expect(spy).to.have.been.calledOnce; expect(spy.args[0][0].detail.clean).to.be.true; @@ -914,8 +994,8 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should result in a disconnect event without msg when no reason given', function () { const spy = sinon.spy(); client.addEventListener("disconnect", spy); - client._rfb_connection_state = 'disconnecting'; - client._rfb_disconnect_reason = ""; + client._rfbConnectionState = 'disconnecting'; + client._rfbDisconnectReason = ""; client._updateConnectionState('disconnected'); expect(spy).to.have.been.calledOnce; expect(spy.args[0].length).to.equal(1); @@ -926,152 +1006,152 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('Protocol Initialization States', function () { let client; beforeEach(function () { - client = make_rfb(); - client._rfb_connection_state = 'connecting'; + client = makeRFB(); + client._rfbConnectionState = 'connecting'; }); describe('ProtocolVersion', function () { - function send_ver(ver, client) { + function sendVer(ver, client) { const arr = new Uint8Array(12); for (let i = 0; i < ver.length; i++) { arr[i+4] = ver.charCodeAt(i); } arr[0] = 'R'; arr[1] = 'F'; arr[2] = 'B'; arr[3] = ' '; arr[11] = '\n'; - client._sock._websocket._receive_data(arr); + client._sock._websocket._receiveData(arr); } describe('version parsing', function () { it('should interpret version 003.003 as version 3.3', function () { - send_ver('003.003', client); - expect(client._rfb_version).to.equal(3.3); + sendVer('003.003', client); + expect(client._rfbVersion).to.equal(3.3); }); it('should interpret version 003.006 as version 3.3', function () { - send_ver('003.006', client); - expect(client._rfb_version).to.equal(3.3); + sendVer('003.006', client); + expect(client._rfbVersion).to.equal(3.3); }); it('should interpret version 003.889 as version 3.3', function () { - send_ver('003.889', client); - expect(client._rfb_version).to.equal(3.3); + sendVer('003.889', client); + expect(client._rfbVersion).to.equal(3.3); }); it('should interpret version 003.007 as version 3.7', function () { - send_ver('003.007', client); - expect(client._rfb_version).to.equal(3.7); + sendVer('003.007', client); + expect(client._rfbVersion).to.equal(3.7); }); it('should interpret version 003.008 as version 3.8', function () { - send_ver('003.008', client); - expect(client._rfb_version).to.equal(3.8); + sendVer('003.008', client); + expect(client._rfbVersion).to.equal(3.8); }); it('should interpret version 004.000 as version 3.8', function () { - send_ver('004.000', client); - expect(client._rfb_version).to.equal(3.8); + sendVer('004.000', client); + expect(client._rfbVersion).to.equal(3.8); }); it('should interpret version 004.001 as version 3.8', function () { - send_ver('004.001', client); - expect(client._rfb_version).to.equal(3.8); + sendVer('004.001', client); + expect(client._rfbVersion).to.equal(3.8); }); it('should interpret version 005.000 as version 3.8', function () { - send_ver('005.000', client); - expect(client._rfb_version).to.equal(3.8); + sendVer('005.000', client); + expect(client._rfbVersion).to.equal(3.8); }); it('should fail on an invalid version', function () { sinon.spy(client, "_fail"); - send_ver('002.000', client); + sendVer('002.000', client); expect(client._fail).to.have.been.calledOnce; }); }); it('should send back the interpreted version', function () { - send_ver('004.000', client); + sendVer('004.000', client); - const expected_str = 'RFB 003.008\n'; + const expectedStr = 'RFB 003.008\n'; const expected = []; - for (let i = 0; i < expected_str.length; i++) { - expected[i] = expected_str.charCodeAt(i); + for (let i = 0; i < expectedStr.length; i++) { + expected[i] = expectedStr.charCodeAt(i); } expect(client._sock).to.have.sent(new Uint8Array(expected)); }); it('should transition to the Security state on successful negotiation', function () { - send_ver('003.008', client); - expect(client._rfb_init_state).to.equal('Security'); + sendVer('003.008', client); + expect(client._rfbInitState).to.equal('Security'); }); describe('Repeater', function () { beforeEach(function () { - client = make_rfb('wss://host:8675', { repeaterID: "12345" }); - client._rfb_connection_state = 'connecting'; + client = makeRFB('wss://host:8675', { repeaterID: "12345" }); + client._rfbConnectionState = 'connecting'; }); it('should interpret version 000.000 as a repeater', function () { - send_ver('000.000', client); - expect(client._rfb_version).to.equal(0); + sendVer('000.000', client); + expect(client._rfbVersion).to.equal(0); - const sent_data = client._sock._websocket._get_sent_data(); - expect(new Uint8Array(sent_data.buffer, 0, 9)).to.array.equal(new Uint8Array([73, 68, 58, 49, 50, 51, 52, 53, 0])); - expect(sent_data).to.have.length(250); + const sentData = client._sock._websocket._getSentData(); + expect(new Uint8Array(sentData.buffer, 0, 9)).to.array.equal(new Uint8Array([73, 68, 58, 49, 50, 51, 52, 53, 0])); + expect(sentData).to.have.length(250); }); it('should handle two step repeater negotiation', function () { - send_ver('000.000', client); - send_ver('003.008', client); - expect(client._rfb_version).to.equal(3.8); + sendVer('000.000', client); + sendVer('003.008', client); + expect(client._rfbVersion).to.equal(3.8); }); }); }); describe('Security', function () { beforeEach(function () { - client._rfb_init_state = 'Security'; + client._rfbInitState = 'Security'; }); it('should simply receive the auth scheme when for versions < 3.7', function () { - client._rfb_version = 3.6; - const auth_scheme_raw = [1, 2, 3, 4]; - const auth_scheme = (auth_scheme_raw[0] << 24) + (auth_scheme_raw[1] << 16) + - (auth_scheme_raw[2] << 8) + auth_scheme_raw[3]; - client._sock._websocket._receive_data(new Uint8Array(auth_scheme_raw)); - expect(client._rfb_auth_scheme).to.equal(auth_scheme); + client._rfbVersion = 3.6; + const authSchemeRaw = [1, 2, 3, 4]; + const authScheme = (authSchemeRaw[0] << 24) + (authSchemeRaw[1] << 16) + + (authSchemeRaw[2] << 8) + authSchemeRaw[3]; + client._sock._websocket._receiveData(new Uint8Array(authSchemeRaw)); + expect(client._rfbAuthScheme).to.equal(authScheme); }); it('should prefer no authentication is possible', function () { - client._rfb_version = 3.7; - const auth_schemes = [2, 1, 3]; - client._sock._websocket._receive_data(new Uint8Array(auth_schemes)); - expect(client._rfb_auth_scheme).to.equal(1); + client._rfbVersion = 3.7; + const authSchemes = [2, 1, 3]; + client._sock._websocket._receiveData(new Uint8Array(authSchemes)); + expect(client._rfbAuthScheme).to.equal(1); expect(client._sock).to.have.sent(new Uint8Array([1, 1])); }); it('should choose for the most prefered scheme possible for versions >= 3.7', function () { - client._rfb_version = 3.7; - const auth_schemes = [2, 22, 16]; - client._sock._websocket._receive_data(new Uint8Array(auth_schemes)); - expect(client._rfb_auth_scheme).to.equal(22); + client._rfbVersion = 3.7; + const authSchemes = [2, 22, 16]; + client._sock._websocket._receiveData(new Uint8Array(authSchemes)); + expect(client._rfbAuthScheme).to.equal(22); expect(client._sock).to.have.sent(new Uint8Array([22])); }); it('should fail if there are no supported schemes for versions >= 3.7', function () { sinon.spy(client, "_fail"); - client._rfb_version = 3.7; - const auth_schemes = [1, 32]; - client._sock._websocket._receive_data(new Uint8Array(auth_schemes)); + client._rfbVersion = 3.7; + const authSchemes = [1, 32]; + client._sock._websocket._receiveData(new Uint8Array(authSchemes)); expect(client._fail).to.have.been.calledOnce; }); it('should fail with the appropriate message if no types are sent for versions >= 3.7', function () { - client._rfb_version = 3.7; - const failure_data = [0, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; + client._rfbVersion = 3.7; + const failureData = [0, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; sinon.spy(client, '_fail'); - client._sock._websocket._receive_data(new Uint8Array(failure_data)); + client._sock._websocket._receiveData(new Uint8Array(failureData)); expect(client._fail).to.have.been.calledOnce; expect(client._fail).to.have.been.calledWith( @@ -1079,126 +1159,126 @@ describe('Remote Frame Buffer Protocol Client', function () { }); it('should transition to the Authentication state and continue on successful negotiation', function () { - client._rfb_version = 3.7; - const auth_schemes = [1, 1]; - client._negotiate_authentication = sinon.spy(); - client._sock._websocket._receive_data(new Uint8Array(auth_schemes)); - expect(client._rfb_init_state).to.equal('Authentication'); - expect(client._negotiate_authentication).to.have.been.calledOnce; + client._rfbVersion = 3.7; + const authSchemes = [1, 1]; + client._negotiateAuthentication = sinon.spy(); + client._sock._websocket._receiveData(new Uint8Array(authSchemes)); + expect(client._rfbInitState).to.equal('Authentication'); + expect(client._negotiateAuthentication).to.have.been.calledOnce; }); }); describe('Authentication', function () { beforeEach(function () { - client._rfb_init_state = 'Security'; + client._rfbInitState = 'Security'; }); - function send_security(type, cl) { - cl._sock._websocket._receive_data(new Uint8Array([1, type])); + function sendSecurity(type, cl) { + cl._sock._websocket._receiveData(new Uint8Array([1, type])); } it('should fail on auth scheme 0 (pre 3.7) with the given message', function () { - client._rfb_version = 3.6; - const err_msg = "Whoopsies"; + client._rfbVersion = 3.6; + const errMsg = "Whoopsies"; const data = [0, 0, 0, 0]; - const err_len = err_msg.length; - push32(data, err_len); - for (let i = 0; i < err_len; i++) { - data.push(err_msg.charCodeAt(i)); + const errLen = errMsg.length; + push32(data, errLen); + for (let i = 0; i < errLen; i++) { + data.push(errMsg.charCodeAt(i)); } sinon.spy(client, '_fail'); - client._sock._websocket._receive_data(new Uint8Array(data)); + client._sock._websocket._receiveData(new Uint8Array(data)); expect(client._fail).to.have.been.calledWith( 'Security negotiation failed on authentication scheme (reason: Whoopsies)'); }); it('should transition straight to SecurityResult on "no auth" (1) for versions >= 3.8', function () { - client._rfb_version = 3.8; - send_security(1, client); - expect(client._rfb_init_state).to.equal('SecurityResult'); + client._rfbVersion = 3.8; + sendSecurity(1, client); + expect(client._rfbInitState).to.equal('SecurityResult'); }); it('should transition straight to ServerInitialisation on "no auth" for versions < 3.8', function () { - client._rfb_version = 3.7; - send_security(1, client); - expect(client._rfb_init_state).to.equal('ServerInitialisation'); + client._rfbVersion = 3.7; + sendSecurity(1, client); + expect(client._rfbInitState).to.equal('ServerInitialisation'); }); it('should fail on an unknown auth scheme', function () { sinon.spy(client, "_fail"); - client._rfb_version = 3.8; - send_security(57, client); + client._rfbVersion = 3.8; + sendSecurity(57, client); expect(client._fail).to.have.been.calledOnce; }); describe('VNC Authentication (type 2) Handler', function () { beforeEach(function () { - client._rfb_init_state = 'Security'; - client._rfb_version = 3.8; + client._rfbInitState = 'Security'; + client._rfbVersion = 3.8; }); it('should fire the credentialsrequired event if missing a password', function () { const spy = sinon.spy(); client.addEventListener("credentialsrequired", spy); - send_security(2, client); + sendSecurity(2, client); const challenge = []; for (let i = 0; i < 16; i++) { challenge[i] = i; } - client._sock._websocket._receive_data(new Uint8Array(challenge)); + client._sock._websocket._receiveData(new Uint8Array(challenge)); - expect(client._rfb_credentials).to.be.empty; + expect(client._rfbCredentials).to.be.empty; expect(spy).to.have.been.calledOnce; expect(spy.args[0][0].detail.types).to.have.members(["password"]); }); it('should encrypt the password with DES and then send it back', function () { - client._rfb_credentials = { password: 'passwd' }; - send_security(2, client); - client._sock._websocket._get_sent_data(); // skip the choice of auth reply + client._rfbCredentials = { password: 'passwd' }; + sendSecurity(2, client); + client._sock._websocket._getSentData(); // skip the choice of auth reply const challenge = []; for (let i = 0; i < 16; i++) { challenge[i] = i; } - client._sock._websocket._receive_data(new Uint8Array(challenge)); + client._sock._websocket._receiveData(new Uint8Array(challenge)); - const des_pass = RFB.genDES('passwd', challenge); - expect(client._sock).to.have.sent(new Uint8Array(des_pass)); + const desPass = RFB.genDES('passwd', challenge); + expect(client._sock).to.have.sent(new Uint8Array(desPass)); }); it('should transition to SecurityResult immediately after sending the password', function () { - client._rfb_credentials = { password: 'passwd' }; - send_security(2, client); + client._rfbCredentials = { password: 'passwd' }; + sendSecurity(2, client); const challenge = []; for (let i = 0; i < 16; i++) { challenge[i] = i; } - client._sock._websocket._receive_data(new Uint8Array(challenge)); + client._sock._websocket._receiveData(new Uint8Array(challenge)); - expect(client._rfb_init_state).to.equal('SecurityResult'); + expect(client._rfbInitState).to.equal('SecurityResult'); }); }); describe('XVP Authentication (type 22) Handler', function () { beforeEach(function () { - client._rfb_init_state = 'Security'; - client._rfb_version = 3.8; + client._rfbInitState = 'Security'; + client._rfbVersion = 3.8; }); it('should fall through to standard VNC authentication upon completion', function () { - client._rfb_credentials = { username: 'user', - target: 'target', - password: 'password' }; - client._negotiate_std_vnc_auth = sinon.spy(); - send_security(22, client); - expect(client._negotiate_std_vnc_auth).to.have.been.calledOnce; + client._rfbCredentials = { username: 'user', + target: 'target', + password: 'password' }; + client._negotiateStdVNCAuth = sinon.spy(); + sendSecurity(22, client); + expect(client._negotiateStdVNCAuth).to.have.been.calledOnce; }); it('should fire the credentialsrequired event if all credentials are missing', function () { const spy = sinon.spy(); client.addEventListener("credentialsrequired", spy); - client._rfb_credentials = {}; - send_security(22, client); + client._rfbCredentials = {}; + sendSecurity(22, client); - expect(client._rfb_credentials).to.be.empty; + expect(client._rfbCredentials).to.be.empty; expect(spy).to.have.been.calledOnce; expect(spy.args[0][0].detail.types).to.have.members(["username", "password", "target"]); }); @@ -1206,21 +1286,21 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should fire the credentialsrequired event if some credentials are missing', function () { const spy = sinon.spy(); client.addEventListener("credentialsrequired", spy); - client._rfb_credentials = { username: 'user', - target: 'target' }; - send_security(22, client); + client._rfbCredentials = { username: 'user', + target: 'target' }; + sendSecurity(22, client); expect(spy).to.have.been.calledOnce; expect(spy.args[0][0].detail.types).to.have.members(["username", "password", "target"]); }); it('should send user and target separately', function () { - client._rfb_credentials = { username: 'user', - target: 'target', - password: 'password' }; - client._negotiate_std_vnc_auth = sinon.spy(); + client._rfbCredentials = { username: 'user', + target: 'target', + password: 'password' }; + client._negotiateStdVNCAuth = sinon.spy(); - send_security(22, client); + sendSecurity(22, client); const expected = [22, 4, 6]; // auth selection, len user, len target for (let i = 0; i < 10; i++) { expected[i+3] = 'usertarget'.charCodeAt(i); } @@ -1231,13 +1311,13 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('TightVNC Authentication (type 16) Handler', function () { beforeEach(function () { - client._rfb_init_state = 'Security'; - client._rfb_version = 3.8; - send_security(16, client); - client._sock._websocket._get_sent_data(); // skip the security reply + client._rfbInitState = 'Security'; + client._rfbVersion = 3.8; + sendSecurity(16, client); + client._sock._websocket._getSentData(); // skip the security reply }); - function send_num_str_pairs(pairs, client) { + function sendNumStrPairs(pairs, client) { const data = []; push32(data, pairs.length); @@ -1251,67 +1331,67 @@ describe('Remote Frame Buffer Protocol Client', function () { } } - client._sock._websocket._receive_data(new Uint8Array(data)); + client._sock._websocket._receiveData(new Uint8Array(data)); } it('should skip tunnel negotiation if no tunnels are requested', function () { - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._rfb_tightvnc).to.be.true; + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); + expect(client._rfbTightVNC).to.be.true; }); it('should fail if no supported tunnels are listed', function () { sinon.spy(client, "_fail"); - send_num_str_pairs([[123, 'OTHR', 'SOMETHNG']], client); + sendNumStrPairs([[123, 'OTHR', 'SOMETHNG']], client); expect(client._fail).to.have.been.calledOnce; }); it('should choose the notunnel tunnel type', function () { - send_num_str_pairs([[0, 'TGHT', 'NOTUNNEL'], [123, 'OTHR', 'SOMETHNG']], client); + sendNumStrPairs([[0, 'TGHT', 'NOTUNNEL'], [123, 'OTHR', 'SOMETHNG']], client); expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 0])); }); it('should choose the notunnel tunnel type for Siemens devices', function () { - send_num_str_pairs([[1, 'SICR', 'SCHANNEL'], [2, 'SICR', 'SCHANLPW']], client); + sendNumStrPairs([[1, 'SICR', 'SCHANNEL'], [2, 'SICR', 'SCHANLPW']], client); expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 0])); }); it('should continue to sub-auth negotiation after tunnel negotiation', function () { - send_num_str_pairs([[0, 'TGHT', 'NOTUNNEL']], client); - client._sock._websocket._get_sent_data(); // skip the tunnel choice here - send_num_str_pairs([[1, 'STDV', 'NOAUTH__']], client); + sendNumStrPairs([[0, 'TGHT', 'NOTUNNEL']], client); + client._sock._websocket._getSentData(); // skip the tunnel choice here + sendNumStrPairs([[1, 'STDV', 'NOAUTH__']], client); expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 1])); - expect(client._rfb_init_state).to.equal('SecurityResult'); + expect(client._rfbInitState).to.equal('SecurityResult'); }); /*it('should attempt to use VNC auth over no auth when possible', function () { - client._rfb_tightvnc = true; - client._negotiate_std_vnc_auth = sinon.spy(); - send_num_str_pairs([[1, 'STDV', 'NOAUTH__'], [2, 'STDV', 'VNCAUTH_']], client); + client._rfbTightVNC = true; + client._negotiateStdVNCAuth = sinon.spy(); + sendNumStrPairs([[1, 'STDV', 'NOAUTH__'], [2, 'STDV', 'VNCAUTH_']], client); expect(client._sock).to.have.sent([0, 0, 0, 1]); - expect(client._negotiate_std_vnc_auth).to.have.been.calledOnce; - expect(client._rfb_auth_scheme).to.equal(2); + expect(client._negotiateStdVNCAuth).to.have.been.calledOnce; + expect(client._rfbAuthScheme).to.equal(2); });*/ // while this would make sense, the original code doesn't actually do this it('should accept the "no auth" auth type and transition to SecurityResult', function () { - client._rfb_tightvnc = true; - send_num_str_pairs([[1, 'STDV', 'NOAUTH__']], client); + client._rfbTightVNC = true; + sendNumStrPairs([[1, 'STDV', 'NOAUTH__']], client); expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 1])); - expect(client._rfb_init_state).to.equal('SecurityResult'); + expect(client._rfbInitState).to.equal('SecurityResult'); }); it('should accept VNC authentication and transition to that', function () { - client._rfb_tightvnc = true; - client._negotiate_std_vnc_auth = sinon.spy(); - send_num_str_pairs([[2, 'STDV', 'VNCAUTH__']], client); + client._rfbTightVNC = true; + client._negotiateStdVNCAuth = sinon.spy(); + sendNumStrPairs([[2, 'STDV', 'VNCAUTH__']], client); expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 2])); - expect(client._negotiate_std_vnc_auth).to.have.been.calledOnce; - expect(client._rfb_auth_scheme).to.equal(2); + expect(client._negotiateStdVNCAuth).to.have.been.calledOnce; + expect(client._rfbAuthScheme).to.equal(2); }); it('should fail if there are no supported auth types', function () { sinon.spy(client, "_fail"); - client._rfb_tightvnc = true; - send_num_str_pairs([[23, 'stdv', 'badval__']], client); + client._rfbTightVNC = true; + sendNumStrPairs([[23, 'stdv', 'badval__']], client); expect(client._fail).to.have.been.calledOnce; }); }); @@ -1319,27 +1399,27 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('SecurityResult', function () { beforeEach(function () { - client._rfb_init_state = 'SecurityResult'; + client._rfbInitState = 'SecurityResult'; }); it('should fall through to ServerInitialisation on a response code of 0', function () { - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._rfb_init_state).to.equal('ServerInitialisation'); + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); + expect(client._rfbInitState).to.equal('ServerInitialisation'); }); it('should fail on an error code of 1 with the given message for versions >= 3.8', function () { - client._rfb_version = 3.8; + client._rfbVersion = 3.8; sinon.spy(client, '_fail'); - const failure_data = [0, 0, 0, 1, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); + const failureData = [0, 0, 0, 1, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; + client._sock._websocket._receiveData(new Uint8Array(failureData)); expect(client._fail).to.have.been.calledWith( 'Security negotiation failed on security result (reason: whoops)'); }); it('should fail on an error code of 1 with a standard message for version < 3.8', function () { sinon.spy(client, '_fail'); - client._rfb_version = 3.7; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 1])); + client._rfbVersion = 3.7; + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 1])); expect(client._fail).to.have.been.calledWith( 'Security handshake failed'); }); @@ -1347,37 +1427,37 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should result in securityfailure event when receiving a non zero status', function () { const spy = sinon.spy(); client.addEventListener("securityfailure", spy); - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 2])); + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 2])); expect(spy).to.have.been.calledOnce; expect(spy.args[0][0].detail.status).to.equal(2); }); it('should include reason when provided in securityfailure event', function () { - client._rfb_version = 3.8; + client._rfbVersion = 3.8; const spy = sinon.spy(); client.addEventListener("securityfailure", spy); - const failure_data = [0, 0, 0, 1, 0, 0, 0, 12, 115, 117, 99, 104, - 32, 102, 97, 105, 108, 117, 114, 101]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); + const failureData = [0, 0, 0, 1, 0, 0, 0, 12, 115, 117, 99, 104, + 32, 102, 97, 105, 108, 117, 114, 101]; + client._sock._websocket._receiveData(new Uint8Array(failureData)); expect(spy.args[0][0].detail.status).to.equal(1); expect(spy.args[0][0].detail.reason).to.equal('such failure'); }); it('should not include reason when length is zero in securityfailure event', function () { - client._rfb_version = 3.9; + client._rfbVersion = 3.9; const spy = sinon.spy(); client.addEventListener("securityfailure", spy); - const failure_data = [0, 0, 0, 1, 0, 0, 0, 0]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); + const failureData = [0, 0, 0, 1, 0, 0, 0, 0]; + client._sock._websocket._receiveData(new Uint8Array(failureData)); expect(spy.args[0][0].detail.status).to.equal(1); expect('reason' in spy.args[0][0].detail).to.be.false; }); it('should not include reason in securityfailure event for version < 3.8', function () { - client._rfb_version = 3.6; + client._rfbVersion = 3.6; const spy = sinon.spy(); client.addEventListener("securityfailure", spy); - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 2])); + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 2])); expect(spy.args[0][0].detail.status).to.equal(2); expect('reason' in spy.args[0][0].detail).to.be.false; }); @@ -1385,78 +1465,79 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('ClientInitialisation', function () { it('should transition to the ServerInitialisation state', function () { - const client = make_rfb(); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._rfb_init_state).to.equal('ServerInitialisation'); + const client = makeRFB(); + client._rfbConnectionState = 'connecting'; + client._rfbInitState = 'SecurityResult'; + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); + expect(client._rfbInitState).to.equal('ServerInitialisation'); }); it('should send 1 if we are in shared mode', function () { - const client = make_rfb('wss://host:8675', { shared: true }); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); + const client = makeRFB('wss://host:8675', { shared: true }); + client._rfbConnectionState = 'connecting'; + client._rfbInitState = 'SecurityResult'; + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); expect(client._sock).to.have.sent(new Uint8Array([1])); }); it('should send 0 if we are not in shared mode', function () { - const client = make_rfb('wss://host:8675', { shared: false }); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); + const client = makeRFB('wss://host:8675', { shared: false }); + client._rfbConnectionState = 'connecting'; + client._rfbInitState = 'SecurityResult'; + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); expect(client._sock).to.have.sent(new Uint8Array([0])); }); }); describe('ServerInitialisation', function () { beforeEach(function () { - client._rfb_init_state = 'ServerInitialisation'; + client._rfbInitState = 'ServerInitialisation'; }); - function send_server_init(opts, client) { - const full_opts = { width: 10, height: 12, bpp: 24, depth: 24, big_endian: 0, - true_color: 1, red_max: 255, green_max: 255, blue_max: 255, - red_shift: 16, green_shift: 8, blue_shift: 0, name: 'a name' }; + function sendServerInit(opts, client) { + const fullOpts = { width: 10, height: 12, bpp: 24, depth: 24, bigEndian: 0, + trueColor: 1, redMax: 255, greenMax: 255, blueMax: 255, + redShift: 16, greenShift: 8, blueShift: 0, name: 'a name' }; for (let opt in opts) { - full_opts[opt] = opts[opt]; + fullOpts[opt] = opts[opt]; } const data = []; - push16(data, full_opts.width); - push16(data, full_opts.height); + push16(data, fullOpts.width); + push16(data, fullOpts.height); - data.push(full_opts.bpp); - data.push(full_opts.depth); - data.push(full_opts.big_endian); - data.push(full_opts.true_color); + data.push(fullOpts.bpp); + data.push(fullOpts.depth); + data.push(fullOpts.bigEndian); + data.push(fullOpts.trueColor); - push16(data, full_opts.red_max); - push16(data, full_opts.green_max); - push16(data, full_opts.blue_max); - push8(data, full_opts.red_shift); - push8(data, full_opts.green_shift); - push8(data, full_opts.blue_shift); + push16(data, fullOpts.redMax); + push16(data, fullOpts.greenMax); + push16(data, fullOpts.blueMax); + push8(data, fullOpts.redShift); + push8(data, fullOpts.greenShift); + push8(data, fullOpts.blueShift); // padding push8(data, 0); push8(data, 0); push8(data, 0); - client._sock._websocket._receive_data(new Uint8Array(data)); + client._sock._websocket._receiveData(new Uint8Array(data)); - const name_data = []; - push32(name_data, full_opts.name.length); - for (let i = 0; i < full_opts.name.length; i++) { - name_data.push(full_opts.name.charCodeAt(i)); - } - client._sock._websocket._receive_data(new Uint8Array(name_data)); + const nameData = []; + let nameLen = []; + pushString(nameData, fullOpts.name); + push32(nameLen, nameData.length); + + client._sock._websocket._receiveData(new Uint8Array(nameLen)); + client._sock._websocket._receiveData(new Uint8Array(nameData)); } it('should set the framebuffer width and height', function () { - send_server_init({ width: 32, height: 84 }, client); - expect(client._fb_width).to.equal(32); - expect(client._fb_height).to.equal(84); + sendServerInit({ width: 32, height: 84 }, client); + expect(client._fbWidth).to.equal(32); + expect(client._fbHeight).to.equal(84); }); // NB(sross): we just warn, not fail, for endian-ness and shifts, so we don't test them @@ -1464,46 +1545,44 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should set the framebuffer name and call the callback', function () { const spy = sinon.spy(); client.addEventListener("desktopname", spy); - send_server_init({ name: 'some name' }, client); + sendServerInit({ name: 'som€ nam€' }, client); - expect(client._fb_name).to.equal('some name'); + expect(client._fbName).to.equal('som€ nam€'); expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.name).to.equal('some name'); + expect(spy.args[0][0].detail.name).to.equal('som€ nam€'); }); it('should handle the extended init message of the tight encoding', function () { // NB(sross): we don't actually do anything with it, so just test that we can // read it w/o throwing an error - client._rfb_tightvnc = true; - send_server_init({}, client); - - const tight_data = []; - push16(tight_data, 1); - push16(tight_data, 2); - push16(tight_data, 3); - push16(tight_data, 0); + client._rfbTightVNC = true; + sendServerInit({}, client); + + const tightData = []; + push16(tightData, 1); + push16(tightData, 2); + push16(tightData, 3); + push16(tightData, 0); for (let i = 0; i < 16 + 32 + 48; i++) { - tight_data.push(i); + tightData.push(i); } - client._sock._websocket._receive_data(new Uint8Array(tight_data)); + client._sock._websocket._receiveData(new Uint8Array(tightData)); - expect(client._rfb_connection_state).to.equal('connected'); + expect(client._rfbConnectionState).to.equal('connected'); }); it('should resize the display', function () { sinon.spy(client._display, 'resize'); - send_server_init({ width: 27, height: 32 }, client); + sendServerInit({ width: 27, height: 32 }, client); expect(client._display.resize).to.have.been.calledOnce; expect(client._display.resize).to.have.been.calledWith(27, 32); }); - it('should grab the mouse and keyboard', function () { + it('should grab the keyboard', function () { sinon.spy(client._keyboard, 'grab'); - sinon.spy(client._mouse, 'grab'); - send_server_init({}, client); + sendServerInit({}, client); expect(client._keyboard.grab).to.have.been.calledOnce; - expect(client._mouse.grab).to.have.been.calledOnce; }); describe('Initial Update Request', function () { @@ -1521,7 +1600,7 @@ describe('Remote Frame Buffer Protocol Client', function () { // TODO(directxman12): test the various options in this configuration matrix it('should reply with the pixel format, client encodings, and initial update request', function () { - send_server_init({ width: 27, height: 32 }, client); + sendServerInit({ width: 27, height: 32 }, client); expect(RFB.messages.pixelFormat).to.have.been.calledOnce; expect(RFB.messages.pixelFormat).to.have.been.calledWith(client._sock, 24, true); @@ -1534,7 +1613,7 @@ describe('Remote Frame Buffer Protocol Client', function () { }); it('should reply with restricted settings for Intel AMT servers', function () { - send_server_init({ width: 27, height: 32, name: "Intel(r) AMT KVM"}, client); + sendServerInit({ width: 27, height: 32, name: "Intel(r) AMT KVM"}, client); expect(RFB.messages.pixelFormat).to.have.been.calledOnce; expect(RFB.messages.pixelFormat).to.have.been.calledWith(client._sock, 8, true); @@ -1549,8 +1628,8 @@ describe('Remote Frame Buffer Protocol Client', function () { }); it('should transition to the "connected" state', function () { - send_server_init({}, client); - expect(client._rfb_connection_state).to.equal('connected'); + sendServerInit({}, client); + expect(client._rfbConnectionState).to.equal('connected'); }); }); }); @@ -1559,125 +1638,125 @@ describe('Remote Frame Buffer Protocol Client', function () { let client; beforeEach(function () { - client = make_rfb(); - client._fb_name = 'some device'; - client._fb_width = 640; - client._fb_height = 20; + client = makeRFB(); + client._fbName = 'some device'; + client._fbWidth = 640; + client._fbHeight = 20; }); describe('Framebuffer Update Handling', function () { - const target_data_arr = [ + const targetDataArr = [ 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255, 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255 ]; - let target_data; + let targetData; - const target_data_check_arr = [ + const targetDataCheckArr = [ 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 ]; - let target_data_check; + let targetDataCheck; before(function () { // NB(directxman12): PhantomJS 1.x doesn't implement Uint8ClampedArray - target_data = new Uint8Array(target_data_arr); - target_data_check = new Uint8Array(target_data_check_arr); + targetData = new Uint8Array(targetDataArr); + targetDataCheck = new Uint8Array(targetDataCheckArr); }); - function send_fbu_msg(rect_info, rect_data, client, rect_cnt) { + function sendFbuMsg(rectInfo, rectData, client, rectCnt) { let data = []; - if (!rect_cnt || rect_cnt > -1) { + if (!rectCnt || rectCnt > -1) { // header data.push(0); // msg type data.push(0); // padding - push16(data, rect_cnt || rect_data.length); + push16(data, rectCnt || rectData.length); } - for (let i = 0; i < rect_data.length; i++) { - if (rect_info[i]) { - push16(data, rect_info[i].x); - push16(data, rect_info[i].y); - push16(data, rect_info[i].width); - push16(data, rect_info[i].height); - push32(data, rect_info[i].encoding); + for (let i = 0; i < rectData.length; i++) { + if (rectInfo[i]) { + push16(data, rectInfo[i].x); + push16(data, rectInfo[i].y); + push16(data, rectInfo[i].width); + push16(data, rectInfo[i].height); + push32(data, rectInfo[i].encoding); } - data = data.concat(rect_data[i]); + data = data.concat(rectData[i]); } - client._sock._websocket._receive_data(new Uint8Array(data)); + client._sock._websocket._receiveData(new Uint8Array(data)); } it('should send an update request if there is sufficient data', function () { - const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; - RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); + const expectedMsg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; + RFB.messages.fbUpdateRequest(expectedMsg, true, 0, 0, 640, 20); client._framebufferUpdate = () => true; - client._sock._websocket._receive_data(new Uint8Array([0])); + client._sock._websocket._receiveData(new Uint8Array([0])); - expect(client._sock).to.have.sent(expected_msg._sQ); + expect(client._sock).to.have.sent(expectedMsg._sQ); }); it('should not send an update request if we need more data', function () { - client._sock._websocket._receive_data(new Uint8Array([0])); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); + client._sock._websocket._receiveData(new Uint8Array([0])); + expect(client._sock._websocket._getSentData()).to.have.length(0); }); it('should resume receiving an update if we previously did not have enough data', function () { - const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; - RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); + const expectedMsg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; + RFB.messages.fbUpdateRequest(expectedMsg, true, 0, 0, 640, 20); // just enough to set FBU.rects - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 3])); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 3])); + expect(client._sock._websocket._getSentData()).to.have.length(0); client._framebufferUpdate = function () { this._sock.rQskipBytes(1); return true; }; // we magically have enough data // 247 should *not* be used as the message type here - client._sock._websocket._receive_data(new Uint8Array([247])); - expect(client._sock).to.have.sent(expected_msg._sQ); + client._sock._websocket._receiveData(new Uint8Array([247])); + expect(client._sock).to.have.sent(expectedMsg._sQ); }); it('should not send a request in continuous updates mode', function () { client._enabledContinuousUpdates = true; client._framebufferUpdate = () => true; - client._sock._websocket._receive_data(new Uint8Array([0])); + client._sock._websocket._receiveData(new Uint8Array([0])); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); + expect(client._sock._websocket._getSentData()).to.have.length(0); }); it('should fail on an unsupported encoding', function () { sinon.spy(client, "_fail"); - const rect_info = { x: 8, y: 11, width: 27, height: 32, encoding: 234 }; - send_fbu_msg([rect_info], [[]], client); + const rectInfo = { x: 8, y: 11, width: 27, height: 32, encoding: 234 }; + sendFbuMsg([rectInfo], [[]], client); expect(client._fail).to.have.been.calledOnce; }); it('should be able to pause and resume receiving rects if not enought data', function () { // seed some initial data to copy - client._fb_width = 4; - client._fb_height = 4; + client._fbWidth = 4; + client._fbHeight = 4; client._display.resize(4, 4); - client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(target_data_check_arr.slice(0, 32)), 0); + client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(targetDataCheckArr.slice(0, 32)), 0); const info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, { x: 2, y: 2, width: 2, height: 2, encoding: 0x01}]; // data says [{ old_x: 2, old_y: 0 }, { old_x: 0, old_y: 0 }] const rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; - send_fbu_msg([info[0]], [rects[0]], client, 2); - send_fbu_msg([info[1]], [rects[1]], client, -1); - expect(client._display).to.have.displayed(target_data_check); + sendFbuMsg([info[0]], [rects[0]], client, 2); + sendFbuMsg([info[1]], [rects[1]], client, -1); + expect(client._display).to.have.displayed(targetDataCheck); }); describe('Message Encoding Handlers', function () { beforeEach(function () { // a really small frame - client._fb_width = 4; - client._fb_height = 4; - client._fb_depth = 24; + client._fbWidth = 4; + client._fbHeight = 4; + client._fbDepth = 24; client._display.resize(4, 4); }); @@ -1692,8 +1771,8 @@ describe('Remote Frame Buffer Protocol Client', function () { [0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0], [0xff, 0x00, 0xee, 0, 0xff, 0xee, 0x00, 0, 0xff, 0xee, 0xaa, 0, 0xff, 0xee, 0xab, 0], [0xff, 0x00, 0xee, 0, 0xff, 0xee, 0x00, 0, 0xff, 0xee, 0xaa, 0, 0xff, 0xee, 0xab, 0]]; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data); + sendFbuMsg(info, rects, client); + expect(client._display).to.have.displayed(targetData); }); it('should handle the RAW encoding in low colour mode', function () { @@ -1706,21 +1785,21 @@ describe('Remote Frame Buffer Protocol Client', function () { [0x0c, 0x0c, 0x0c, 0x0c], [0x0c, 0x0c, 0x03, 0x03], [0x0c, 0x0c, 0x03, 0x03]]; - client._fb_depth = 8; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data_check); + client._fbDepth = 8; + sendFbuMsg(info, rects, client); + expect(client._display).to.have.displayed(targetDataCheck); }); it('should handle the COPYRECT encoding', function () { // seed some initial data to copy - client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(target_data_check_arr.slice(0, 32)), 0); + client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(targetDataCheckArr.slice(0, 32)), 0); const info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, { x: 2, y: 2, width: 2, height: 2, encoding: 0x01}]; // data says [{ old_x: 0, old_y: 0 }, { old_x: 0, old_y: 0 }] const rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data_check); + sendFbuMsg(info, rects, client); + expect(client._display).to.have.displayed(targetDataCheck); }); // TODO(directxman12): for encodings with subrects, test resuming on partial send? @@ -1747,9 +1826,8 @@ describe('Remote Frame Buffer Protocol Client', function () { push16(rect, 2); // y: 2 push16(rect, 2); // width: 2 push16(rect, 2); // height: 2 - - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); + sendFbuMsg(info, [rect], client); + expect(client._display).to.have.displayed(targetDataCheck); }); describe('the HEXTILE encoding handler', function () { @@ -1767,22 +1845,22 @@ describe('Remote Frame Buffer Protocol Client', function () { rect.push(1 | (1 << 4)); // width: 2, height: 2 rect.push(2 | (2 << 4)); // x: 2, y: 2 rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); + sendFbuMsg(info, [rect], client); + expect(client._display).to.have.displayed(targetDataCheck); }); it('should handle a raw tile', function () { const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; const rect = []; rect.push(0x01); // raw - for (let i = 0; i < target_data.length; i += 4) { - rect.push(target_data[i + 2]); - rect.push(target_data[i + 1]); - rect.push(target_data[i]); - rect.push(target_data[i + 3]); + for (let i = 0; i < targetData.length; i += 4) { + rect.push(targetData[i + 2]); + rect.push(targetData[i + 1]); + rect.push(targetData[i]); + rect.push(targetData[i + 3]); } - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data); + sendFbuMsg(info, [rect], client); + expect(client._display).to.have.displayed(targetData); }); it('should handle a tile with only bg specified (solid bg)', function () { @@ -1790,7 +1868,7 @@ describe('Remote Frame Buffer Protocol Client', function () { const rect = []; rect.push(0x02); push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - send_fbu_msg(info, [rect], client); + sendFbuMsg(info, [rect], client); const expected = []; for (let i = 0; i < 16; i++) { push32(expected, 0xff00ff); } @@ -1799,7 +1877,7 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should handle a tile with only bg specified and an empty frame afterwards', function () { // set the width so we can have two tiles - client._fb_width = 8; + client._fbWidth = 8; client._display.resize(8, 4); const info = [{ x: 0, y: 0, width: 32, height: 4, encoding: 0x05 }]; @@ -1813,7 +1891,7 @@ describe('Remote Frame Buffer Protocol Client', function () { // send an empty frame rect.push(0x00); - send_fbu_msg(info, [rect], client); + sendFbuMsg(info, [rect], client); const expected = []; for (let i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 1: solid @@ -1839,13 +1917,13 @@ describe('Remote Frame Buffer Protocol Client', function () { rect.push(0xff); rect.push(2 | (2 << 4)); // x: 2, y: 2 rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); + sendFbuMsg(info, [rect], client); + expect(client._display).to.have.displayed(targetDataCheck); }); it('should carry over fg and bg colors from the previous tile if not specified', function () { - client._fb_width = 4; - client._fb_height = 17; + client._fbWidth = 4; + client._fbHeight = 17; client._display.resize(4, 17); const info = [{ x: 0, y: 0, width: 4, height: 17, encoding: 0x05}]; @@ -1867,11 +1945,11 @@ describe('Remote Frame Buffer Protocol Client', function () { rect.push(1); // 1 subrect rect.push(0); // x: 0, y: 0 rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); + sendFbuMsg(info, [rect], client); let expected = []; - for (let i = 0; i < 4; i++) { expected = expected.concat(target_data_check_arr); } - expected = expected.concat(target_data_check_arr.slice(0, 16)); + for (let i = 0; i < 4; i++) { expected = expected.concat(targetDataCheckArr); } + expected = expected.concat(targetDataCheckArr.slice(0, 16)); expect(client._display).to.have.displayed(new Uint8Array(expected)); }); @@ -1879,7 +1957,7 @@ describe('Remote Frame Buffer Protocol Client', function () { sinon.spy(client, "_fail"); const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; const rects = [[45]]; // an invalid subencoding - send_fbu_msg(info, rects, client); + sendFbuMsg(info, rects, client); expect(client._fail).to.have.been.calledOnce; }); }); @@ -1894,10 +1972,10 @@ describe('Remote Frame Buffer Protocol Client', function () { it('should handle the DesktopSize pseduo-encoding', function () { sinon.spy(client._display, 'resize'); - send_fbu_msg([{ x: 0, y: 0, width: 20, height: 50, encoding: -223 }], [[]], client); + sendFbuMsg([{ x: 0, y: 0, width: 20, height: 50, encoding: -223 }], [[]], client); - expect(client._fb_width).to.equal(20); - expect(client._fb_height).to.equal(50); + expect(client._fbWidth).to.equal(20); + expect(client._fbHeight).to.equal(50); expect(client._display.resize).to.have.been.calledOnce; expect(client._display.resize).to.have.been.calledWith(20, 50); @@ -1906,18 +1984,18 @@ describe('Remote Frame Buffer Protocol Client', function () { describe('the ExtendedDesktopSize pseudo-encoding handler', function () { beforeEach(function () { // a really small frame - client._fb_width = 4; - client._fb_height = 4; + client._fbWidth = 4; + client._fbHeight = 4; client._display.resize(4, 4); sinon.spy(client._display, 'resize'); }); - function make_screen_data(nr_of_screens) { + function makeScreenData(nrOfScreens) { const data = []; - push8(data, nr_of_screens); // number-of-screens + push8(data, nrOfScreens); // number-of-screens push8(data, 0); // padding push16(data, 0); // padding - for (let i=0; i {}}; - const incoming_msg = {_sQ: new Uint8Array(16), _sQlen: 0, flush: () => {}}; + const expectedMsg = {_sQ: new Uint8Array(16), _sQlen: 0, flush: () => {}}; + const incomingMsg = {_sQ: new Uint8Array(16), _sQlen: 0, flush: () => {}}; const payload = "foo\x00ab9"; // ClientFence and ServerFence are identical in structure - RFB.messages.clientFence(expected_msg, (1<<0) | (1<<1), payload); - RFB.messages.clientFence(incoming_msg, 0xffffffff, payload); + RFB.messages.clientFence(expectedMsg, (1<<0) | (1<<1), payload); + RFB.messages.clientFence(incomingMsg, 0xffffffff, payload); - client._sock._websocket._receive_data(incoming_msg._sQ); + client._sock._websocket._receiveData(incomingMsg._sQ); - expect(client._sock).to.have.sent(expected_msg._sQ); + expect(client._sock).to.have.sent(expectedMsg._sQ); - expected_msg._sQlen = 0; - incoming_msg._sQlen = 0; + expectedMsg._sQlen = 0; + incomingMsg._sQlen = 0; - RFB.messages.clientFence(expected_msg, (1<<0), payload); - RFB.messages.clientFence(incoming_msg, (1<<0) | (1<<31), payload); + RFB.messages.clientFence(expectedMsg, (1<<0), payload); + RFB.messages.clientFence(incomingMsg, (1<<0) | (1<<31), payload); - client._sock._websocket._receive_data(incoming_msg._sQ); + client._sock._websocket._receiveData(incomingMsg._sQ); - expect(client._sock).to.have.sent(expected_msg._sQ); + expect(client._sock).to.have.sent(expectedMsg._sQ); }); it('should enable continuous updates on first EndOfContinousUpdates', function () { - const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; + const expectedMsg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; - RFB.messages.enableContinuousUpdates(expected_msg, true, 0, 0, 640, 20); + RFB.messages.enableContinuousUpdates(expectedMsg, true, 0, 0, 640, 20); expect(client._enabledContinuousUpdates).to.be.false; - client._sock._websocket._receive_data(new Uint8Array([150])); + client._sock._websocket._receiveData(new Uint8Array([150])); expect(client._enabledContinuousUpdates).to.be.true; - expect(client._sock).to.have.sent(expected_msg._sQ); + expect(client._sock).to.have.sent(expectedMsg._sQ); }); it('should disable continuous updates on subsequent EndOfContinousUpdates', function () { client._enabledContinuousUpdates = true; client._supportsContinuousUpdates = true; - client._sock._websocket._receive_data(new Uint8Array([150])); + client._sock._websocket._receiveData(new Uint8Array([150])); expect(client._enabledContinuousUpdates).to.be.false; }); it('should update continuous updates on resize', function () { - const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; - RFB.messages.enableContinuousUpdates(expected_msg, true, 0, 0, 90, 700); + const expectedMsg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: () => {}}; + RFB.messages.enableContinuousUpdates(expectedMsg, true, 0, 0, 90, 700); client._resize(450, 160); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); + expect(client._sock._websocket._getSentData()).to.have.length(0); client._enabledContinuousUpdates = true; client._resize(90, 700); - expect(client._sock).to.have.sent(expected_msg._sQ); + expect(client._sock).to.have.sent(expectedMsg._sQ); }); it('should fail on an unknown message type', function () { sinon.spy(client, "_fail"); - client._sock._websocket._receive_data(new Uint8Array([87])); + client._sock._websocket._receiveData(new Uint8Array([87])); expect(client._fail).to.have.been.calledOnce; }); }); describe('Asynchronous Events', function () { let client; + let pointerEvent; + let keyEvent; + let qemuKeyEvent; + beforeEach(function () { - client = make_rfb(); + client = makeRFB(); + client._display.resize(100, 100); + + // We need to disable this as focusing the canvas will + // cause the browser to scoll to it, messing up our + // client coordinate calculations + client.focusOnClick = false; + + pointerEvent = sinon.spy(RFB.messages, 'pointerEvent'); + keyEvent = sinon.spy(RFB.messages, 'keyEvent'); + qemuKeyEvent = sinon.spy(RFB.messages, 'QEMUExtendedKeyEvent'); + }); + + afterEach(function () { + pointerEvent.restore(); + keyEvent.restore(); + qemuKeyEvent.restore(); }); - describe('Mouse event handlers', function () { + function elementToClient(x, y) { + let res = { x: 0, y: 0 }; + + let bounds = client._canvas.getBoundingClientRect(); + + /* + * If the canvas is on a fractional position we will calculate + * a fractional mouse position. But that gets truncated when we + * send the event, AND the same thing happens in RFB when it + * generates the PointerEvent message. To compensate for that + * fact we round the value upwards here. + */ + res.x = Math.ceil(bounds.left + x); + res.y = Math.ceil(bounds.top + y); + + return res; + } + + describe('Mouse Events', function () { + function sendMouseMoveEvent(x, y) { + let pos = elementToClient(x, y); + let ev; + + try { + ev = new MouseEvent('mousemove', + { 'screenX': pos.x + window.screenX, + 'screenY': pos.y + window.screenY, + 'clientX': pos.x, + 'clientY': pos.y }); + } catch (e) { + ev = document.createEvent('MouseEvent'); + ev.initMouseEvent('mousemove', + true, true, window, 0, + pos.x + window.screenX, + pos.y + window.screenY, + pos.x, pos.y, + false, false, false, false, + 0, null); + } + + client._canvas.dispatchEvent(ev); + } + + function sendMouseButtonEvent(x, y, down, button) { + let pos = elementToClient(x, y); + let ev; + + try { + ev = new MouseEvent(down ? 'mousedown' : 'mouseup', + { 'screenX': pos.x + window.screenX, + 'screenY': pos.y + window.screenY, + 'clientX': pos.x, + 'clientY': pos.y, + 'button': button, + 'buttons': 1 << button }); + } catch (e) { + ev = document.createEvent('MouseEvent'); + ev.initMouseEvent(down ? 'mousedown' : 'mouseup', + true, true, window, 0, + pos.x + window.screenX, + pos.y + window.screenY, + pos.x, pos.y, + false, false, false, false, + button, null); + } + + client._canvas.dispatchEvent(ev); + } + it('should not send button messages in view-only mode', function () { client._viewOnly = true; - sinon.spy(client._sock, 'flush'); - client._handleMouseButton(0, 0, 1, 0x001); - expect(client._sock.flush).to.not.have.been.called; + sendMouseButtonEvent(10, 10, true, 0); + clock.tick(50); + expect(pointerEvent).to.not.have.been.called; }); it('should not send movement messages in view-only mode', function () { client._viewOnly = true; - sinon.spy(client._sock, 'flush'); - client._handleMouseMove(0, 0); - expect(client._sock.flush).to.not.have.been.called; + sendMouseMoveEvent(10, 10); + clock.tick(50); + expect(pointerEvent).to.not.have.been.called; }); - it('should send a pointer event on mouse button presses', function () { - client._handleMouseButton(10, 12, 1, 0x001); - const pointer_msg = {_sQ: new Uint8Array(6), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x001); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); + it('should handle left mouse button', function () { + sendMouseButtonEvent(10, 10, true, 0); - it('should send a mask of 1 on mousedown', function () { - client._handleMouseButton(10, 12, 1, 0x001); - const pointer_msg = {_sQ: new Uint8Array(6), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x001); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 10, 10, 0x1); + pointerEvent.resetHistory(); - it('should send a mask of 0 on mouseup', function () { - client._mouse_buttonMask = 0x001; - client._handleMouseButton(10, 12, 0, 0x001); - const pointer_msg = {_sQ: new Uint8Array(6), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x000); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); + sendMouseButtonEvent(10, 10, false, 0); - it('should send a pointer event on mouse movement', function () { - client._handleMouseMove(10, 12); - const pointer_msg = {_sQ: new Uint8Array(6), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x000); - expect(client._sock).to.have.sent(pointer_msg._sQ); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 10, 10, 0x0); }); - it('should set the button mask so that future mouse movements use it', function () { - client._handleMouseButton(10, 12, 1, 0x010); - client._handleMouseMove(13, 9); - const pointer_msg = {_sQ: new Uint8Array(12), _sQlen: 0, flush: () => {}}; - RFB.messages.pointerEvent(pointer_msg, 10, 12, 0x010); - RFB.messages.pointerEvent(pointer_msg, 13, 9, 0x010); - expect(client._sock).to.have.sent(pointer_msg._sQ); - }); - }); + it('should handle middle mouse button', function () { + sendMouseButtonEvent(10, 10, true, 1); - describe('Keyboard Event Handlers', function () { - it('should send a key message on a key press', function () { - client._handleKeyEvent(0x41, 'KeyA', true); - const key_msg = {_sQ: new Uint8Array(8), _sQlen: 0, flush: () => {}}; - RFB.messages.keyEvent(key_msg, 0x41, 1); - expect(client._sock).to.have.sent(key_msg._sQ); - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 10, 10, 0x2); + pointerEvent.resetHistory(); - it('should not send messages in view-only mode', function () { - client._viewOnly = true; - sinon.spy(client._sock, 'flush'); - client._handleKeyEvent('a', 'KeyA', true); - expect(client._sock.flush).to.not.have.been.called; - }); - }); + sendMouseButtonEvent(10, 10, false, 1); - describe('WebSocket event handlers', function () { - // message events - it('should do nothing if we receive an empty message and have nothing in the queue', function () { - client._normal_msg = sinon.spy(); - client._sock._websocket._receive_data(new Uint8Array([])); - expect(client._normal_msg).to.not.have.been.called; + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 10, 10, 0x0); }); - it('should handle a message in the connected state as a normal message', function () { - client._normal_msg = sinon.spy(); - client._sock._websocket._receive_data(new Uint8Array([1, 2, 3])); - expect(client._normal_msg).to.have.been.called; - }); + it('should handle right mouse button', function () { + sendMouseButtonEvent(10, 10, true, 2); - it('should handle a message in any non-disconnected/failed state like an init message', function () { - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'ProtocolVersion'; - client._init_msg = sinon.spy(); - client._sock._websocket._receive_data(new Uint8Array([1, 2, 3])); - expect(client._init_msg).to.have.been.called; - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 10, 10, 0x4); + pointerEvent.resetHistory(); - it('should process all normal messages directly', function () { - const spy = sinon.spy(); - client.addEventListener("bell", spy); - client._sock._websocket._receive_data(new Uint8Array([0x02, 0x02])); - expect(spy).to.have.been.calledTwice; - }); + sendMouseButtonEvent(10, 10, false, 2); - // open events - it('should update the state to ProtocolVersion on open (if the state is "connecting")', function () { - client = new RFB(document.createElement('div'), 'wss://host:8675'); - this.clock.tick(); - client._sock._websocket._open(); - expect(client._rfb_init_state).to.equal('ProtocolVersion'); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 10, 10, 0x0); }); - it('should fail if we are not currently ready to connect and we get an "open" event', function () { - sinon.spy(client, "_fail"); - client._rfb_connection_state = 'connected'; - client._sock._websocket._open(); - expect(client._fail).to.have.been.calledOnce; - }); + it('should handle multiple mouse buttons', function () { + sendMouseButtonEvent(10, 10, true, 0); + sendMouseButtonEvent(10, 10, true, 2); - // close events - it('should transition to "disconnected" from "disconnecting" on a close event', function () { - const real = client._sock._websocket.close; - client._sock._websocket.close = () => {}; - client.disconnect(); - expect(client._rfb_connection_state).to.equal('disconnecting'); - client._sock._websocket.close = real; - client._sock._websocket.close(); - expect(client._rfb_connection_state).to.equal('disconnected'); + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 0x1); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0x5); + + pointerEvent.resetHistory(); + + sendMouseButtonEvent(10, 10, false, 0); + sendMouseButtonEvent(10, 10, false, 2); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 0x4); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0x0); }); - it('should fail if we get a close event while connecting', function () { - sinon.spy(client, "_fail"); - client._rfb_connection_state = 'connecting'; - client._sock._websocket.close(); - expect(client._fail).to.have.been.calledOnce; + it('should handle mouse movement', function () { + sendMouseMoveEvent(50, 70); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 50, 70, 0x0); }); - it('should unregister close event handler', function () { - sinon.spy(client._sock, 'off'); - client.disconnect(); - client._sock._websocket.close(); - expect(client._sock.off).to.have.been.calledWith('close'); + it('should handle click and drag', function () { + sendMouseButtonEvent(10, 10, true, 0); + sendMouseMoveEvent(50, 70); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 0x1); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 50, 70, 0x1); + + pointerEvent.resetHistory(); + + sendMouseButtonEvent(50, 70, false, 0); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 50, 70, 0x0); }); - // error events do nothing + describe('Event Aggregation', function () { + it('should send a single pointer event on mouse movement', function () { + sendMouseMoveEvent(50, 70); + clock.tick(100); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 50, 70, 0x0); + }); + + it('should delay one move if two events are too close', function () { + sendMouseMoveEvent(18, 30); + sendMouseMoveEvent(20, 50); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 18, 30, 0x0); + pointerEvent.resetHistory(); + + clock.tick(100); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 50, 0x0); + }); + + it('should only send first and last move of many close events', function () { + sendMouseMoveEvent(18, 30); + sendMouseMoveEvent(20, 50); + sendMouseMoveEvent(21, 55); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 18, 30, 0x0); + pointerEvent.resetHistory(); + + clock.tick(100); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 21, 55, 0x0); + }); + + // We selected the 17ms since that is ~60 FPS + it('should send move events every 17 ms', function () { + sendMouseMoveEvent(1, 10); // instant send + clock.tick(10); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 1, 10, 0x0); + pointerEvent.resetHistory(); + + sendMouseMoveEvent(2, 20); // delayed + clock.tick(10); // timeout send + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 2, 20, 0x0); + pointerEvent.resetHistory(); + + sendMouseMoveEvent(3, 30); // delayed + clock.tick(10); + sendMouseMoveEvent(4, 40); // delayed + clock.tick(10); // timeout send + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 4, 40, 0x0); + pointerEvent.resetHistory(); + + sendMouseMoveEvent(5, 50); // delayed + + expect(pointerEvent).to.not.have.been.called; + }); + + it('should send waiting move events before a button press', function () { + sendMouseMoveEvent(13, 9); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 13, 9, 0x0); + pointerEvent.resetHistory(); + + sendMouseMoveEvent(20, 70); + + expect(pointerEvent).to.not.have.been.called; + + sendMouseButtonEvent(20, 70, true, 0); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 70, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 70, 0x1); + }); + + it('should send move events with enough time apart normally', function () { + sendMouseMoveEvent(58, 60); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 58, 60, 0x0); + pointerEvent.resetHistory(); + + clock.tick(20); + + sendMouseMoveEvent(25, 60); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 25, 60, 0x0); + pointerEvent.resetHistory(); + }); + + it('should not send waiting move events if disconnected', function () { + sendMouseMoveEvent(88, 99); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 88, 99, 0x0); + pointerEvent.resetHistory(); + + sendMouseMoveEvent(66, 77); + client.disconnect(); + clock.tick(20); + + expect(pointerEvent).to.not.have.been.called; + }); + }); + + it.skip('should block click events', function () { + /* FIXME */ + }); + + it.skip('should block contextmenu events', function () { + /* FIXME */ + }); + }); + + describe('Wheel Events', function () { + function sendWheelEvent(x, y, dx, dy, mode=0) { + let pos = elementToClient(x, y); + let ev; + + try { + ev = new WheelEvent('wheel', + { 'screenX': pos.x + window.screenX, + 'screenY': pos.y + window.screenY, + 'clientX': pos.x, + 'clientY': pos.y, + 'deltaX': dx, + 'deltaY': dy, + 'deltaMode': mode }); + } catch (e) { + ev = document.createEvent('WheelEvent'); + ev.initWheelEvent('wheel', true, true, window, 0, + pos.x + window.screenX, + pos.y + window.screenY, + pos.x, pos.y, + 0, null, "", + dx, dy, 0, mode); + } + + client._canvas.dispatchEvent(ev); + } + + it('should handle wheel up event', function () { + sendWheelEvent(10, 10, 0, -50); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 1<<3); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0); + }); + + it('should handle wheel down event', function () { + sendWheelEvent(10, 10, 0, 50); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 1<<4); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0); + }); + + it('should handle wheel left event', function () { + sendWheelEvent(10, 10, -50, 0); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 1<<5); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0); + }); + + it('should handle wheel right event', function () { + sendWheelEvent(10, 10, 50, 0); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 1<<6); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0); + }); + + it('should ignore wheel when in view only', function () { + client._viewOnly = true; + + sendWheelEvent(10, 10, 50, 0); + + expect(pointerEvent).to.not.have.been.called; + }); + + it('should accumulate wheel events if small enough', function () { + sendWheelEvent(10, 10, 0, 20); + sendWheelEvent(10, 10, 0, 20); + + expect(pointerEvent).to.not.have.been.called; + + sendWheelEvent(10, 10, 0, 20); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 1<<4); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0); + }); + + it('should not accumulate large wheel events', function () { + sendWheelEvent(10, 10, 0, 400); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 1<<4); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0); + }); + + it('should handle line based wheel event', function () { + sendWheelEvent(10, 10, 0, 3, 1); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 1<<4); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0); + }); + + it('should handle page based wheel event', function () { + sendWheelEvent(10, 10, 0, 3, 2); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 10, 1<<4); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 10, 0); + }); + }); + + describe('Keyboard Events', function () { + it('should send a key message on a key press', function () { + client._handleKeyEvent(0x41, 'KeyA', true); + const keyMsg = {_sQ: new Uint8Array(8), _sQlen: 0, flush: () => {}}; + RFB.messages.keyEvent(keyMsg, 0x41, 1); + expect(client._sock).to.have.sent(keyMsg._sQ); + }); + + it('should not send messages in view-only mode', function () { + client._viewOnly = true; + sinon.spy(client._sock, 'flush'); + client._handleKeyEvent('a', 'KeyA', true); + expect(client._sock.flush).to.not.have.been.called; + }); + }); + + describe('Gesture event handlers', function () { + beforeEach(function () { + // Touch events and gestures are not supported on IE + if (browser.isIE()) { + this.skip(); + return; + } + }); + + function gestureStart(gestureType, x, y, + magnitudeX = 0, magnitudeY = 0) { + let pos = elementToClient(x, y); + let detail = {type: gestureType, clientX: pos.x, clientY: pos.y}; + + detail.magnitudeX = magnitudeX; + detail.magnitudeY = magnitudeY; + + let ev = new CustomEvent('gesturestart', { detail: detail }); + client._canvas.dispatchEvent(ev); + } + + function gestureMove(gestureType, x, y, + magnitudeX = 0, magnitudeY = 0) { + let pos = elementToClient(x, y); + let detail = {type: gestureType, clientX: pos.x, clientY: pos.y}; + + detail.magnitudeX = magnitudeX; + detail.magnitudeY = magnitudeY; + + let ev = new CustomEvent('gesturemove', { detail: detail }); + client._canvas.dispatchEvent(ev); + } + + function gestureEnd(gestureType, x, y) { + let pos = elementToClient(x, y); + let detail = {type: gestureType, clientX: pos.x, clientY: pos.y}; + let ev = new CustomEvent('gestureend', { detail: detail }); + client._canvas.dispatchEvent(ev); + } + + describe('Gesture onetap', function () { + it('should handle onetap events', function () { + let bmask = 0x1; + + gestureStart('onetap', 20, 40); + gestureEnd('onetap', 20, 40); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should keep same position for multiple onetap events', function () { + let bmask = 0x1; + + gestureStart('onetap', 20, 40); + gestureEnd('onetap', 20, 40); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureStart('onetap', 20, 50); + gestureEnd('onetap', 20, 50); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureStart('onetap', 30, 50); + gestureEnd('onetap', 30, 50); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should not keep same position for onetap events when too far apart', function () { + let bmask = 0x1; + + gestureStart('onetap', 20, 40); + gestureEnd('onetap', 20, 40); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureStart('onetap', 80, 95); + gestureEnd('onetap', 80, 95); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 80, 95, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 80, 95, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 80, 95, 0x0); + }); + + it('should not keep same position for onetap events when enough time inbetween', function () { + let bmask = 0x1; + + gestureStart('onetap', 10, 20); + gestureEnd('onetap', 10, 20); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 20, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 20, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 10, 20, 0x0); + + pointerEvent.resetHistory(); + this.clock.tick(1500); + + gestureStart('onetap', 15, 20); + gestureEnd('onetap', 15, 20); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 15, 20, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 15, 20, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 15, 20, 0x0); + + pointerEvent.resetHistory(); + }); + }); + + describe('Gesture twotap', function () { + it('should handle gesture twotap events', function () { + let bmask = 0x4; + + gestureStart("twotap", 20, 40); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should keep same position for multiple twotap events', function () { + let bmask = 0x4; + + for (let offset = 0;offset < 30;offset += 10) { + pointerEvent.resetHistory(); + + gestureStart('twotap', 20, 40 + offset); + gestureEnd('twotap', 20, 40 + offset); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + } + }); + }); + + describe('Gesture threetap', function () { + it('should handle gesture start for threetap events', function () { + let bmask = 0x2; + + gestureStart("threetap", 20, 40); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should keep same position for multiple threetap events', function () { + let bmask = 0x2; + + for (let offset = 0;offset < 30;offset += 10) { + pointerEvent.resetHistory(); + + gestureStart('threetap', 20, 40 + offset); + gestureEnd('threetap', 20, 40 + offset); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + } + }); + }); + + describe('Gesture drag', function () { + it('should handle gesture drag events', function () { + let bmask = 0x1; + + gestureStart('drag', 20, 40); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + + pointerEvent.resetHistory(); + + gestureMove('drag', 30, 50); + clock.tick(50); + + expect(pointerEvent).to.have.been.calledOnce; + expect(pointerEvent).to.have.been.calledWith(client._sock, + 30, 50, bmask); + + pointerEvent.resetHistory(); + + gestureEnd('drag', 30, 50); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 30, 50, bmask); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + }); + }); + + describe('Gesture long press', function () { + it('should handle long press events', function () { + let bmask = 0x4; + + gestureStart('longpress', 20, 40); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + pointerEvent.resetHistory(); + + gestureMove('longpress', 40, 60); + clock.tick(50); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 40, 60, bmask); + + pointerEvent.resetHistory(); + + gestureEnd('longpress', 40, 60); + + expect(pointerEvent).to.have.been.calledTwice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 40, 60, bmask); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 40, 60, 0x0); + }); + }); + + describe('Gesture twodrag', function () { + it('should handle gesture twodrag up events', function () { + let bmask = 0x10; // Button mask for scroll down + + gestureStart('twodrag', 20, 40, 0, 0); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 20, 40, 0, -60); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should handle gesture twodrag down events', function () { + let bmask = 0x8; // Button mask for scroll up + + gestureStart('twodrag', 20, 40, 0, 0); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 20, 40, 0, 60); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should handle gesture twodrag right events', function () { + let bmask = 0x20; // Button mask for scroll right + + gestureStart('twodrag', 20, 40, 0, 0); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 20, 40, 60, 0); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should handle gesture twodrag left events', function () { + let bmask = 0x40; // Button mask for scroll left + + gestureStart('twodrag', 20, 40, 0, 0); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 20, 40, -60, 0); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should handle gesture twodrag diag events', function () { + let scrlUp = 0x8; // Button mask for scroll up + let scrlRight = 0x20; // Button mask for scroll right + + gestureStart('twodrag', 20, 40, 0, 0); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 20, 40, 60, 60); + + expect(pointerEvent).to.have.been.callCount(5); + expect(pointerEvent.getCall(0)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.getCall(1)).to.have.been.calledWith(client._sock, + 20, 40, scrlUp); + expect(pointerEvent.getCall(2)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.getCall(3)).to.have.been.calledWith(client._sock, + 20, 40, scrlRight); + expect(pointerEvent.getCall(4)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should handle multiple small gesture twodrag events', function () { + let bmask = 0x8; // Button mask for scroll up + + gestureStart('twodrag', 20, 40, 0, 0); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 20, 40, 0, 10); + clock.tick(50); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 20, 40, 0, 20); + clock.tick(50); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 20, 40, 0, 60); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should handle large gesture twodrag events', function () { + let bmask = 0x8; // Button mask for scroll up + + gestureStart('twodrag', 30, 50, 0, 0); + + expect(pointerEvent). + to.have.been.calledOnceWith(client._sock, 30, 50, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 30, 50, 0, 200); + + expect(pointerEvent).to.have.callCount(7); + expect(pointerEvent.getCall(0)).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + expect(pointerEvent.getCall(1)).to.have.been.calledWith(client._sock, + 30, 50, bmask); + expect(pointerEvent.getCall(2)).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + expect(pointerEvent.getCall(3)).to.have.been.calledWith(client._sock, + 30, 50, bmask); + expect(pointerEvent.getCall(4)).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + expect(pointerEvent.getCall(5)).to.have.been.calledWith(client._sock, + 30, 50, bmask); + expect(pointerEvent.getCall(6)).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + }); + }); + + describe('Gesture pinch', function () { + it('should handle gesture pinch in events', function () { + let keysym = KeyTable.XK_Control_L; + let bmask = 0x10; // Button mask for scroll down + + gestureStart('pinch', 20, 40, 90, 90); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + expect(keyEvent).to.not.have.been.called; + + pointerEvent.resetHistory(); + + gestureMove('pinch', 20, 40, 30, 30); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + expect(keyEvent).to.have.been.calledTwice; + expect(keyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, 1); + expect(keyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, 0); + + expect(keyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(keyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); + + pointerEvent.resetHistory(); + keyEvent.resetHistory(); + + gestureEnd('pinch', 20, 40); + + expect(pointerEvent).to.not.have.been.called; + expect(keyEvent).to.not.have.been.called; + }); + + it('should handle gesture pinch out events', function () { + let keysym = KeyTable.XK_Control_L; + let bmask = 0x8; // Button mask for scroll up + + gestureStart('pinch', 10, 20, 10, 20); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 10, 20, 0x0); + expect(keyEvent).to.not.have.been.called; + + pointerEvent.resetHistory(); + + gestureMove('pinch', 10, 20, 70, 80); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 20, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 20, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 10, 20, 0x0); + + expect(keyEvent).to.have.been.calledTwice; + expect(keyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, 1); + expect(keyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, 0); + + expect(keyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(keyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); + + pointerEvent.resetHistory(); + keyEvent.resetHistory(); + + gestureEnd('pinch', 10, 20); + + expect(pointerEvent).to.not.have.been.called; + expect(keyEvent).to.not.have.been.called; + }); + + it('should handle large gesture pinch', function () { + let keysym = KeyTable.XK_Control_L; + let bmask = 0x10; // Button mask for scroll down + + gestureStart('pinch', 20, 40, 150, 150); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + expect(keyEvent).to.not.have.been.called; + + pointerEvent.resetHistory(); + + gestureMove('pinch', 20, 40, 30, 30); + + expect(pointerEvent).to.have.been.callCount(5); + expect(pointerEvent.getCall(0)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.getCall(1)).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.getCall(2)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.getCall(3)).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.getCall(4)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + expect(keyEvent).to.have.been.calledTwice; + expect(keyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, 1); + expect(keyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, 0); + + expect(keyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(keyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); + + pointerEvent.resetHistory(); + keyEvent.resetHistory(); + + gestureEnd('pinch', 20, 40); + + expect(pointerEvent).to.not.have.been.called; + expect(keyEvent).to.not.have.been.called; + }); + + it('should handle multiple small gesture pinch out events', function () { + let keysym = KeyTable.XK_Control_L; + let bmask = 0x8; // Button mask for scroll down + + gestureStart('pinch', 20, 40, 0, 10); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + expect(keyEvent).to.not.have.been.called; + + pointerEvent.resetHistory(); + + gestureMove('pinch', 20, 40, 0, 30); + clock.tick(50); + + expect(pointerEvent).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('pinch', 20, 40, 0, 60); + clock.tick(50); + + expect(pointerEvent).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + pointerEvent.resetHistory(); + keyEvent.resetHistory(); + + gestureMove('pinch', 20, 40, 0, 90); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + expect(keyEvent).to.have.been.calledTwice; + expect(keyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, 1); + expect(keyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, 0); + + expect(keyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(keyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); + + pointerEvent.resetHistory(); + keyEvent.resetHistory(); + + gestureEnd('pinch', 20, 40); + + expect(keyEvent).to.not.have.been.called; + }); + + it('should send correct key control code', function () { + let keysym = KeyTable.XK_Control_L; + let code = 0x1d; + let bmask = 0x10; // Button mask for scroll down + + client._qemuExtKeyEventSupported = true; + + gestureStart('pinch', 20, 40, 90, 90); + + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + expect(qemuKeyEvent).to.not.have.been.called; + + pointerEvent.resetHistory(); + + gestureMove('pinch', 20, 40, 30, 30); + + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + expect(qemuKeyEvent).to.have.been.calledTwice; + expect(qemuKeyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, + true, + code); + expect(qemuKeyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, + false, + code); + + expect(qemuKeyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(qemuKeyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); + + pointerEvent.resetHistory(); + qemuKeyEvent.resetHistory(); + + gestureEnd('pinch', 20, 40); + + expect(pointerEvent).to.not.have.been.called; + expect(qemuKeyEvent).to.not.have.been.called; + }); + }); + }); + + describe('WebSocket Events', function () { + // message events + it('should do nothing if we receive an empty message and have nothing in the queue', function () { + client._normalMsg = sinon.spy(); + client._sock._websocket._receiveData(new Uint8Array([])); + expect(client._normalMsg).to.not.have.been.called; + }); + + it('should handle a message in the connected state as a normal message', function () { + client._normalMsg = sinon.spy(); + client._sock._websocket._receiveData(new Uint8Array([1, 2, 3])); + expect(client._normalMsg).to.have.been.called; + }); + + it('should handle a message in any non-disconnected/failed state like an init message', function () { + client._rfbConnectionState = 'connecting'; + client._rfbInitState = 'ProtocolVersion'; + client._initMsg = sinon.spy(); + client._sock._websocket._receiveData(new Uint8Array([1, 2, 3])); + expect(client._initMsg).to.have.been.called; + }); + + it('should process all normal messages directly', function () { + const spy = sinon.spy(); + client.addEventListener("bell", spy); + client._sock._websocket._receiveData(new Uint8Array([0x02, 0x02])); + expect(spy).to.have.been.calledTwice; + }); + + // open events + it('should update the state to ProtocolVersion on open (if the state is "connecting")', function () { + client = new RFB(document.createElement('div'), 'wss://host:8675'); + this.clock.tick(); + client._sock._websocket._open(); + expect(client._rfbInitState).to.equal('ProtocolVersion'); + }); + + it('should fail if we are not currently ready to connect and we get an "open" event', function () { + sinon.spy(client, "_fail"); + client._rfbConnectionState = 'connected'; + client._sock._websocket._open(); + expect(client._fail).to.have.been.calledOnce; + }); + + // close events + it('should transition to "disconnected" from "disconnecting" on a close event', function () { + const real = client._sock._websocket.close; + client._sock._websocket.close = () => {}; + client.disconnect(); + expect(client._rfbConnectionState).to.equal('disconnecting'); + client._sock._websocket.close = real; + client._sock._websocket.close(); + expect(client._rfbConnectionState).to.equal('disconnected'); + }); + + it('should fail if we get a close event while connecting', function () { + sinon.spy(client, "_fail"); + client._rfbConnectionState = 'connecting'; + client._sock._websocket.close(); + expect(client._fail).to.have.been.calledOnce; + }); + + it('should unregister close event handler', function () { + sinon.spy(client._sock, 'off'); + client.disconnect(); + client._sock._websocket.close(); + expect(client._sock.off).to.have.been.calledWith('close'); + }); + + // error events do nothing + }); + }); + + describe('Quality level setting', function () { + const defaultQuality = 6; + + let client; + + beforeEach(function () { + client = makeRFB(); + sinon.spy(RFB.messages, "clientEncodings"); + }); + + afterEach(function () { + RFB.messages.clientEncodings.restore(); + }); + + it(`should equal ${defaultQuality} by default`, function () { + expect(client._qualityLevel).to.equal(defaultQuality); + }); + + it('should ignore non-integers when set', function () { + client.qualityLevel = '1'; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.qualityLevel = 1.5; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.qualityLevel = null; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.qualityLevel = undefined; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.qualityLevel = {}; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + }); + + it('should ignore integers out of range [0, 9]', function () { + client.qualityLevel = -1; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.qualityLevel = 10; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + }); + + it('should send clientEncodings with new quality value', function () { + let newQuality; + + newQuality = 8; + client.qualityLevel = newQuality; + expect(client.qualityLevel).to.equal(newQuality); + expect(RFB.messages.clientEncodings).to.have.been.calledOnce; + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.pseudoEncodingQualityLevel0 + newQuality); + }); + + it('should not send clientEncodings if quality is the same', function () { + let newQuality; + + newQuality = 2; + client.qualityLevel = newQuality; + expect(RFB.messages.clientEncodings).to.have.been.calledOnce; + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.pseudoEncodingQualityLevel0 + newQuality); + + RFB.messages.clientEncodings.resetHistory(); + + client.qualityLevel = newQuality; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + }); + + it('should not send clientEncodings if not in connected state', function () { + let newQuality; + + client._rfbConnectionState = ''; + newQuality = 2; + client.qualityLevel = newQuality; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client._rfbConnectionState = 'connnecting'; + newQuality = 6; + client.qualityLevel = newQuality; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client._rfbConnectionState = 'connected'; + newQuality = 5; + client.qualityLevel = newQuality; + expect(RFB.messages.clientEncodings).to.have.been.calledOnce; + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.pseudoEncodingQualityLevel0 + newQuality); + }); + }); + + describe('Compression level setting', function () { + const defaultCompression = 2; + + let client; + + beforeEach(function () { + client = makeRFB(); + sinon.spy(RFB.messages, "clientEncodings"); + }); + + afterEach(function () { + RFB.messages.clientEncodings.restore(); + }); + + it(`should equal ${defaultCompression} by default`, function () { + expect(client._compressionLevel).to.equal(defaultCompression); + }); + + it('should ignore non-integers when set', function () { + client.compressionLevel = '1'; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.compressionLevel = 1.5; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.compressionLevel = null; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.compressionLevel = undefined; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.compressionLevel = {}; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + }); + + it('should ignore integers out of range [0, 9]', function () { + client.compressionLevel = -1; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client.compressionLevel = 10; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + }); + + it('should send clientEncodings with new compression value', function () { + let newCompression; + + newCompression = 5; + client.compressionLevel = newCompression; + expect(client.compressionLevel).to.equal(newCompression); + expect(RFB.messages.clientEncodings).to.have.been.calledOnce; + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.pseudoEncodingCompressLevel0 + newCompression); + }); + + it('should not send clientEncodings if compression is the same', function () { + let newCompression; + + newCompression = 9; + client.compressionLevel = newCompression; + expect(RFB.messages.clientEncodings).to.have.been.calledOnce; + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.pseudoEncodingCompressLevel0 + newCompression); + + RFB.messages.clientEncodings.resetHistory(); + + client.compressionLevel = newCompression; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + }); + + it('should not send clientEncodings if not in connected state', function () { + let newCompression; + + client._rfbConnectionState = ''; + newCompression = 7; + client.compressionLevel = newCompression; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client._rfbConnectionState = 'connnecting'; + newCompression = 6; + client.compressionLevel = newCompression; + expect(RFB.messages.clientEncodings).to.not.have.been.called; + + RFB.messages.clientEncodings.resetHistory(); + + client._rfbConnectionState = 'connected'; + newCompression = 5; + client.compressionLevel = newCompression; + expect(RFB.messages.clientEncodings).to.have.been.calledOnce; + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.pseudoEncodingCompressLevel0 + newCompression); + }); + }); +}); + +describe('RFB messages', function () { + let sock; + + before(function () { + FakeWebSocket.replace(); + sock = new Websock(); + sock.open(); + }); + + after(function () { + FakeWebSocket.restore(); + }); + + describe('Extended Clipboard Handling Send', function () { + beforeEach(function () { + sinon.spy(RFB.messages, 'clientCutText'); + }); + + afterEach(function () { + RFB.messages.clientCutText.restore(); + }); + + it('should call clientCutText with correct Caps data', function () { + let formats = { + 0: 2, + 2: 4121 + }; + let expectedData = new Uint8Array([0x1F, 0x00, 0x00, 0x05, + 0x00, 0x00, 0x00, 0x02, + 0x00, 0x00, 0x10, 0x19]); + let actions = [ + 1 << 24, // Caps + 1 << 25, // Request + 1 << 26, // Peek + 1 << 27, // Notify + 1 << 28 // Provide + ]; + + RFB.messages.extendedClipboardCaps(sock, actions, formats); + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(sock, expectedData); + }); + + it('should call clientCutText with correct Request data', function () { + let formats = new Uint8Array([0x01]); + let expectedData = new Uint8Array([0x02, 0x00, 0x00, 0x01]); + + RFB.messages.extendedClipboardRequest(sock, formats); + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(sock, expectedData); + }); + + it('should call clientCutText with correct Notify data', function () { + let formats = new Uint8Array([0x01]); + let expectedData = new Uint8Array([0x08, 0x00, 0x00, 0x01]); + + RFB.messages.extendedClipboardNotify(sock, formats); + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(sock, expectedData); + }); + + it('should call clientCutText with correct Provide data', function () { + let testText = "Test string"; + let expectedText = encodeUTF8(testText + "\0"); + + let deflatedData = deflateWithSize(expectedText); + + // Build Expected with flags and deflated data + let expectedData = new Uint8Array(4 + deflatedData.length); + expectedData[0] = 0x10; // The client capabilities + expectedData[1] = 0x00; // Reserved flags + expectedData[2] = 0x00; // Reserved flags + expectedData[3] = 0x01; // The formats client supports + expectedData.set(deflatedData, 4); + + RFB.messages.extendedClipboardProvide(sock, [0x01], [testText]); + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(sock, expectedData, true); + + }); + + describe('End of line characters', function () { + it('Carriage return', function () { + + let testText = "Hello\rworld\r\r!"; + let expectedText = encodeUTF8("Hello\r\nworld\r\n\r\n!\0"); + + let deflatedData = deflateWithSize(expectedText); + + // Build Expected with flags and deflated data + let expectedData = new Uint8Array(4 + deflatedData.length); + expectedData[0] = 0x10; // The client capabilities + expectedData[1] = 0x00; // Reserved flags + expectedData[2] = 0x00; // Reserved flags + expectedData[3] = 0x01; // The formats client supports + expectedData.set(deflatedData, 4); + + RFB.messages.extendedClipboardProvide(sock, [0x01], [testText]); + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(sock, expectedData, true); + }); + + it('Carriage return Line feed', function () { + + let testText = "Hello\r\n\r\nworld\r\n!"; + let expectedText = encodeUTF8(testText + "\0"); + + let deflatedData = deflateWithSize(expectedText); + + // Build Expected with flags and deflated data + let expectedData = new Uint8Array(4 + deflatedData.length); + expectedData[0] = 0x10; // The client capabilities + expectedData[1] = 0x00; // Reserved flags + expectedData[2] = 0x00; // Reserved flags + expectedData[3] = 0x01; // The formats client supports + expectedData.set(deflatedData, 4); + + RFB.messages.extendedClipboardProvide(sock, [0x01], [testText]); + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(sock, expectedData, true); + }); + + it('Line feed', function () { + let testText = "Hello\n\n\nworld\n!"; + let expectedText = encodeUTF8("Hello\r\n\r\n\r\nworld\r\n!\0"); + + let deflatedData = deflateWithSize(expectedText); + + // Build Expected with flags and deflated data + let expectedData = new Uint8Array(4 + deflatedData.length); + expectedData[0] = 0x10; // The client capabilities + expectedData[1] = 0x00; // Reserved flags + expectedData[2] = 0x00; // Reserved flags + expectedData[3] = 0x01; // The formats client supports + expectedData.set(deflatedData, 4); + + RFB.messages.extendedClipboardProvide(sock, [0x01], [testText]); + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(sock, expectedData, true); + }); + + it('Carriage return and Line feed mixed', function () { + let testText = "\rHello\r\n\rworld\n\n!"; + let expectedText = encodeUTF8("\r\nHello\r\n\r\nworld\r\n\r\n!\0"); + + let deflatedData = deflateWithSize(expectedText); + + // Build Expected with flags and deflated data + let expectedData = new Uint8Array(4 + deflatedData.length); + expectedData[0] = 0x10; // The client capabilities + expectedData[1] = 0x00; // Reserved flags + expectedData[2] = 0x00; // Reserved flags + expectedData[3] = 0x01; // The formats client supports + expectedData.set(deflatedData, 4); + + RFB.messages.extendedClipboardProvide(sock, [0x01], [testText]); + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(sock, expectedData, true); + }); }); }); }); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.util.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.util.js index 201acc8b..cd61f248 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.util.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.util.js @@ -2,6 +2,7 @@ const expect = chai.expect; import * as Log from '../core/util/logging.js'; +import { encodeUTF8, decodeUTF8 } from '../core/util/strings.js'; describe('Utils', function () { "use strict"; @@ -21,45 +22,64 @@ describe('Utils', function () { console.warn.restore(); console.error.restore(); console.info.restore(); - Log.init_logging(); + Log.initLogging(); }); it('should use noop for levels lower than the min level', function () { - Log.init_logging('warn'); + Log.initLogging('warn'); Log.Debug('hi'); Log.Info('hello'); expect(console.log).to.not.have.been.called; }); it('should use console.debug for Debug', function () { - Log.init_logging('debug'); + Log.initLogging('debug'); Log.Debug('dbg'); expect(console.debug).to.have.been.calledWith('dbg'); }); it('should use console.info for Info', function () { - Log.init_logging('debug'); + Log.initLogging('debug'); Log.Info('inf'); expect(console.info).to.have.been.calledWith('inf'); }); it('should use console.warn for Warn', function () { - Log.init_logging('warn'); + Log.initLogging('warn'); Log.Warn('wrn'); expect(console.warn).to.have.been.called; expect(console.warn).to.have.been.calledWith('wrn'); }); it('should use console.error for Error', function () { - Log.init_logging('error'); + Log.initLogging('error'); Log.Error('err'); expect(console.error).to.have.been.called; expect(console.error).to.have.been.calledWith('err'); }); }); + describe('string functions', function () { + it('should decode UTF-8 to DOMString correctly', function () { + const utf8string = '\xd0\x9f'; + const domstring = decodeUTF8(utf8string); + expect(domstring).to.equal("П"); + }); + + it('should encode DOMString to UTF-8 correctly', function () { + const domstring = "åäöa"; + const utf8string = encodeUTF8(domstring); + expect(utf8string).to.equal('\xc3\xa5\xc3\xa4\xc3\xb6\x61'); + }); + + it('should allow Latin-1 strings if allowLatin1 is set when decoding', function () { + const latin1string = '\xe5\xe4\xf6'; + expect(() => decodeUTF8(latin1string)).to.throw(Error); + expect(decodeUTF8(latin1string, true)).to.equal('åäö'); + }); + }); + // TODO(directxman12): test the conf_default and conf_defaults methods - // TODO(directxman12): test decodeUTF8 // TODO(directxman12): test the event methods (addEvent, removeEvent, stopEvent) // TODO(directxman12): figure out a good way to test getPosition and getEventPosition // TODO(directxman12): figure out how to test the browser detection functions properly diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.websock.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.websock.js index 30e19e9d..a8e17e6b 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.websock.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.websock.js @@ -13,7 +13,7 @@ describe('Websock', function () { beforeEach(function () { sock = new Websock(); // skip init - sock._allocate_buffers(); + sock._allocateBuffers(); sock._rQ.set(RQ_TEMPLATE); sock._rQlen = RQ_TEMPLATE.length; }); @@ -33,51 +33,51 @@ describe('Websock', function () { describe('rQpeek8', function () { it('should peek at the next byte without poping it off the queue', function () { - const bef_len = sock.rQlen; + const befLen = sock.rQlen; const peek = sock.rQpeek8(); expect(sock.rQpeek8()).to.equal(peek); - expect(sock.rQlen).to.equal(bef_len); + expect(sock.rQlen).to.equal(befLen); }); }); describe('rQshift8()', function () { it('should pop a single byte from the receive queue', function () { const peek = sock.rQpeek8(); - const bef_len = sock.rQlen; + const befLen = sock.rQlen; expect(sock.rQshift8()).to.equal(peek); - expect(sock.rQlen).to.equal(bef_len - 1); + expect(sock.rQlen).to.equal(befLen - 1); }); }); describe('rQshift16()', function () { it('should pop two bytes from the receive queue and return a single number', function () { - const bef_len = sock.rQlen; + const befLen = sock.rQlen; const expected = (RQ_TEMPLATE[0] << 8) + RQ_TEMPLATE[1]; expect(sock.rQshift16()).to.equal(expected); - expect(sock.rQlen).to.equal(bef_len - 2); + expect(sock.rQlen).to.equal(befLen - 2); }); }); describe('rQshift32()', function () { it('should pop four bytes from the receive queue and return a single number', function () { - const bef_len = sock.rQlen; + const befLen = sock.rQlen; const expected = (RQ_TEMPLATE[0] << 24) + (RQ_TEMPLATE[1] << 16) + (RQ_TEMPLATE[2] << 8) + RQ_TEMPLATE[3]; expect(sock.rQshift32()).to.equal(expected); - expect(sock.rQlen).to.equal(bef_len - 4); + expect(sock.rQlen).to.equal(befLen - 4); }); }); describe('rQshiftStr', function () { it('should shift the given number of bytes off of the receive queue and return a string', function () { - const bef_len = sock.rQlen; - const bef_rQi = sock.rQi; + const befLen = sock.rQlen; + const befRQi = sock.rQi; const shifted = sock.rQshiftStr(3); expect(shifted).to.be.a('string'); - expect(shifted).to.equal(String.fromCharCode.apply(null, Array.prototype.slice.call(new Uint8Array(RQ_TEMPLATE.buffer, bef_rQi, 3)))); - expect(sock.rQlen).to.equal(bef_len - 3); + expect(shifted).to.equal(String.fromCharCode.apply(null, Array.prototype.slice.call(new Uint8Array(RQ_TEMPLATE.buffer, befRQi, 3)))); + expect(sock.rQlen).to.equal(befLen - 3); }); it('should shift the entire rest of the queue off if no length is given', function () { @@ -112,12 +112,12 @@ describe('Websock', function () { describe('rQshiftBytes', function () { it('should shift the given number of bytes of the receive queue and return an array', function () { - const bef_len = sock.rQlen; - const bef_rQi = sock.rQi; + const befLen = sock.rQlen; + const befRQi = sock.rQi; const shifted = sock.rQshiftBytes(3); expect(shifted).to.be.an.instanceof(Uint8Array); - expect(shifted).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, bef_rQi, 3)); - expect(sock.rQlen).to.equal(bef_len - 3); + expect(shifted).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, befRQi, 3)); + expect(sock.rQlen).to.equal(befLen - 3); }); it('should shift the entire rest of the queue off if no length is given', function () { @@ -132,9 +132,9 @@ describe('Websock', function () { }); it('should not modify the receive queue', function () { - const bef_len = sock.rQlen; + const befLen = sock.rQlen; sock.rQslice(0, 2); - expect(sock.rQlen).to.equal(bef_len); + expect(sock.rQlen).to.equal(befLen); }); it('should return an array containing the given slice of the receive queue', function () { @@ -198,7 +198,7 @@ describe('Websock', function () { sock._websocket.readyState = WebSocket.OPEN; sock._sQ = new Uint8Array([1, 2, 3]); sock._sQlen = 3; - const encoded = sock._encode_message(); + const encoded = sock._encodeMessage(); sock.flush(); expect(sock._websocket.send).to.have.been.calledOnce; @@ -232,22 +232,22 @@ describe('Websock', function () { }); }); - describe('send_string', function () { + describe('sendString', function () { beforeEach(function () { sock.send = sinon.spy(); }); it('should call send after converting the string to an array', function () { - sock.send_string("\x01\x02\x03"); + sock.sendString("\x01\x02\x03"); expect(sock.send).to.have.been.calledWith([1, 2, 3]); }); }); }); describe('lifecycle methods', function () { - let old_WS; + let oldWS; before(function () { - old_WS = WebSocket; + oldWS = WebSocket; }); let sock; @@ -255,10 +255,10 @@ describe('Websock', function () { sock = new Websock(); // eslint-disable-next-line no-global-assign WebSocket = sinon.spy(); - WebSocket.OPEN = old_WS.OPEN; - WebSocket.CONNECTING = old_WS.CONNECTING; - WebSocket.CLOSING = old_WS.CLOSING; - WebSocket.CLOSED = old_WS.CLOSED; + WebSocket.OPEN = oldWS.OPEN; + WebSocket.CONNECTING = oldWS.CONNECTING; + WebSocket.CLOSING = oldWS.CLOSING; + WebSocket.CLOSED = oldWS.CLOSED; WebSocket.prototype.binaryType = 'arraybuffer'; }); @@ -306,30 +306,30 @@ describe('Websock', function () { expect(sock._websocket.close).not.to.have.been.called; }); - it('should reset onmessage to not call _recv_message', function () { - sinon.spy(sock, '_recv_message'); + it('should reset onmessage to not call _recvMessage', function () { + sinon.spy(sock, '_recvMessage'); sock.close(); sock._websocket.onmessage(null); try { - expect(sock._recv_message).not.to.have.been.called; + expect(sock._recvMessage).not.to.have.been.called; } finally { - sock._recv_message.restore(); + sock._recvMessage.restore(); } }); }); describe('event handlers', function () { beforeEach(function () { - sock._recv_message = sinon.spy(); + sock._recvMessage = sinon.spy(); sock.on('open', sinon.spy()); sock.on('close', sinon.spy()); sock.on('error', sinon.spy()); sock.open('ws://'); }); - it('should call _recv_message on a message', function () { + it('should call _recvMessage on a message', function () { sock._websocket.onmessage(null); - expect(sock._recv_message).to.have.been.calledOnce; + expect(sock._recvMessage).to.have.been.calledOnce; }); it('should call the open event handler on opening', function () { @@ -350,7 +350,7 @@ describe('Websock', function () { after(function () { // eslint-disable-next-line no-global-assign - WebSocket = old_WS; + WebSocket = oldWS; }); }); @@ -358,13 +358,13 @@ describe('Websock', function () { let sock; beforeEach(function () { sock = new Websock(); - sock._allocate_buffers(); + sock._allocateBuffers(); }); it('should support adding binary Uint8Array data to the receive queue', function () { const msg = { data: new Uint8Array([1, 2, 3]) }; sock._mode = 'binary'; - sock._recv_message(msg); + sock._recvMessage(msg); expect(sock.rQshiftStr(3)).to.equal('\x01\x02\x03'); }); @@ -372,7 +372,7 @@ describe('Websock', function () { sock._eventHandlers.message = sinon.spy(); const msg = { data: new Uint8Array([1, 2, 3]).buffer }; sock._mode = 'binary'; - sock._recv_message(msg); + sock._recvMessage(msg); expect(sock._eventHandlers.message).to.have.been.calledOnce; }); @@ -380,37 +380,59 @@ describe('Websock', function () { sock._eventHandlers.message = sinon.spy(); const msg = { data: new Uint8Array([]).buffer }; sock._mode = 'binary'; - sock._recv_message(msg); + sock._recvMessage(msg); expect(sock._eventHandlers.message).not.to.have.been.called; }); - it('should compact the receive queue', function () { - // NB(sross): while this is an internal implementation detail, it's important to - // test, otherwise the receive queue could become very large very quickly + it('should compact the receive queue when a message handler empties it', function () { + sock._eventHandlers.message = () => { sock.rQi = sock._rQlen; }; sock._rQ = new Uint8Array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0]); sock._rQlen = 6; sock.rQi = 6; - sock._rQmax = 3; const msg = { data: new Uint8Array([1, 2, 3]).buffer }; sock._mode = 'binary'; - sock._recv_message(msg); - expect(sock._rQlen).to.equal(3); + sock._recvMessage(msg); + expect(sock._rQlen).to.equal(0); expect(sock.rQi).to.equal(0); }); - it('should automatically resize the receive queue if the incoming message is too large', function () { + it('should compact the receive queue when we reach the end of the buffer', function () { + sock._rQ = new Uint8Array(20); + sock._rQbufferSize = 20; + sock._rQlen = 20; + sock.rQi = 10; + const msg = { data: new Uint8Array([1, 2]).buffer }; + sock._mode = 'binary'; + sock._recvMessage(msg); + expect(sock._rQlen).to.equal(12); + expect(sock.rQi).to.equal(0); + }); + + it('should automatically resize the receive queue if the incoming message is larger than the buffer', function () { sock._rQ = new Uint8Array(20); sock._rQlen = 0; sock.rQi = 0; sock._rQbufferSize = 20; - sock._rQmax = 2; const msg = { data: new Uint8Array(30).buffer }; sock._mode = 'binary'; - sock._recv_message(msg); + sock._recvMessage(msg); expect(sock._rQlen).to.equal(30); expect(sock.rQi).to.equal(0); expect(sock._rQ.length).to.equal(240); // keep the invariant that rQbufferSize / 8 >= rQlen }); + + it('should automatically resize the receive queue if the incoming message is larger than 1/8th of the buffer and we reach the end of the buffer', function () { + sock._rQ = new Uint8Array(20); + sock._rQlen = 16; + sock.rQi = 16; + sock._rQbufferSize = 20; + const msg = { data: new Uint8Array(6).buffer }; + sock._mode = 'binary'; + sock._recvMessage(msg); + expect(sock._rQlen).to.equal(6); + expect(sock.rQi).to.equal(0); + expect(sock._rQ.length).to.equal(48); + }); }); describe('Data encoding', function () { @@ -428,13 +450,13 @@ describe('Websock', function () { it('should only send the send queue up to the send queue length', function () { sock._sQ = new Uint8Array([1, 2, 3, 4, 5]); sock._sQlen = 3; - const res = sock._encode_message(); + const res = sock._encodeMessage(); expect(res).to.array.equal(new Uint8Array([1, 2, 3])); }); it('should properly pass the encoded data off to the actual WebSocket', function () { sock.send([1, 2, 3]); - expect(sock._websocket._get_sent_data()).to.array.equal(new Uint8Array([1, 2, 3])); + expect(sock._websocket._getSentData()).to.array.equal(new Uint8Array([1, 2, 3])); }); }); }); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.webutil.js b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.webutil.js index 72e19421..2a166ee0 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.webutil.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/tests/test.webutil.js @@ -42,7 +42,9 @@ describe('WebUtil', function () { return WebUtil.initSettings(); }); afterEach(function () { - Object.defineProperty(window, "localStorage", origLocalStorage); + if (origLocalStorage !== undefined) { + Object.defineProperty(window, "localStorage", origLocalStorage); + } }); describe('writeSetting', function () { diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/utils/genkeysymdef.js b/jupyter_desktop/share/web/noVNC-1.2.0/utils/genkeysymdef.js index d21773f9..f539a0b2 100755 --- a/jupyter_desktop/share/web/noVNC-1.2.0/utils/genkeysymdef.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/utils/genkeysymdef.js @@ -9,14 +9,14 @@ const fs = require('fs'); -let show_help = process.argv.length === 2; +let showHelp = process.argv.length === 2; let filename; for (let i = 2; i < process.argv.length; ++i) { switch (process.argv[i]) { case "--help": case "-h": - show_help = true; + showHelp = true; break; case "--file": case "-f": @@ -26,11 +26,11 @@ for (let i = 2; i < process.argv.length; ++i) { } if (!filename) { - show_help = true; + showHelp = true; console.log("Error: No filename specified\n"); } -if (show_help) { +if (showHelp) { console.log("Parses a *nix keysymdef.h to generate Unicode code point mappings"); console.log("Usage: node parse.js [options] filename:"); console.log(" -h [ --help ] Produce this help message"); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/utils/img2js.py b/jupyter_desktop/share/web/noVNC-1.2.0/utils/img2js.py deleted file mode 100755 index ceab6bf7..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/utils/img2js.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python - -# -# Convert image to Javascript compatible base64 Data URI -# Copyright (C) 2018 The noVNC Authors -# Licensed under MPL 2.0 (see docs/LICENSE.MPL-2.0) -# - -import sys, base64 - -try: - from PIL import Image -except: - print "python PIL module required (python-imaging package)" - sys.exit(1) - - -if len(sys.argv) < 3: - print "Usage: %s IMAGE JS_VARIABLE" % sys.argv[0] - sys.exit(1) - -fname = sys.argv[1] -var = sys.argv[2] - -ext = fname.lower().split('.')[-1] -if ext == "png": mime = "image/png" -elif ext in ["jpg", "jpeg"]: mime = "image/jpeg" -elif ext == "gif": mime = "image/gif" -else: - print "Only PNG, JPEG and GIF images are supported" - sys.exit(1) -uri = "data:%s;base64," % mime - -im = Image.open(fname) -w, h = im.size - -raw = open(fname).read() - -print '%s = {"width": %s, "height": %s, "data": "%s%s"};' % ( - var, w, h, uri, base64.b64encode(raw)) diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/utils/json2graph.py b/jupyter_desktop/share/web/noVNC-1.2.0/utils/json2graph.py deleted file mode 100755 index bdaeecca..00000000 --- a/jupyter_desktop/share/web/noVNC-1.2.0/utils/json2graph.py +++ /dev/null @@ -1,206 +0,0 @@ -#!/usr/bin/env python - -''' -Use matplotlib to generate performance charts -Copyright (C) 2018 The noVNC Authors -Licensed under MPL-2.0 (see docs/LICENSE.MPL-2.0) -''' - -# a bar plot with errorbars -import sys, json -import numpy as np -import matplotlib.pyplot as plt -from matplotlib.font_manager import FontProperties - -def usage(): - print "%s json_file level1 level2 level3 [legend_height]\n\n" % sys.argv[0] - print "Description:\n" - print "level1, level2, and level3 are one each of the following:\n"; - print " select=ITEM - select only ITEM at this level"; - print " bar - each item on this level becomes a graph bar"; - print " group - items on this level become groups of bars"; - print "\n"; - print "json_file is a file containing json data in the following format:\n" - print ' {'; - print ' "conf": {'; - print ' "order_l1": ['; - print ' "level1_label1",'; - print ' "level1_label2",'; - print ' ...'; - print ' ],'; - print ' "order_l2": ['; - print ' "level2_label1",'; - print ' "level2_label2",'; - print ' ...'; - print ' ],'; - print ' "order_l3": ['; - print ' "level3_label1",'; - print ' "level3_label2",'; - print ' ...'; - print ' ]'; - print ' },'; - print ' "stats": {'; - print ' "level1_label1": {'; - print ' "level2_label1": {'; - print ' "level3_label1": [val1, val2, val3],'; - print ' "level3_label2": [val1, val2, val3],'; - print ' ...'; - print ' },'; - print ' "level2_label2": {'; - print ' ...'; - print ' },'; - print ' },'; - print ' "level1_label2": {'; - print ' ...'; - print ' },'; - print ' ...'; - print ' },'; - print ' }'; - sys.exit(2) - -def error(msg): - print msg - sys.exit(1) - - -#colors = ['#ff0000', '#0863e9', '#00f200', '#ffa100', -# '#800000', '#805100', '#013075', '#007900'] -colors = ['#ff0000', '#00ff00', '#0000ff', - '#dddd00', '#dd00dd', '#00dddd', - '#dd6622', '#dd2266', '#66dd22', - '#8844dd', '#44dd88', '#4488dd'] - -if len(sys.argv) < 5: - usage() - -filename = sys.argv[1] -L1 = sys.argv[2] -L2 = sys.argv[3] -L3 = sys.argv[4] -if len(sys.argv) > 5: - legendHeight = float(sys.argv[5]) -else: - legendHeight = 0.75 - -# Load the JSON data from the file -data = json.loads(file(filename).read()) -conf = data['conf'] -stats = data['stats'] - -# Sanity check data hierarchy -if len(conf['order_l1']) != len(stats.keys()): - error("conf.order_l1 does not match stats level 1") -for l1 in stats.keys(): - if len(conf['order_l2']) != len(stats[l1].keys()): - error("conf.order_l2 does not match stats level 2 for %s" % l1) - if conf['order_l1'].count(l1) < 1: - error("%s not found in conf.order_l1" % l1) - for l2 in stats[l1].keys(): - if len(conf['order_l3']) != len(stats[l1][l2].keys()): - error("conf.order_l3 does not match stats level 3") - if conf['order_l2'].count(l2) < 1: - error("%s not found in conf.order_l2" % l2) - for l3 in stats[l1][l2].keys(): - if conf['order_l3'].count(l3) < 1: - error("%s not found in conf.order_l3" % l3) - -# -# Generate the data based on the level specifications -# -bar_labels = None -group_labels = None -bar_vals = [] -bar_sdvs = [] -if L3.startswith("select="): - select_label = l3 = L3.split("=")[1] - bar_labels = conf['order_l1'] - group_labels = conf['order_l2'] - bar_vals = [[0]*len(group_labels) for i in bar_labels] - bar_sdvs = [[0]*len(group_labels) for i in bar_labels] - for b in range(len(bar_labels)): - l1 = bar_labels[b] - for g in range(len(group_labels)): - l2 = group_labels[g] - bar_vals[b][g] = np.mean(stats[l1][l2][l3]) - bar_sdvs[b][g] = np.std(stats[l1][l2][l3]) -elif L2.startswith("select="): - select_label = l2 = L2.split("=")[1] - bar_labels = conf['order_l1'] - group_labels = conf['order_l3'] - bar_vals = [[0]*len(group_labels) for i in bar_labels] - bar_sdvs = [[0]*len(group_labels) for i in bar_labels] - for b in range(len(bar_labels)): - l1 = bar_labels[b] - for g in range(len(group_labels)): - l3 = group_labels[g] - bar_vals[b][g] = np.mean(stats[l1][l2][l3]) - bar_sdvs[b][g] = np.std(stats[l1][l2][l3]) -elif L1.startswith("select="): - select_label = l1 = L1.split("=")[1] - bar_labels = conf['order_l2'] - group_labels = conf['order_l3'] - bar_vals = [[0]*len(group_labels) for i in bar_labels] - bar_sdvs = [[0]*len(group_labels) for i in bar_labels] - for b in range(len(bar_labels)): - l2 = bar_labels[b] - for g in range(len(group_labels)): - l3 = group_labels[g] - bar_vals[b][g] = np.mean(stats[l1][l2][l3]) - bar_sdvs[b][g] = np.std(stats[l1][l2][l3]) -else: - usage() - -# If group is before bar then flip (zip) the data -if [L1, L2, L3].index("group") < [L1, L2, L3].index("bar"): - bar_labels, group_labels = group_labels, bar_labels - bar_vals = zip(*bar_vals) - bar_sdvs = zip(*bar_sdvs) - -print "bar_vals:", bar_vals - -# -# Now render the bar graph -# -ind = np.arange(len(group_labels)) # the x locations for the groups -width = 0.8 * (1.0/len(bar_labels)) # the width of the bars - -fig = plt.figure(figsize=(10,6), dpi=80) -plot = fig.add_subplot(1, 1, 1) - -rects = [] -for i in range(len(bar_vals)): - rects.append(plot.bar(ind+width*i, bar_vals[i], width, color=colors[i], - yerr=bar_sdvs[i], align='center')) - -# add some -plot.set_ylabel('Milliseconds (less is better)') -plot.set_title("Javascript array test: %s" % select_label) -plot.set_xticks(ind+width) -plot.set_xticklabels( group_labels ) - -fontP = FontProperties() -fontP.set_size('small') -plot.legend( [r[0] for r in rects], bar_labels, prop=fontP, - loc = 'center right', bbox_to_anchor = (1.0, legendHeight)) - -def autolabel(rects): - # attach some text labels - for rect in rects: - height = rect.get_height() - if np.isnan(height): - height = 0.0 - plot.text(rect.get_x()+rect.get_width()/2., height+20, '%d'%int(height), - ha='center', va='bottom', size='7') - -for rect in rects: - autolabel(rect) - -# Adjust axis sizes -axis = list(plot.axis()) -axis[0] = -width # Make sure left side has enough for bar -#axis[1] = axis[1] * 1.20 # Add 20% to the right to make sure it fits -axis[2] = 0 # Make y-axis start at 0 -axis[3] = axis[3] * 1.10 # Add 10% to the top -plot.axis(axis) - -plt.show() diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/utils/launch.sh b/jupyter_desktop/share/web/noVNC-1.2.0/utils/launch.sh index 162607eb..4cb6fc2b 100755 --- a/jupyter_desktop/share/web/noVNC-1.2.0/utils/launch.sh +++ b/jupyter_desktop/share/web/noVNC-1.2.0/utils/launch.sh @@ -17,8 +17,10 @@ usage() { echo " Default: 6080" echo " --vnc VNC_HOST:PORT VNC server host:port proxy target" echo " Default: localhost:5900" - echo " --cert CERT Path to combined cert/key file" + echo " --cert CERT Path to combined cert/key file, or just" + echo " the cert file if used with --key" echo " Default: self.pem" + echo " --key KEY Path to key file, when not combined with cert" echo " --web WEB Path to web files (e.g. vnc.html)" echo " Default: ./" echo " --ssl-only Disable non-https connections." @@ -34,6 +36,7 @@ HERE="$(cd "$(dirname "$REAL_NAME")" && pwd)" PORT="6080" VNC_DEST="localhost:5900" CERT="" +KEY="" WEB="" proxy_pid="" SSLONLY="" @@ -63,6 +66,7 @@ while [ "$*" ]; do --listen) PORT="${OPTARG}"; shift ;; --vnc) VNC_DEST="${OPTARG}"; shift ;; --cert) CERT="${OPTARG}"; shift ;; + --key) KEY="${OPTARG}"; shift ;; --web) WEB="${OPTARG}"; shift ;; --ssl-only) SSLONLY="--ssl-only" ;; --record) RECORD_ARG="--record ${OPTARG}"; shift ;; @@ -116,8 +120,15 @@ else echo "Warning: could not find self.pem" fi +# Check key file +if [ -n "${KEY}" ]; then + if [ ! -e "${KEY}" ]; then + die "Could not find ${KEY}" + fi +fi + # try to find websockify (prefer local, try global, then download local) -if [[ -e ${HERE}/websockify ]]; then +if [[ -d ${HERE}/websockify ]]; then WEBSOCKIFY=${HERE}/websockify/run if [[ ! -x $WEBSOCKIFY ]]; then @@ -128,9 +139,12 @@ if [[ -e ${HERE}/websockify ]]; then echo "Using local websockify at $WEBSOCKIFY" else - WEBSOCKIFY=$(which websockify 2>/dev/null) + WEBSOCKIFY_FROMSYSTEM=$(which websockify 2>/dev/null) + WEBSOCKIFY_FROMSNAP=${HERE}/../usr/bin/python2-websockify + [ -f $WEBSOCKIFY_FROMSYSTEM ] && WEBSOCKIFY=$WEBSOCKIFY_FROMSYSTEM + [ -f $WEBSOCKIFY_FROMSNAP ] && WEBSOCKIFY=$WEBSOCKIFY_FROMSNAP - if [[ $? -ne 0 ]]; then + if [ ! -f "$WEBSOCKIFY" ]; then echo "No installed websockify, attempting to clone websockify..." WEBSOCKIFY=${HERE}/websockify/run git clone https://github.com/novnc/websockify ${HERE}/websockify @@ -148,7 +162,7 @@ fi echo "Starting webserver and WebSockets proxy on port ${PORT}" #${HERE}/websockify --web ${WEB} ${CERT:+--cert ${CERT}} ${PORT} ${VNC_DEST} & -${WEBSOCKIFY} ${SSLONLY} --web ${WEB} ${CERT:+--cert ${CERT}} ${PORT} ${VNC_DEST} ${RECORD_ARG} & +${WEBSOCKIFY} ${SSLONLY} --web ${WEB} ${CERT:+--cert ${CERT}} ${KEY:+--key ${KEY}} ${PORT} ${VNC_DEST} ${RECORD_ARG} & proxy_pid="$!" sleep 1 if ! ps -p ${proxy_pid} >/dev/null; then diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/utils/use_require.js b/jupyter_desktop/share/web/noVNC-1.2.0/utils/use_require.js index 24879271..c29f7715 100755 --- a/jupyter_desktop/share/web/noVNC-1.2.0/utils/use_require.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/utils/use_require.js @@ -4,7 +4,7 @@ const path = require('path'); const program = require('commander'); const fs = require('fs'); const fse = require('fs-extra'); -const babel = require('babel-core'); +const babel = require('@babel/core'); const SUPPORTED_FORMATS = new Set(['amd', 'commonjs', 'systemjs', 'umd']); @@ -22,28 +22,31 @@ const paths = { core: path.resolve(__dirname, '..', 'core'), app: path.resolve(__dirname, '..', 'app'), vendor: path.resolve(__dirname, '..', 'vendor'), - out_dir_base: path.resolve(__dirname, '..', 'build'), - lib_dir_base: path.resolve(__dirname, '..', 'lib'), + outDirBase: path.resolve(__dirname, '..', 'build'), + libDirBase: path.resolve(__dirname, '..', 'lib'), }; -const no_copy_files = new Set([ +const noCopyFiles = new Set([ // skip these -- they don't belong in the processed application path.join(paths.vendor, 'sinon.js'), path.join(paths.vendor, 'browser-es-module-loader'), - path.join(paths.vendor, 'promise.js'), path.join(paths.app, 'images', 'icons', 'Makefile'), ]); -const no_transform_files = new Set([ +const onlyLegacyScripts = new Set([ + path.join(paths.vendor, 'promise.js'), +]); + +const noTransformFiles = new Set([ // don't transform this -- we want it imported as-is to properly catch loading errors path.join(paths.app, 'error-handler.js'), ]); -no_copy_files.forEach(file => no_transform_files.add(file)); +noCopyFiles.forEach(file => noTransformFiles.add(file)); // util.promisify requires Node.js 8.x, so we have our own function promisify(original) { - return function promise_wrap() { + return function promiseWrap() { const args = Array.prototype.slice.call(arguments); return new Promise((resolve, reject) => { original.apply(this, args.concat((err, value) => { @@ -69,10 +72,10 @@ const babelTransformFile = promisify(babel.transformFile); // walkDir *recursively* walks directories trees, // calling the callback for all normal files found. -function walkDir(base_path, cb, filter) { - return readdir(base_path) +function walkDir(basePath, cb, filter) { + return readdir(basePath) .then((files) => { - const paths = files.map(filename => path.join(base_path, filename)); + const paths = files.map(filename => path.join(basePath, filename)); return Promise.all(paths.map(filepath => lstat(filepath) .then((stats) => { if (filter !== undefined && !filter(filepath, stats)) return; @@ -84,198 +87,204 @@ function walkDir(base_path, cb, filter) { }); } -function transform_html(legacy_scripts, only_legacy) { +function transformHtml(legacyScripts, onlyLegacy) { // write out the modified vnc.html file that works with the bundle - const src_html_path = path.resolve(__dirname, '..', 'vnc.html'); - const out_html_path = path.resolve(paths.out_dir_base, 'vnc.html'); - return readFile(src_html_path) - .then((contents_raw) => { - let contents = contents_raw.toString(); + const srcHtmlPath = path.resolve(__dirname, '..', 'vnc.html'); + const outHtmlPath = path.resolve(paths.outDirBase, 'vnc.html'); + return readFile(srcHtmlPath) + .then((contentsRaw) => { + let contents = contentsRaw.toString(); - const start_marker = '\n'; - const end_marker = ''; - const start_ind = contents.indexOf(start_marker) + start_marker.length; - const end_ind = contents.indexOf(end_marker, start_ind); + const startMarker = '\n'; + const endMarker = ''; + const startInd = contents.indexOf(startMarker) + startMarker.length; + const endInd = contents.indexOf(endMarker, startInd); - let new_script = ''; + let newScript = ''; - if (only_legacy) { + if (onlyLegacy) { // Only legacy version, so include things directly - for (let i = 0;i < legacy_scripts.length;i++) { - new_script += ` \n`; + for (let i = 0;i < legacyScripts.length;i++) { + newScript += ` \n`; } } else { - // Otherwise detect if it's a modern browser and select - // variant accordingly - new_script += `\ - \n\ - \n`; - - // Original, ES6 modules - new_script += ' \n'; + // Otherwise include both modules and legacy fallbacks + newScript += ' \n'; + for (let i = 0;i < legacyScripts.length;i++) { + newScript += ` \n`; + } } - contents = contents.slice(0, start_ind) + `${new_script}\n` + contents.slice(end_ind); + contents = contents.slice(0, startInd) + `${newScript}\n` + contents.slice(endInd); return contents; }) .then((contents) => { - console.log(`Writing ${out_html_path}`); - return writeFile(out_html_path, contents); + console.log(`Writing ${outHtmlPath}`); + return writeFile(outHtmlPath, contents); }); } -function make_lib_files(import_format, source_maps, with_app_dir, only_legacy) { - if (!import_format) { +function makeLibFiles(importFormat, sourceMaps, withAppDir, onlyLegacy) { + if (!importFormat) { throw new Error("you must specify an import format to generate compiled noVNC libraries"); - } else if (!SUPPORTED_FORMATS.has(import_format)) { - throw new Error(`unsupported output format "${import_format}" for import/export -- only ${Array.from(SUPPORTED_FORMATS)} are supported`); + } else if (!SUPPORTED_FORMATS.has(importFormat)) { + throw new Error(`unsupported output format "${importFormat}" for import/export -- only ${Array.from(SUPPORTED_FORMATS)} are supported`); } - // NB: we need to make a copy of babel_opts, since babel sets some defaults on it - const babel_opts = () => ({ - plugins: [`transform-es2015-modules-${import_format}`], - presets: ['es2015'], + // NB: we need to make a copy of babelOpts, since babel sets some defaults on it + const babelOpts = () => ({ + plugins: [], + presets: [ + [ '@babel/preset-env', + { targets: 'ie >= 11', + modules: importFormat } ] + ], ast: false, - sourceMaps: source_maps, + sourceMaps: sourceMaps, }); // No point in duplicate files without the app, so force only converted files - if (!with_app_dir) { - only_legacy = true; + if (!withAppDir) { + onlyLegacy = true; } - let in_path; - let out_path_base; - if (with_app_dir) { - out_path_base = paths.out_dir_base; - in_path = paths.main; + let inPath; + let outPathBase; + if (withAppDir) { + outPathBase = paths.outDirBase; + inPath = paths.main; } else { - out_path_base = paths.lib_dir_base; + outPathBase = paths.libDirBase; } - const legacy_path_base = only_legacy ? out_path_base : path.join(out_path_base, 'legacy'); + const legacyPathBase = onlyLegacy ? outPathBase : path.join(outPathBase, 'legacy'); - fse.ensureDirSync(out_path_base); + fse.ensureDirSync(outPathBase); const helpers = require('./use_require_helpers'); - const helper = helpers[import_format]; + const helper = helpers[importFormat]; const outFiles = []; + const legacyFiles = []; - const handleDir = (js_only, vendor_rewrite, in_path_base, filename) => Promise.resolve() + const handleDir = (jsOnly, vendorRewrite, inPathBase, filename) => Promise.resolve() .then(() => { - if (no_copy_files.has(filename)) return; - - const out_path = path.join(out_path_base, path.relative(in_path_base, filename)); - const legacy_path = path.join(legacy_path_base, path.relative(in_path_base, filename)); + const outPath = path.join(outPathBase, path.relative(inPathBase, filename)); + const legacyPath = path.join(legacyPathBase, path.relative(inPathBase, filename)); if (path.extname(filename) !== '.js') { - if (!js_only) { - console.log(`Writing ${out_path}`); - return copy(filename, out_path); + if (!jsOnly) { + console.log(`Writing ${outPath}`); + return copy(filename, outPath); } return; // skip non-javascript files } + if (noTransformFiles.has(filename)) { + return ensureDir(path.dirname(outPath)) + .then(() => { + console.log(`Writing ${outPath}`); + return copy(filename, outPath); + }); + } + + if (onlyLegacyScripts.has(filename)) { + legacyFiles.push(legacyPath); + return ensureDir(path.dirname(legacyPath)) + .then(() => { + console.log(`Writing ${legacyPath}`); + return copy(filename, legacyPath); + }); + } + return Promise.resolve() .then(() => { - if (only_legacy && !no_transform_files.has(filename)) { + if (onlyLegacy) { return; } - return ensureDir(path.dirname(out_path)) + return ensureDir(path.dirname(outPath)) .then(() => { - console.log(`Writing ${out_path}`); - return copy(filename, out_path); + console.log(`Writing ${outPath}`); + return copy(filename, outPath); }); }) - .then(() => ensureDir(path.dirname(legacy_path))) + .then(() => ensureDir(path.dirname(legacyPath))) .then(() => { - if (no_transform_files.has(filename)) { - return; - } - - const opts = babel_opts(); + const opts = babelOpts(); if (helper && helpers.optionsOverride) { helper.optionsOverride(opts); } // Adjust for the fact that we move the core files relative // to the vendor directory - if (vendor_rewrite) { + if (vendorRewrite) { opts.plugins.push(["import-redirect", - {"root": legacy_path_base, + {"root": legacyPathBase, "redirect": { "vendor/(.+)": "./vendor/$1"}}]); } return babelTransformFile(filename, opts) .then((res) => { - console.log(`Writing ${legacy_path}`); + console.log(`Writing ${legacyPath}`); const {map} = res; let {code} = res; - if (source_maps === true) { + if (sourceMaps === true) { // append URL for external source map - code += `\n//# sourceMappingURL=${path.basename(legacy_path)}.map\n`; + code += `\n//# sourceMappingURL=${path.basename(legacyPath)}.map\n`; } - outFiles.push(`${legacy_path}`); - return writeFile(legacy_path, code) + outFiles.push(`${legacyPath}`); + return writeFile(legacyPath, code) .then(() => { - if (source_maps === true || source_maps === 'both') { - console.log(` and ${legacy_path}.map`); - outFiles.push(`${legacy_path}.map`); - return writeFile(`${legacy_path}.map`, JSON.stringify(map)); + if (sourceMaps === true || sourceMaps === 'both') { + console.log(` and ${legacyPath}.map`); + outFiles.push(`${legacyPath}.map`); + return writeFile(`${legacyPath}.map`, JSON.stringify(map)); } }); }); }); }); - if (with_app_dir && helper && helper.noCopyOverride) { - helper.noCopyOverride(paths, no_copy_files); - } - Promise.resolve() .then(() => { - const handler = handleDir.bind(null, true, false, in_path || paths.main); - const filter = (filename, stats) => !no_copy_files.has(filename); + const handler = handleDir.bind(null, true, false, inPath || paths.main); + const filter = (filename, stats) => !noCopyFiles.has(filename); return walkDir(paths.vendor, handler, filter); }) .then(() => { - const handler = handleDir.bind(null, true, !in_path, in_path || paths.core); - const filter = (filename, stats) => !no_copy_files.has(filename); + const handler = handleDir.bind(null, true, !inPath, inPath || paths.core); + const filter = (filename, stats) => !noCopyFiles.has(filename); return walkDir(paths.core, handler, filter); }) .then(() => { - if (!with_app_dir) return; - const handler = handleDir.bind(null, false, false, in_path); - const filter = (filename, stats) => !no_copy_files.has(filename); + if (!withAppDir) return; + const handler = handleDir.bind(null, false, false, inPath); + const filter = (filename, stats) => !noCopyFiles.has(filename); return walkDir(paths.app, handler, filter); }) .then(() => { - if (!with_app_dir) return; + if (!withAppDir) return; if (!helper || !helper.appWriter) { - throw new Error(`Unable to generate app for the ${import_format} format!`); + throw new Error(`Unable to generate app for the ${importFormat} format!`); } - const out_app_path = path.join(legacy_path_base, 'app.js'); - console.log(`Writing ${out_app_path}`); - return helper.appWriter(out_path_base, legacy_path_base, out_app_path) - .then((extra_scripts) => { - const rel_app_path = path.relative(out_path_base, out_app_path); - const legacy_scripts = extra_scripts.concat([rel_app_path]); - transform_html(legacy_scripts, only_legacy); + const outAppPath = path.join(legacyPathBase, 'app.js'); + console.log(`Writing ${outAppPath}`); + return helper.appWriter(outPathBase, legacyPathBase, outAppPath) + .then((extraScripts) => { + let legacyScripts = []; + + legacyFiles.forEach((file) => { + let relFilePath = path.relative(outPathBase, file); + legacyScripts.push(relFilePath); + }); + + legacyScripts = legacyScripts.concat(extraScripts); + + let relAppPath = path.relative(outPathBase, outAppPath); + legacyScripts.push(relAppPath); + + transformHtml(legacyScripts, onlyLegacy); }) .then(() => { if (!helper.removeModules) return; @@ -283,15 +292,15 @@ function make_lib_files(import_format, source_maps, with_app_dir, only_legacy) { return Promise.all(outFiles.map((filepath) => { unlink(filepath) .then(() => { - // Try to clean up any empty directories if this - // was the last file in there - const rmdir_r = dir => + // Try to clean up any empty directories if + // this was the last file in there + const rmdirR = dir => rmdir(dir) - .then(() => rmdir_r(path.dirname(dir))) + .then(() => rmdirR(path.dirname(dir))) .catch(() => { - // Assume the error was ENOTEMPTY and ignore it + // Assume the error was ENOTEMPTY and ignore it }); - return rmdir_r(path.dirname(filepath)); + return rmdirR(path.dirname(filepath)); }); })); }); @@ -303,11 +312,11 @@ function make_lib_files(import_format, source_maps, with_app_dir, only_legacy) { } if (program.clean) { - console.log(`Removing ${paths.lib_dir_base}`); - fse.removeSync(paths.lib_dir_base); + console.log(`Removing ${paths.libDirBase}`); + fse.removeSync(paths.libDirBase); - console.log(`Removing ${paths.out_dir_base}`); - fse.removeSync(paths.out_dir_base); + console.log(`Removing ${paths.outDirBase}`); + fse.removeSync(paths.outDirBase); } -make_lib_files(program.as, program.withSourceMaps, program.withApp, program.onlyLegacy); +makeLibFiles(program.as, program.withSourceMaps, program.withApp, program.onlyLegacy); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/utils/use_require_helpers.js b/jupyter_desktop/share/web/noVNC-1.2.0/utils/use_require_helpers.js index a4f99c70..8ad45726 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/utils/use_require_helpers.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/utils/use_require_helpers.js @@ -4,7 +4,7 @@ const path = require('path'); // util.promisify requires Node.js 8.x, so we have our own function promisify(original) { - return function promise_wrap() { + return function promiseWrap() { const args = Array.prototype.slice.call(arguments); return new Promise((resolve, reject) => { original.apply(this, args.concat((err, value) => { @@ -19,58 +19,42 @@ const writeFile = promisify(fs.writeFile); module.exports = { 'amd': { - appWriter: (base_out_path, script_base_path, out_path) => { + appWriter: (baseOutPath, scriptBasePath, outPath) => { // setup for requirejs - const ui_path = path.relative(base_out_path, - path.join(script_base_path, 'app', 'ui')); - return writeFile(out_path, `requirejs(["${ui_path}"], (ui) => {});`) + const uiPath = path.relative(baseOutPath, + path.join(scriptBasePath, 'app', 'ui')); + return writeFile(outPath, `requirejs(["${uiPath}"], function (ui) {});`) .then(() => { - console.log(`Please place RequireJS in ${path.join(script_base_path, 'require.js')}`); - const require_path = path.relative(base_out_path, - path.join(script_base_path, 'require.js')); - return [ require_path ]; + console.log(`Please place RequireJS in ${path.join(scriptBasePath, 'require.js')}`); + const requirePath = path.relative(baseOutPath, + path.join(scriptBasePath, 'require.js')); + return [ requirePath ]; }); }, - noCopyOverride: () => {}, }, 'commonjs': { - optionsOverride: (opts) => { - // CommonJS supports properly shifting the default export to work as normal - opts.plugins.unshift("add-module-exports"); - }, - appWriter: (base_out_path, script_base_path, out_path) => { + appWriter: (baseOutPath, scriptBasePath, outPath) => { const browserify = require('browserify'); - const b = browserify(path.join(script_base_path, 'app/ui.js'), {}); + const b = browserify(path.join(scriptBasePath, 'app/ui.js'), {}); return promisify(b.bundle).call(b) - .then(buf => writeFile(out_path, buf)) + .then(buf => writeFile(outPath, buf)) .then(() => []); }, - noCopyOverride: () => {}, removeModules: true, }, 'systemjs': { - appWriter: (base_out_path, script_base_path, out_path) => { - const ui_path = path.relative(base_out_path, - path.join(script_base_path, 'app', 'ui.js')); - return writeFile(out_path, `SystemJS.import("${ui_path}");`) + appWriter: (baseOutPath, scriptBasePath, outPath) => { + const uiPath = path.relative(baseOutPath, + path.join(scriptBasePath, 'app', 'ui.js')); + return writeFile(outPath, `SystemJS.import("${uiPath}");`) .then(() => { - console.log(`Please place SystemJS in ${path.join(script_base_path, 'system-production.js')}`); - // FIXME: Should probably be in the legacy directory - const promise_path = path.relative(base_out_path, - path.join(base_out_path, 'vendor', 'promise.js')); - const systemjs_path = path.relative(base_out_path, - path.join(script_base_path, 'system-production.js')); - return [ promise_path, systemjs_path ]; + console.log(`Please place SystemJS in ${path.join(scriptBasePath, 'system-production.js')}`); + const systemjsPath = path.relative(baseOutPath, + path.join(scriptBasePath, 'system-production.js')); + return [ systemjsPath ]; }); }, - noCopyOverride: (paths, no_copy_files) => { - no_copy_files.delete(path.join(paths.vendor, 'promise.js')); - }, }, 'umd': { - optionsOverride: (opts) => { - // umd supports properly shifting the default export to work as normal - opts.plugins.unshift("add-module-exports"); - }, }, }; diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/README.md b/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/README.md index c26867f9..a50cc37d 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/README.md +++ b/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/README.md @@ -6,8 +6,8 @@ It's based heavily on https://github.com/ModuleLoader/browser-es-module-loader, but uses WebWorkers to compile the modules in the background. -To generate, run `rollup -c` in this directory, and then run `browserify -src/babel-worker.js > dist/babel-worker.js`. +To generate, run `npx rollup -c` in this directory, and then run +`./genworker.js`. LICENSE ------- diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/dist/babel-worker.js b/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/dist/babel-worker.js index 3f9d7e07..43c80df5 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/dist/babel-worker.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/dist/babel-worker.js @@ -1,36197 +1,101079 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<]/g; -}; - -},{}],2:[function(require,module,exports){ -'use strict'; - -function assembleStyles () { - var styles = { - modifiers: { - reset: [0, 0], - bold: [1, 22], // 21 isn't widely supported and 22 does the same thing - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - colors: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39] - }, - bgColors: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49] - } - }; - - // fix humans - styles.colors.grey = styles.colors.gray; - - Object.keys(styles).forEach(function (groupName) { - var group = styles[groupName]; - - Object.keys(group).forEach(function (styleName) { - var style = group[styleName]; - - styles[styleName] = group[styleName] = { - open: '\u001b[' + style[0] + 'm', - close: '\u001b[' + style[1] + 'm' - }; - }); - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - }); - - return styles; -} +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; - } + return data; +} - var x = a.length; - var y = b.length; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; + + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } } - } - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; -} -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); + newObj.default = obj; + return newObj; } - return !!(b != null && b._isBuffer); } -// based on node assert, original notice: - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +var deprecationWarningShown = false; -var util = require('util/'); -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); +function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; } -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { - return true; + +var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + +function getMarkerLines(loc, source, opts) { + var startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + var endLoc = Object.assign({}, startLoc, loc.end); + + var _ref = opts || {}, + _ref$linesAbove = _ref.linesAbove, + linesAbove = _ref$linesAbove === void 0 ? 2 : _ref$linesAbove, + _ref$linesBelow = _ref.linesBelow, + linesBelow = _ref$linesBelow === void 0 ? 3 : _ref$linesBelow; + + var startLine = startLoc.line; + var startColumn = startLoc.column; + var endLine = endLoc.line; + var endColumn = endLoc.column; + var start = Math.max(startLine - (linesAbove + 1), 0); + var end = Math.min(source.length, endLine + linesBelow); + + if (startLine === -1) { + start = 0; } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; + + if (endLine === -1) { + end = source.length; } - return false; -} -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. -var assert = module.exports = ok; + var lineDiff = endLine - startLine; + var markerLines = {}; -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) + if (lineDiff) { + for (var i = 0; i <= lineDiff; i++) { + var lineNumber = i + startLine; -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!util.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; - } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; -} -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + var sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + var _sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, _sourceLength]; + } + } } else { - this.message = getMessage(this); - this.generatedMessage = true; + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); + return { + start: start, + end: end, + markerLines: markerLines + }; +} + +function codeFrameColumns(rawLines, loc) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts); + var chalk = (0, _highlight().getChalk)(opts); + var defs = getDefs(chalk); + + var maybeHighlight = function maybeHighlight(chalkFn, string) { + return highlighted ? chalkFn(string) : string; + }; + + var lines = rawLines.split(NEWLINE); + + var _getMarkerLines = getMarkerLines(loc, lines, opts), + start = _getMarkerLines.start, + end = _getMarkerLines.end, + markerLines = _getMarkerLines.markerLines; + + var hasColumns = loc.start && typeof loc.start.column === "number"; + var numberMaxWidth = String(end).length; + var highlightedLines = highlighted ? (0, _highlight().default)(rawLines, opts) : rawLines; + var frame = highlightedLines.split(NEWLINE).slice(start, end).map(function (line, index) { + var number = start + 1 + index; + var paddedNumber = " ".concat(number).slice(-numberMaxWidth); + var gutter = " ".concat(paddedNumber, " | "); + var hasMarker = markerLines[number]; + var lastMarkerLine = !markerLines[number + 1]; + + if (hasMarker) { + var markerLine = ""; + + if (Array.isArray(hasMarker)) { + var markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + var numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } } - this.stack = out; + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); + } else { + return " ".concat(maybeHighlight(defs.gutter, gutter)).concat(line); } - } -}; + }).join("\n"); -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); + if (opts.message && !hasColumns) { + frame = "".concat(" ".repeat(numberMaxWidth + 1)).concat(opts.message, "\n").concat(frame); + } -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); + if (highlighted) { + return chalk.reset(frame); } else { - return s; - } -} -function inspect(something) { - if (functionsHaveNames || !util.isFunction(something)) { - return util.inspect(something); + return frame; } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; -} -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); } -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. +function _default(rawLines, lineNumber, colNumber) { + var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. + if (!deprecationWarningShown) { + deprecationWarningShown = true; + var message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + var deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + + colNumber = Math.max(colNumber, 0); + var location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); } -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; +}).call(this,require('_process')) +},{"@babel/highlight":88,"_process":1054}],2:[function(require,module,exports){ +"use strict"; -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.makeStrongCache = makeStrongCache; +exports.makeWeakCache = makeWeakCache; +exports.assertSimpleType = assertSimpleType; -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); - } -}; +function makeStrongCache(handler) { + return makeCachedFunction(new Map(), handler); +} -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; +function makeWeakCache(handler) { + return makeCachedFunction(new WeakMap(), handler); +} - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); +function makeCachedFunction(callCache, handler) { + return function cachedFunction(arg, data) { + var cachedValue = callCache.get(arg); - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; - - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; - } else { - memos = memos || {actual: [], expected: []}; + if (cachedValue) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; + try { + for (var _iterator = cachedValue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref = _step.value; + var _value = _ref.value, + valid = _ref.valid; + if (valid(data)) return _value; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } } } - memos.actual.push(actual); - memos.expected.push(expected); + var cache = new CacheConfigurator(data); + var value = handler(arg, cache); + if (!cache.configured()) cache.forever(); + cache.deactivate(); - return objEquiv(actual, expected, strict, memos); - } -} + switch (cache.mode()) { + case "forever": + cachedValue = [{ + value: value, + valid: function valid() { + return true; + } + }]; + callCache.set(arg, cachedValue); + break; -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} + case "invalidate": + cachedValue = [{ + value: value, + valid: cache.validator() + }]; + callCache.set(arg, cachedValue); + break; -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; + case "valid": + if (cachedValue) { + cachedValue.push({ + value: value, + valid: cache.validator() + }); + } else { + cachedValue = [{ + value: value, + valid: cache.validator() + }]; + callCache.set(arg, cachedValue); + } + + } + + return value; + }; } -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); +var CacheConfigurator = +/*#__PURE__*/ +function () { + function CacheConfigurator(data) { + _classCallCheck(this, CacheConfigurator); -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + this._active = true; + this._never = false; + this._forever = false; + this._invalidate = false; + this._configured = false; + this._pairs = []; + this._data = data; } -}; -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); - } -} + _createClass(CacheConfigurator, [{ + key: "simple", + value: function simple() { + return makeSimpleConfigurator(this); + } + }, { + key: "mode", + value: function mode() { + if (this._never) return "never"; + if (this._forever) return "forever"; + if (this._invalidate) return "invalidate"; + return "valid"; + } + }, { + key: "forever", + value: function forever() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + if (this._never) { + throw new Error("Caching has already been configured with .never()"); + } -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); + this._forever = true; + this._configured = true; + } + }, { + key: "never", + value: function never() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; + if (this._forever) { + throw new Error("Caching has already been configured with .forever()"); + } -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + this._never = true; + this._configured = true; + } + }, { + key: "using", + value: function using(handler) { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; + if (this._never || this._forever) { + throw new Error("Caching has already been configured with .never or .forever()"); + } -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } + this._configured = true; + var key = handler(this._data); - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } + this._pairs.push([key, handler]); - try { - if (actual instanceof expected) { - return true; + return key; } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. - } + }, { + key: "invalidate", + value: function invalidate(handler) { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } - if (Error.isPrototypeOf(expected)) { - return false; + if (this._never || this._forever) { + throw new Error("Caching has already been configured with .never or .forever()"); + } + + this._invalidate = true; + this._configured = true; + var key = handler(this._data); + + this._pairs.push([key, handler]); + + return key; + } + }, { + key: "validator", + value: function validator() { + var pairs = this._pairs; + return function (data) { + return pairs.every(function (_ref2) { + var _ref3 = _slicedToArray(_ref2, 2), + key = _ref3[0], + fn = _ref3[1]; + + return key === fn(data); + }); + }; + } + }, { + key: "deactivate", + value: function deactivate() { + this._active = false; + } + }, { + key: "configured", + value: function configured() { + return this._configured; + } + }]); + + return CacheConfigurator; +}(); + +function makeSimpleConfigurator(cache) { + function cacheFn(val) { + if (typeof val === "boolean") { + if (val) cache.forever();else cache.never(); + return; + } + + return cache.using(function () { + return assertSimpleType(val()); + }); } - return expected.call({}, actual) === true; + cacheFn.forever = function () { + return cache.forever(); + }; + + cacheFn.never = function () { + return cache.never(); + }; + + cacheFn.using = function (cb) { + return cache.using(function () { + return assertSimpleType(cb()); + }); + }; + + cacheFn.invalidate = function (cb) { + return cache.invalidate(function () { + return assertSimpleType(cb()); + }); + }; + + return cacheFn; } -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; +function assertSimpleType(value) { + if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") { + throw new Error("Cache keys must be either string, boolean, number, null, or undefined."); } - return error; + + return value; } -function _throws(shouldThrow, block, expected, message) { - var actual; +},{}],3:[function(require,module,exports){ +"use strict"; - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } - if (typeof expected === 'string') { - message = expected; - expected = null; - } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } - actual = _tryBlock(block); +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildPresetChain = buildPresetChain; +exports.buildRootChain = buildRootChain; +exports.buildPresetChainWalker = void 0; - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && util.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; +function _path() { + var data = _interopRequireDefault(require("path")); - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); - } + _path = function _path() { + return data; + }; - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } + return data; } -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); +function _debug() { + var data = _interopRequireDefault(require("debug")); -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); -}; + _debug = function _debug() { + return data; + }; -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; + return data; +} -assert.ifError = function(err) { if (err) throw err; }; +var _options = require("./validation/options"); -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; +var _patternToRegex = _interopRequireDefault(require("./pattern-to-regex")); -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":560}],4:[function(require,module,exports){ -"use strict"; +var _files = require("./files"); -exports.__esModule = true; +var _caching = require("./caching"); -exports.default = function (rawLines, lineNumber, colNumber) { - var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; +var _configDescriptors = require("./config-descriptors"); - colNumber = Math.max(colNumber, 0); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - var highlighted = opts.highlightCode && _chalk2.default.supportsColor || opts.forceColor; - var chalk = _chalk2.default; - if (opts.forceColor) { - chalk = new _chalk2.default.constructor({ enabled: true }); - } - var maybeHighlight = function maybeHighlight(chalkFn, string) { - return highlighted ? chalkFn(string) : string; +var debug = (0, _debug().default)("babel:config:config-chain"); + +function buildPresetChain(arg, context) { + var chain = buildPresetChainWalker(arg, context); + if (!chain) return null; + return { + plugins: dedupDescriptors(chain.plugins), + presets: dedupDescriptors(chain.presets), + options: chain.options.map(function (o) { + return normalizeOptions(o); + }) }; - var defs = getDefs(chalk); - if (highlighted) rawLines = highlight(defs, rawLines); +} - var linesAbove = opts.linesAbove || 2; - var linesBelow = opts.linesBelow || 3; +var buildPresetChainWalker = makeChainWalker({ + init: function init(arg) { + return arg; + }, + root: function root(preset) { + return loadPresetDescriptors(preset); + }, + env: function env(preset, envName) { + return loadPresetEnvDescriptors(preset)(envName); + }, + overrides: function overrides(preset, index) { + return loadPresetOverridesDescriptors(preset)(index); + }, + overridesEnv: function overridesEnv(preset, index, envName) { + return loadPresetOverridesEnvDescriptors(preset)(index)(envName); + } +}); +exports.buildPresetChainWalker = buildPresetChainWalker; +var loadPresetDescriptors = (0, _caching.makeWeakCache)(function (preset) { + return buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors); +}); +var loadPresetEnvDescriptors = (0, _caching.makeWeakCache)(function (preset) { + return (0, _caching.makeStrongCache)(function (envName) { + return buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName); + }); +}); +var loadPresetOverridesDescriptors = (0, _caching.makeWeakCache)(function (preset) { + return (0, _caching.makeStrongCache)(function (index) { + return buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index); + }); +}); +var loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCache)(function (preset) { + return (0, _caching.makeStrongCache)(function (index) { + return (0, _caching.makeStrongCache)(function (envName) { + return buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName); + }); + }); +}); - var lines = rawLines.split(NEWLINE); - var start = Math.max(lineNumber - (linesAbove + 1), 0); - var end = Math.min(lines.length, lineNumber + linesBelow); +function buildRootChain(opts, context) { + var programmaticChain = loadProgrammaticChain({ + options: opts, + dirname: context.cwd + }, context); + if (!programmaticChain) return null; + var configFile; - if (!lineNumber && !colNumber) { - start = 0; - end = lines.length; + if (typeof opts.configFile === "string") { + configFile = (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller); + } else if (opts.configFile !== false) { + configFile = (0, _files.findRootConfig)(context.root, context.envName, context.caller); } - var numberMaxWidth = String(end).length; + var babelrc = opts.babelrc, + babelrcRoots = opts.babelrcRoots; + var babelrcRootsDirectory = context.cwd; + var configFileChain = emptyChain(); - var frame = lines.slice(start, end).map(function (line, index) { - var number = start + 1 + index; - var paddedNumber = (" " + number).slice(-numberMaxWidth); - var gutter = " " + paddedNumber + " | "; - if (number === lineNumber) { - var markerLine = ""; - if (colNumber) { - var markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " "); - markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^")].join(""); - } - return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); - } else { - return " " + maybeHighlight(defs.gutter, gutter) + line; + if (configFile) { + var validatedFile = validateConfigFile(configFile); + var result = loadFileChain(validatedFile, context); + if (!result) return null; + + if (babelrc === undefined) { + babelrc = validatedFile.options.babelrc; } - }).join("\n"); - if (highlighted) { - return chalk.reset(frame); - } else { - return frame; - } -}; + if (babelrcRoots === undefined) { + babelrcRootsDirectory = validatedFile.dirname; + babelrcRoots = validatedFile.options.babelrcRoots; + } -var _jsTokens = require("js-tokens"); + mergeChain(configFileChain, result); + } -var _jsTokens2 = _interopRequireDefault(_jsTokens); + var pkgData = typeof context.filename === "string" ? (0, _files.findPackageData)(context.filename) : null; + var ignoreFile, babelrcFile; + var fileChain = emptyChain(); -var _esutils = require("esutils"); + if ((babelrc === true || babelrc === undefined) && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) { + var _ref = (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller); -var _esutils2 = _interopRequireDefault(_esutils); + ignoreFile = _ref.ignore; + babelrcFile = _ref.config; -var _chalk = require("chalk"); + if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { + return null; + } -var _chalk2 = _interopRequireDefault(_chalk); + if (babelrcFile) { + var _result = loadFileChain(validateBabelrcFile(babelrcFile), context); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!_result) return null; + mergeChain(fileChain, _result); + } + } -function getDefs(chalk) { + var chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); return { - keyword: chalk.cyan, - capitalized: chalk.yellow, - jsx_tag: chalk.yellow, - punctuator: chalk.yellow, - - number: chalk.magenta, - string: chalk.green, - regex: chalk.magenta, - comment: chalk.grey, - invalid: chalk.white.bgRed.bold, - gutter: chalk.grey, - marker: chalk.red.bold + plugins: dedupDescriptors(chain.plugins), + presets: dedupDescriptors(chain.presets), + options: chain.options.map(function (o) { + return normalizeOptions(o); + }), + ignore: ignoreFile || undefined, + babelrc: babelrcFile || undefined, + config: configFile || undefined }; } -var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; - -var JSX_TAG = /^[a-z][\w-]*$/i; - -var BRACKET = /^[()\[\]{}]$/; - -function getTokenType(match) { - var _match$slice = match.slice(-2), - offset = _match$slice[0], - text = _match$slice[1]; - - var token = (0, _jsTokens.matchToToken)(match); - - if (token.type === "name") { - if (_esutils2.default.keyword.isReservedWordES6(token.value)) { - return "keyword"; - } - - if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " 2 && arguments[2] !== undefined ? arguments[2] : new Set(); + var dirname = input.dirname; + var flattenedConfigs = []; + var rootOpts = root(input); -var util = _interopRequireWildcard(_util); + if (configIsApplicable(rootOpts, dirname, context)) { + flattenedConfigs.push(rootOpts); + var envOpts = env(input, context.envName); -var _babelMessages = require("babel-messages"); + if (envOpts && configIsApplicable(envOpts, dirname, context)) { + flattenedConfigs.push(envOpts); + } -var messages = _interopRequireWildcard(_babelMessages); + (rootOpts.options.overrides || []).forEach(function (_, index) { + var overrideOps = overrides(input, index); -var _babelTypes = require("babel-types"); + if (configIsApplicable(overrideOps, dirname, context)) { + flattenedConfigs.push(overrideOps); + var overrideEnvOpts = overridesEnv(input, index, context.envName); -var t = _interopRequireWildcard(_babelTypes); + if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) { + flattenedConfigs.push(overrideEnvOpts); + } + } + }); + } -var _babelTraverse = require("babel-traverse"); + if (flattenedConfigs.some(function (_ref7) { + var _ref7$options = _ref7.options, + ignore = _ref7$options.ignore, + only = _ref7$options.only; + return shouldIgnore(context, ignore, only, dirname); + })) { + return null; + } -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + var chain = emptyChain(); -var _optionManager = require("../transformation/file/options/option-manager"); + for (var _i = 0, _flattenedConfigs = flattenedConfigs; _i < _flattenedConfigs.length; _i++) { + var op = _flattenedConfigs[_i]; -var _optionManager2 = _interopRequireDefault(_optionManager); + if (!mergeExtendsChain(chain, op.options, dirname, context, files)) { + return null; + } -var _pipeline = require("../transformation/pipeline"); + mergeChainOpts(chain, op); + } -var _pipeline2 = _interopRequireDefault(_pipeline); + return chain; + }; +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function mergeExtendsChain(chain, opts, dirname, context, files) { + if (opts.extends === undefined) return true; + var file = (0, _files.loadConfig)(opts.extends, dirname, context.envName, context.caller); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (files.has(file)) { + throw new Error("Configuration cycle detected loading ".concat(file.filepath, ".\n") + "File already loaded following the config chain:\n" + Array.from(files, function (file) { + return " - ".concat(file.filepath); + }).join("\n")); + } -exports.util = util; -exports.messages = messages; -exports.types = t; -exports.traverse = _babelTraverse2.default; -exports.OptionManager = _optionManager2.default; -function Plugin(alias) { - throw new Error("The (" + alias + ") Babel 5 plugin is being run with Babel 6."); + files.add(file); + var fileChain = loadFileChain(validateExtendFile(file), context, files); + files.delete(file); + if (!fileChain) return false; + mergeChain(chain, fileChain); + return true; } -exports.Pipeline = _pipeline2.default; +function mergeChain(target, source) { + var _target$options, _target$plugins, _target$presets; + (_target$options = target.options).push.apply(_target$options, _toConsumableArray(source.options)); -var pipeline = new _pipeline2.default(); -var analyse = exports.analyse = pipeline.analyse.bind(pipeline); -var transform = exports.transform = pipeline.transform.bind(pipeline); -var transformFromAst = exports.transformFromAst = pipeline.transformFromAst.bind(pipeline); + (_target$plugins = target.plugins).push.apply(_target$plugins, _toConsumableArray(source.plugins)); -function transformFile(filename, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; - } + (_target$presets = target.presets).push.apply(_target$presets, _toConsumableArray(source.presets)); - opts.filename = filename; + return target; +} - _fs2.default.readFile(filename, function (err, code) { - var result = void 0; +function mergeChainOpts(target, _ref8) { + var _target$plugins2, _target$presets2; - if (!err) { - try { - result = transform(code, opts); - } catch (_err) { - err = _err; - } - } + var options = _ref8.options, + plugins = _ref8.plugins, + presets = _ref8.presets; + target.options.push(options); - if (err) { - callback(err); - } else { - callback(null, result); - } - }); -} + (_target$plugins2 = target.plugins).push.apply(_target$plugins2, _toConsumableArray(plugins())); -function transformFileSync(filename) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + (_target$presets2 = target.presets).push.apply(_target$presets2, _toConsumableArray(presets())); - opts.filename = filename; - return transform(_fs2.default.readFileSync(filename, "utf8"), opts); + return target; } -},{"../../package":32,"../helpers/resolve-plugin":12,"../helpers/resolve-preset":13,"../tools/build-external-helpers":16,"../transformation/file":17,"../transformation/file/options/config":21,"../transformation/file/options/option-manager":23,"../transformation/pipeline":28,"../util":31,"babel-messages":61,"babel-template":114,"babel-traverse":118,"babel-types":151,"fs":159}],7:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.default = getPossiblePluginNames; -function getPossiblePluginNames(pluginName) { - return ["babel-plugin-" + pluginName, pluginName]; +function emptyChain() { + return { + options: [], + presets: [], + plugins: [] + }; } -module.exports = exports["default"]; -},{}],8:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = getPossiblePresetNames; -function getPossiblePresetNames(presetName) { - var possibleNames = ["babel-preset-" + presetName, presetName]; - var matches = presetName.match(/^(@[^/]+)\/(.+)$/); - if (matches) { - var orgName = matches[1], - presetPath = matches[2]; +function normalizeOptions(opts) { + var options = Object.assign({}, opts); + delete options.extends; + delete options.env; + delete options.overrides; + delete options.plugins; + delete options.presets; + delete options.passPerPreset; + delete options.ignore; + delete options.only; + delete options.test; + delete options.include; + delete options.exclude; - possibleNames.push(orgName + "/babel-preset-" + presetPath); + if (Object.prototype.hasOwnProperty.call(options, "sourceMap")) { + options.sourceMaps = options.sourceMap; + delete options.sourceMap; } - return possibleNames; + return options; } -module.exports = exports["default"]; -},{}],9:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -var _getIterator3 = _interopRequireDefault(_getIterator2); +function dedupDescriptors(items) { + var map = new Map(); + var descriptors = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; -exports.default = function (dest, src) { - if (!dest || !src) return; - - return (0, _mergeWith2.default)(dest, src, function (a, b) { - if (b && Array.isArray(a)) { - var newArray = b.slice(0); + try { + for (var _iterator = items[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var item = _step.value; - for (var _iterator = a, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (typeof item.value === "function") { + var fnKey = item.value; + var nameMap = map.get(fnKey); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + if (!nameMap) { + nameMap = new Map(); + map.set(fnKey, nameMap); } - var item = _ref; + var desc = nameMap.get(item.name); - if (newArray.indexOf(item) < 0) { - newArray.push(item); + if (!desc) { + desc = { + value: item + }; + descriptors.push(desc); + if (!item.ownPass) nameMap.set(item.name, desc); + } else { + desc.value = item; } + } else { + descriptors.push({ + value: item + }); } - - return newArray; } - }); -}; - -var _mergeWith = require("lodash/mergeWith"); - -var _mergeWith2 = _interopRequireDefault(_mergeWith); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"lodash/mergeWith":502}],10:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (ast, comments, tokens) { - if (ast) { - if (ast.type === "Program") { - return t.file(ast, comments || [], tokens || []); - } else if (ast.type === "File") { - return ast; + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } } - throw new Error("Not a valid ast?"); -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -module.exports = exports["default"]; -},{"babel-types":151}],11:[function(require,module,exports){ -"use strict"; + return descriptors.reduce(function (acc, desc) { + acc.push(desc.value); + return acc; + }, []); +} -exports.__esModule = true; -exports.default = resolveFromPossibleNames; +function configIsApplicable(_ref9, dirname, context) { + var options = _ref9.options; + return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname)); +} -var _resolve = require("./resolve"); +function configFieldIsApplicable(context, test, dirname) { + var patterns = Array.isArray(test) ? test : [test]; + return matchesPatterns(context, patterns, dirname); +} -var _resolve2 = _interopRequireDefault(_resolve); +function shouldIgnore(context, ignore, only, dirname) { + if (ignore && matchesPatterns(context, ignore, dirname)) { + debug("Ignored %o because it matched one of %O from %o", context.filename, ignore, dirname); + return true; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (only && !matchesPatterns(context, only, dirname)) { + debug("Ignored %o because it failed to match one of %O from %o", context.filename, only, dirname); + return true; + } -function resolveFromPossibleNames(possibleNames, dirname) { - return possibleNames.reduce(function (accum, curr) { - return accum || (0, _resolve2.default)(curr, dirname); - }, null); + return false; } -module.exports = exports["default"]; -},{"./resolve":14}],12:[function(require,module,exports){ -(function (process){ -"use strict"; -exports.__esModule = true; -exports.default = resolvePlugin; +function matchesPatterns(context, patterns, dirname) { + return patterns.some(function (pattern) { + return matchPattern(pattern, dirname, context.filename, context); + }); +} -var _resolveFromPossibleNames = require("./resolve-from-possible-names"); +function matchPattern(pattern, dirname, pathToTest, context) { + if (typeof pattern === "function") { + return !!pattern(pathToTest, { + dirname: dirname, + envName: context.envName, + caller: context.caller + }); + } -var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); + if (typeof pathToTest !== "string") { + throw new Error("Configuration contains string/RegExp pattern, but no filename was passed to Babel"); + } -var _getPossiblePluginNames = require("./get-possible-plugin-names"); + if (typeof pattern === "string") { + pattern = (0, _patternToRegex.default)(pattern, dirname); + } -var _getPossiblePluginNames2 = _interopRequireDefault(_getPossiblePluginNames); + return pattern.test(pathToTest); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +},{"./caching":2,"./config-descriptors":4,"./files":5,"./pattern-to-regex":12,"./validation/options":16,"debug":34,"path":1052}],4:[function(require,module,exports){ +"use strict"; -function resolvePlugin(pluginName) { - var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePluginNames2.default)(pluginName), dirname); -} -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./get-possible-plugin-names":7,"./resolve-from-possible-names":11,"_process":525}],13:[function(require,module,exports){ -(function (process){ -"use strict"; +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -exports.__esModule = true; -exports.default = resolvePreset; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -var _resolveFromPossibleNames = require("./resolve-from-possible-names"); +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -var _getPossiblePresetNames = require("./get-possible-preset-names"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createCachedDescriptors = createCachedDescriptors; +exports.createUncachedDescriptors = createUncachedDescriptors; +exports.createDescriptor = createDescriptor; -var _getPossiblePresetNames2 = _interopRequireDefault(_getPossiblePresetNames); +var _files = require("./files"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _item = require("./item"); -function resolvePreset(presetName) { - var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); +var _caching = require("./caching"); - return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePresetNames2.default)(presetName), dirname); +function isEqualDescriptor(a, b) { + return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved); } -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./get-possible-preset-names":8,"./resolve-from-possible-names":11,"_process":525}],14:[function(require,module,exports){ -(function (process){ -"use strict"; -exports.__esModule = true; +function createCachedDescriptors(dirname, options, alias) { + var plugins = options.plugins, + presets = options.presets, + passPerPreset = options.passPerPreset; + return { + options: options, + plugins: plugins ? function () { + return createCachedPluginDescriptors(plugins, dirname)(alias); + } : function () { + return []; + }, + presets: presets ? function () { + return createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset); + } : function () { + return []; + } + }; +} -var _typeof2 = require("babel-runtime/helpers/typeof"); +function createUncachedDescriptors(dirname, options, alias) { + var _plugins; -var _typeof3 = _interopRequireDefault(_typeof2); + var _presets; -exports.default = function (loc) { - var relative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); + return { + options: options, + plugins: function plugins() { + if (!_plugins) { + _plugins = createPluginDescriptors(options.plugins || [], dirname, alias); + } - if ((typeof _module2.default === "undefined" ? "undefined" : (0, _typeof3.default)(_module2.default)) === "object") return null; + return _plugins; + }, + presets: function presets() { + if (!_presets) { + _presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset); + } - var relativeMod = relativeModules[relative]; + return _presets; + } + }; +} - if (!relativeMod) { - relativeMod = new _module2.default(); +var PRESET_DESCRIPTOR_CACHE = new WeakMap(); +var createCachedPresetDescriptors = (0, _caching.makeWeakCache)(function (items, cache) { + var dirname = cache.using(function (dir) { + return dir; + }); + return (0, _caching.makeStrongCache)(function (alias) { + return (0, _caching.makeStrongCache)(function (passPerPreset) { + return createPresetDescriptors(items, dirname, alias, passPerPreset).map(function (desc) { + return loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc); + }); + }); + }); +}); +var PLUGIN_DESCRIPTOR_CACHE = new WeakMap(); +var createCachedPluginDescriptors = (0, _caching.makeWeakCache)(function (items, cache) { + var dirname = cache.using(function (dir) { + return dir; + }); + return (0, _caching.makeStrongCache)(function (alias) { + return createPluginDescriptors(items, dirname, alias).map(function (desc) { + return loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc); + }); + }); +}); +var DEFAULT_OPTIONS = {}; - var filename = _path2.default.join(relative, ".babelrc"); - relativeMod.id = filename; - relativeMod.filename = filename; +function loadCachedDescriptor(cache, desc) { + var value = desc.value, + _desc$options = desc.options, + options = _desc$options === void 0 ? DEFAULT_OPTIONS : _desc$options; + if (options === false) return desc; + var cacheByOptions = cache.get(value); - relativeMod.paths = _module2.default._nodeModulePaths(relative); - relativeModules[relative] = relativeMod; + if (!cacheByOptions) { + cacheByOptions = new WeakMap(); + cache.set(value, cacheByOptions); } - try { - return _module2.default._resolveFilename(loc, relativeMod); - } catch (err) { - return null; - } -}; + var possibilities = cacheByOptions.get(options); -var _module = require("module"); + if (!possibilities) { + possibilities = []; + cacheByOptions.set(options, possibilities); + } -var _module2 = _interopRequireDefault(_module); + if (possibilities.indexOf(desc) === -1) { + var matches = possibilities.filter(function (possibility) { + return isEqualDescriptor(possibility, desc); + }); -var _path = require("path"); + if (matches.length > 0) { + return matches[0]; + } -var _path2 = _interopRequireDefault(_path); + possibilities.push(desc); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return desc; +} -var relativeModules = {}; +function createPresetDescriptors(items, dirname, alias, passPerPreset) { + return createDescriptors("preset", items, dirname, alias, passPerPreset); +} -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"_process":525,"babel-runtime/helpers/typeof":113,"module":159,"path":522}],15:[function(require,module,exports){ -"use strict"; +function createPluginDescriptors(items, dirname, alias) { + return createDescriptors("plugin", items, dirname, alias); +} -exports.__esModule = true; +function createDescriptors(type, items, dirname, alias, ownPass) { + var descriptors = items.map(function (item, index) { + return createDescriptor(item, dirname, { + type: type, + alias: "".concat(alias, "$").concat(index), + ownPass: !!ownPass + }); + }); + assertNoDuplicates(descriptors); + return descriptors; +} -var _map = require("babel-runtime/core-js/map"); +function createDescriptor(pair, dirname, _ref) { + var type = _ref.type, + alias = _ref.alias, + ownPass = _ref.ownPass; + var desc = (0, _item.getItemDescriptor)(pair); -var _map2 = _interopRequireDefault(_map); + if (desc) { + return desc; + } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + var name; + var options; + var value = pair; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + if (Array.isArray(value)) { + if (value.length === 3) { + var _value = value; -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + var _value2 = _slicedToArray(_value, 3); -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + value = _value2[0]; + options = _value2[1]; + name = _value2[2]; + } else { + var _value3 = value; -var _inherits2 = require("babel-runtime/helpers/inherits"); + var _value4 = _slicedToArray(_value3, 2); -var _inherits3 = _interopRequireDefault(_inherits2); + value = _value4[0]; + options = _value4[1]; + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var file = undefined; + var filepath = null; -var Store = function (_Map) { - (0, _inherits3.default)(Store, _Map); + if (typeof value === "string") { + if (typeof type !== "string") { + throw new Error("To resolve a string-based item, the type of item must be given"); + } - function Store() { - (0, _classCallCheck3.default)(this, Store); + var resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset; + var request = value; - var _this = (0, _possibleConstructorReturn3.default)(this, _Map.call(this)); + var _resolver = resolver(value, dirname); - _this.dynamicData = {}; - return _this; + filepath = _resolver.filepath; + value = _resolver.value; + file = { + request: request, + resolved: filepath + }; } - Store.prototype.setDynamic = function setDynamic(key, fn) { - this.dynamicData[key] = fn; - }; + if (!value) { + throw new Error("Unexpected falsy value: ".concat(String(value))); + } - Store.prototype.get = function get(key) { - if (this.has(key)) { - return _Map.prototype.get.call(this, key); + if (_typeof(value) === "object" && value.__esModule) { + if (value.default) { + value = value.default; } else { - if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) { - var val = this.dynamicData[key](); - this.set(key, val); - return val; - } + throw new Error("Must export a default export when using ES6 modules."); } - }; - - return Store; -}(_map2.default); - -exports.default = Store; -module.exports = exports["default"]; -},{"babel-runtime/core-js/map":97,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112}],16:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (whitelist) { - var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "global"; - - var namespace = t.identifier("babelHelpers"); - - var builder = function builder(body) { - return buildHelpers(body, namespace, whitelist); - }; - - var tree = void 0; - - var build = { - global: buildGlobal, - umd: buildUmd, - var: buildVar - }[outputType]; - - if (build) { - tree = build(namespace, builder); - } else { - throw new Error(messages.get("unsupportedOutputType", outputType)); } - return (0, _babelGenerator2.default)(tree).code; -}; - -var _babelHelpers = require("babel-helpers"); - -var helpers = _interopRequireWildcard(_babelHelpers); - -var _babelGenerator = require("babel-generator"); - -var _babelGenerator2 = _interopRequireDefault(_babelGenerator); + if (_typeof(value) !== "object" && typeof value !== "function") { + throw new Error("Unsupported format: ".concat(_typeof(value), ". Expected an object or a function.")); + } -var _babelMessages = require("babel-messages"); + if (filepath !== null && _typeof(value) === "object" && value) { + throw new Error("Plugin/Preset files are not allowed to export objects, only functions. In ".concat(filepath)); + } -var messages = _interopRequireWildcard(_babelMessages); + return { + name: name, + alias: filepath || alias, + value: value, + options: options, + dirname: dirname, + ownPass: ownPass, + file: file + }; +} -var _babelTemplate = require("babel-template"); +function assertNoDuplicates(items) { + var map = new Map(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + try { + var _loop = function _loop() { + var item = _step.value; + if (typeof item.value !== "function") return "continue"; + var nameMap = map.get(item.value); -var _babelTypes = require("babel-types"); + if (!nameMap) { + nameMap = new Set(); + map.set(item.value, nameMap); + } -var t = _interopRequireWildcard(_babelTypes); + if (nameMap.has(item.name)) { + var conflicts = items.filter(function (i) { + return i.value === item.value; + }); + throw new Error(["Duplicate plugin/preset detected.", "If you'd like to use two separate instances of a plugin,", "they need separate names, e.g.", "", " plugins: [", " ['some-plugin', {}],", " ['some-plugin', {}, 'some unique name'],", " ]", "", "Duplicates detected are:", "".concat(JSON.stringify(conflicts, null, 2))].join("\n")); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + nameMap.add(item.name); + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + for (var _iterator = items[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ret = _loop(); -var buildUmdWrapper = (0, _babelTemplate2.default)("\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n"); + if (_ret === "continue") continue; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } +} -function buildGlobal(namespace, builder) { - var body = []; - var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); - var tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]); +},{"./caching":2,"./files":5,"./item":10}],5:[function(require,module,exports){ +"use strict"; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])))])); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findConfigUpwards = findConfigUpwards; +exports.findPackageData = findPackageData; +exports.findRelativeConfig = findRelativeConfig; +exports.findRootConfig = findRootConfig; +exports.loadConfig = loadConfig; +exports.resolvePlugin = resolvePlugin; +exports.resolvePreset = resolvePreset; +exports.loadPlugin = loadPlugin; +exports.loadPreset = loadPreset; + +function findConfigUpwards(rootDir) { + return null; +} - builder(body); +function findPackageData(filepath) { + return { + filepath: filepath, + directories: [], + pkg: null, + isPackage: false + }; +} - return tree; +function findRelativeConfig(pkgData, envName, caller) { + return { + pkg: null, + config: null, + ignore: null + }; } -function buildUmd(namespace, builder) { - var body = []; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.identifier("global"))])); +function findRootConfig(dirname, envName, caller) { + return null; +} - builder(body); +function loadConfig(name, dirname, envName, caller) { + throw new Error("Cannot load ".concat(name, " relative to ").concat(dirname, " in a browser")); +} - return t.program([buildUmdWrapper({ - FACTORY_PARAMETERS: t.identifier("global"), - BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression([])), - COMMON_ARGUMENTS: t.identifier("exports"), - AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]), - FACTORY_BODY: body, - UMD_ROOT: t.identifier("this") - })]); +function resolvePlugin(name, dirname) { + return null; } -function buildVar(namespace, builder) { - var body = []; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.objectExpression([]))])); - builder(body); - body.push(t.expressionStatement(namespace)); - return t.program(body); +function resolvePreset(name, dirname) { + return null; } -function buildHelpers(body, namespace, whitelist) { - helpers.list.forEach(function (name) { - if (whitelist && whitelist.indexOf(name) < 0) return; +function loadPlugin(name, dirname) { + throw new Error("Cannot load plugin ".concat(name, " relative to ").concat(dirname, " in a browser")); +} - var key = t.identifier(name); - body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name)))); - }); +function loadPreset(name, dirname) { + throw new Error("Cannot load preset ".concat(name, " relative to ").concat(dirname, " in a browser")); } -module.exports = exports["default"]; -},{"babel-generator":44,"babel-helpers":60,"babel-messages":61,"babel-template":114,"babel-types":151}],17:[function(require,module,exports){ -(function (process){ + +},{}],6:[function(require,module,exports){ "use strict"; -exports.__esModule = true; -exports.File = undefined; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } -var _getIterator3 = _interopRequireDefault(_getIterator2); +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } -var _create = require("babel-runtime/core-js/object/create"); +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -var _create2 = _interopRequireDefault(_create); +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } -var _assign = require("babel-runtime/core-js/object/assign"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadFullConfig; -var _assign2 = _interopRequireDefault(_assign); +var _util = require("./util"); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +var context = _interopRequireWildcard(require("../index")); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +var _plugin = _interopRequireDefault(require("./plugin")); -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); +var _item = require("./item"); -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); +var _configChain = require("./config-chain"); -var _inherits2 = require("babel-runtime/helpers/inherits"); +function _traverse() { + var data = _interopRequireDefault(require("@babel/traverse")); -var _inherits3 = _interopRequireDefault(_inherits2); + _traverse = function _traverse() { + return data; + }; -var _babelHelpers = require("babel-helpers"); + return data; +} -var _babelHelpers2 = _interopRequireDefault(_babelHelpers); +var _caching = require("./caching"); -var _metadata = require("./metadata"); +var _options = require("./validation/options"); -var metadataVisitor = _interopRequireWildcard(_metadata); +var _plugins = require("./validation/plugins"); -var _convertSourceMap = require("convert-source-map"); +var _configApi = _interopRequireDefault(require("./helpers/config-api")); -var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap); +var _partial = _interopRequireDefault(require("./partial")); -var _optionManager = require("./options/option-manager"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} -var _optionManager2 = _interopRequireDefault(_optionManager); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -var _pluginPass = require("../plugin-pass"); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; -var _pluginPass2 = _interopRequireDefault(_pluginPass); + return cache; +} -var _babelTraverse = require("babel-traverse"); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + var cache = _getRequireWildcardCache(); -var _sourceMap = require("source-map"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var _sourceMap2 = _interopRequireDefault(_sourceMap); + var newObj = {}; -var _babelGenerator = require("babel-generator"); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -var _babelGenerator2 = _interopRequireDefault(_babelGenerator); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -var _babelCodeFrame = require("babel-code-frame"); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } -var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); + newObj.default = obj; -var _defaults = require("lodash/defaults"); + if (cache) { + cache.set(obj, newObj); + } -var _defaults2 = _interopRequireDefault(_defaults); + return newObj; +} -var _logger = require("./logger"); +function loadFullConfig(inputOpts) { + var result = (0, _partial.default)(inputOpts); -var _logger2 = _interopRequireDefault(_logger); + if (!result) { + return null; + } -var _store = require("../../store"); + var options = result.options, + context = result.context; + var optionDefaults = {}; + var passes = [[]]; -var _store2 = _interopRequireDefault(_store); + try { + var plugins = options.plugins, + presets = options.presets; -var _babylon = require("babylon"); + if (!plugins || !presets) { + throw new Error("Assertion failure - plugins and presets exist"); + } -var _util = require("../../util"); + var ignored = function recurseDescriptors(config, pass) { + var plugins = config.plugins.reduce(function (acc, descriptor) { + if (descriptor.options !== false) { + acc.push(loadPluginDescriptor(descriptor, context)); + } -var util = _interopRequireWildcard(_util); + return acc; + }, []); + var presets = config.presets.reduce(function (acc, descriptor) { + if (descriptor.options !== false) { + acc.push({ + preset: loadPresetDescriptor(descriptor, context), + pass: descriptor.ownPass ? [] : pass + }); + } -var _path = require("path"); + return acc; + }, []); -var _path2 = _interopRequireDefault(_path); + if (presets.length > 0) { + passes.splice.apply(passes, [1, 0].concat(_toConsumableArray(presets.map(function (o) { + return o.pass; + }).filter(function (p) { + return p !== pass; + })))); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; -var _babelTypes = require("babel-types"); + try { + for (var _iterator = presets[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref = _step.value; + var preset = _ref.preset, + _pass = _ref.pass; + if (!preset) return true; + + var _ignored = recurseDescriptors({ + plugins: preset.plugins, + presets: preset.presets + }, _pass); + + if (_ignored) return true; + preset.options.forEach(function (opts) { + (0, _util.mergeOptions)(optionDefaults, opts); + }); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } -var t = _interopRequireWildcard(_babelTypes); + if (plugins.length > 0) { + pass.unshift.apply(pass, _toConsumableArray(plugins)); + } + }({ + plugins: plugins.map(function (item) { + var desc = (0, _item.getItemDescriptor)(item); -var _resolve = require("../../helpers/resolve"); + if (!desc) { + throw new Error("Assertion failure - must be config item"); + } -var _resolve2 = _interopRequireDefault(_resolve); + return desc; + }), + presets: presets.map(function (item) { + var desc = (0, _item.getItemDescriptor)(item); -var _blockHoist = require("../internal-plugins/block-hoist"); + if (!desc) { + throw new Error("Assertion failure - must be config item"); + } -var _blockHoist2 = _interopRequireDefault(_blockHoist); + return desc; + }) + }, passes[0]); -var _shadowFunctions = require("../internal-plugins/shadow-functions"); + if (ignored) return null; + } catch (e) { + if (!/^\[BABEL\]/.test(e.message)) { + e.message = "[BABEL] ".concat(context.filename || "unknown", ": ").concat(e.message); + } -var _shadowFunctions2 = _interopRequireDefault(_shadowFunctions); + throw e; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var opts = optionDefaults; + (0, _util.mergeOptions)(opts, options); + opts.plugins = passes[0]; + opts.presets = passes.slice(1).filter(function (plugins) { + return plugins.length > 0; + }).map(function (plugins) { + return { + plugins: plugins + }; + }); + opts.passPerPreset = opts.presets.length > 0; + return { + options: opts, + passes: passes + }; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var loadDescriptor = (0, _caching.makeWeakCache)(function (_ref2, cache) { + var value = _ref2.value, + options = _ref2.options, + dirname = _ref2.dirname, + alias = _ref2.alias; + if (options === false) throw new Error("Assertion failure"); + options = options || {}; + var item = value; -var shebangRegex = /^#!.*/; + if (typeof value === "function") { + var api = Object.assign({}, context, {}, (0, _configApi.default)(cache)); -var INTERNAL_PLUGINS = [[_blockHoist2.default], [_shadowFunctions2.default]]; + try { + item = value(api, options, dirname); + } catch (e) { + if (alias) { + e.message += " (While processing: ".concat(JSON.stringify(alias), ")"); + } -var errorVisitor = { - enter: function enter(path, state) { - var loc = path.node.loc; - if (loc) { - state.loc = loc; - path.stop(); + throw e; } } -}; -var File = function (_Store) { - (0, _inherits3.default)(File, _Store); - - function File() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var pipeline = arguments[1]; - (0, _classCallCheck3.default)(this, File); + if (!item || _typeof(item) !== "object") { + throw new Error("Plugin/Preset did not return an object."); + } - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + if (typeof item.then === "function") { + throw new Error("You appear to be using an async plugin, " + "which your current version of Babel does not support. " + "If you're using a published plugin, " + "you may need to upgrade your @babel/core version."); + } - _this.pipeline = pipeline; + return { + value: item, + options: options, + dirname: dirname, + alias: alias + }; +}); - _this.log = new _logger2.default(_this, opts.filename || "unknown"); - _this.opts = _this.initOptions(opts); +function loadPluginDescriptor(descriptor, context) { + if (descriptor.value instanceof _plugin.default) { + if (descriptor.options) { + throw new Error("Passed options to an existing Plugin instance will not work."); + } - _this.parserOpts = { - sourceType: _this.opts.sourceType, - sourceFileName: _this.opts.filename, - plugins: [] - }; + return descriptor.value; + } - _this.pluginVisitors = []; - _this.pluginPasses = []; + return instantiatePlugin(loadDescriptor(descriptor, context), context); +} - _this.buildPluginsForOptions(_this.opts); +var instantiatePlugin = (0, _caching.makeWeakCache)(function (_ref3, cache) { + var value = _ref3.value, + options = _ref3.options, + dirname = _ref3.dirname, + alias = _ref3.alias; + var pluginObj = (0, _plugins.validatePluginObject)(value); + var plugin = Object.assign({}, pluginObj); - if (_this.opts.passPerPreset) { - _this.perPresetOpts = []; - _this.opts.presets.forEach(function (presetOpts) { - var perPresetOpts = (0, _assign2.default)((0, _create2.default)(_this.opts), presetOpts); - _this.perPresetOpts.push(perPresetOpts); - _this.buildPluginsForOptions(perPresetOpts); - }); - } + if (plugin.visitor) { + plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor)); + } - _this.metadata = { - usedHelpers: [], - marked: [], - modules: { - imports: [], - exports: { - exported: [], - specifiers: [] - } - } + if (plugin.inherits) { + var inheritsDescriptor = { + name: undefined, + alias: "".concat(alias, "$inherits"), + value: plugin.inherits, + options: options, + dirname: dirname }; + var inherits = cache.invalidate(function (data) { + return loadPluginDescriptor(inheritsDescriptor, data); + }); + plugin.pre = chain(inherits.pre, plugin.pre); + plugin.post = chain(inherits.post, plugin.post); + plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions); + plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]); + } - _this.dynamicImportTypes = {}; - _this.dynamicImportIds = {}; - _this.dynamicImports = []; - _this.declarations = {}; - _this.usedHelpers = {}; - - _this.path = null; - _this.ast = {}; - - _this.code = ""; - _this.shebang = ""; + return new _plugin.default(plugin, options, alias); +}); - _this.hub = new _babelTraverse.Hub(_this); - return _this; +var validateIfOptionNeedsFilename = function validateIfOptionNeedsFilename(options, descriptor) { + if (options.test || options.include || options.exclude) { + var formattedPresetName = descriptor.name ? "\"".concat(descriptor.name, "\"") : "/* your preset */"; + throw new Error(["Preset ".concat(formattedPresetName, " requires a filename to be set when babel is called directly,"), "```", "babel.transform(code, { filename: 'file.ts', presets: [".concat(formattedPresetName, "] });"), "```", "See https://babeljs.io/docs/en/options#filename for more information."].join("\n")); } +}; - File.prototype.getMetadata = function getMetadata() { - var has = false; - for (var _iterator = this.ast.program.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var validatePreset = function validatePreset(preset, context, descriptor) { + if (!context.filename) { + var options = preset.options; + validateIfOptionNeedsFilename(options, descriptor); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (options.overrides) { + options.overrides.forEach(function (overrideOptions) { + return validateIfOptionNeedsFilename(overrideOptions, descriptor); + }); + } + } +}; - var node = _ref; +var loadPresetDescriptor = function loadPresetDescriptor(descriptor, context) { + var preset = instantiatePreset(loadDescriptor(descriptor, context)); + validatePreset(preset, context, descriptor); + return (0, _configChain.buildPresetChain)(preset, context); +}; - if (t.isModuleDeclaration(node)) { - has = true; - break; - } - } - if (has) { - this.path.traverse(metadataVisitor, this); - } +var instantiatePreset = (0, _caching.makeWeakCache)(function (_ref4) { + var value = _ref4.value, + dirname = _ref4.dirname, + alias = _ref4.alias; + return { + options: (0, _options.validate)("preset", value), + alias: alias, + dirname: dirname }; +}); - File.prototype.initOptions = function initOptions(opts) { - opts = new _optionManager2.default(this.log, this.pipeline).init(opts); - - if (opts.inputSourceMap) { - opts.sourceMaps = true; +function chain(a, b) { + var fns = [a, b].filter(Boolean); + if (fns.length <= 1) return fns[0]; + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - if (opts.moduleId) { - opts.moduleIds = true; - } + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - opts.basename = _path2.default.basename(opts.filename, _path2.default.extname(opts.filename)); + try { + for (var _iterator2 = fns[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var fn = _step2.value; + fn.apply(this, args); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + }; +} - opts.ignore = util.arrayify(opts.ignore, util.regexify); +},{"../index":19,"./caching":2,"./config-chain":3,"./helpers/config-api":7,"./item":10,"./partial":11,"./plugin":13,"./util":14,"./validation/options":16,"./validation/plugins":17,"@babel/traverse":176}],7:[function(require,module,exports){ +"use strict"; - if (opts.only) opts.only = util.arrayify(opts.only, util.regexify); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = makeAPI; - (0, _defaults2.default)(opts, { - moduleRoot: opts.sourceRoot - }); +function _semver() { + var data = _interopRequireDefault(require("semver")); - (0, _defaults2.default)(opts, { - sourceRoot: opts.moduleRoot - }); + _semver = function _semver() { + return data; + }; - (0, _defaults2.default)(opts, { - filenameRelative: opts.filename - }); + return data; +} - var basenameRelative = _path2.default.basename(opts.filenameRelative); +var _ = require("../../"); - (0, _defaults2.default)(opts, { - sourceFileName: basenameRelative, - sourceMapTarget: basenameRelative - }); +var _caching = require("../caching"); - return opts; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - File.prototype.buildPluginsForOptions = function buildPluginsForOptions(opts) { - if (!Array.isArray(opts.plugins)) { - return; - } - - var plugins = opts.plugins.concat(INTERNAL_PLUGINS); - var currentPluginVisitors = []; - var currentPluginPasses = []; - - for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; +function makeAPI(cache) { + var env = function env(value) { + return cache.using(function (data) { + if (typeof value === "undefined") return data.envName; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + if (typeof value === "function") { + return (0, _caching.assertSimpleType)(value(data.envName)); } - var ref = _ref2; - var plugin = ref[0], - pluginOpts = ref[1]; - + if (!Array.isArray(value)) value = [value]; + return value.some(function (entry) { + if (typeof entry !== "string") { + throw new Error("Unexpected non-string value"); + } - currentPluginVisitors.push(plugin.visitor); - currentPluginPasses.push(new _pluginPass2.default(this, plugin, pluginOpts)); + return entry === data.envName; + }); + }); + }; - if (plugin.manipulateOptions) { - plugin.manipulateOptions(opts, this.parserOpts, this); - } - } + var caller = function caller(cb) { + return cache.using(function (data) { + return (0, _caching.assertSimpleType)(cb(data.caller)); + }); + }; - this.pluginVisitors.push(currentPluginVisitors); - this.pluginPasses.push(currentPluginPasses); + return { + version: _.version, + cache: cache.simple(), + env: env, + async: function async() { + return false; + }, + caller: caller, + assertVersion: assertVersion, + tokTypes: undefined }; +} - File.prototype.getModuleName = function getModuleName() { - var opts = this.opts; - if (!opts.moduleIds) { - return null; +function assertVersion(range) { + if (typeof range === "number") { + if (!Number.isInteger(range)) { + throw new Error("Expected string or integer value."); } - if (opts.moduleId != null && !opts.getModuleId) { - return opts.moduleId; - } + range = "^".concat(range, ".0.0-0"); + } - var filenameRelative = opts.filenameRelative; - var moduleName = ""; + if (typeof range !== "string") { + throw new Error("Expected string or integer value."); + } - if (opts.moduleRoot != null) { - moduleName = opts.moduleRoot + "/"; - } + if (_semver().default.satisfies(_.version, range)) return; + var limit = Error.stackTraceLimit; - if (!opts.filenameRelative) { - return moduleName + opts.filename.replace(/^\//, ""); - } + if (typeof limit === "number" && limit < 25) { + Error.stackTraceLimit = 25; + } - if (opts.sourceRoot != null) { - var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?"); - filenameRelative = filenameRelative.replace(sourceRootRegEx, ""); - } + var err = new Error("Requires Babel \"".concat(range, "\", but was loaded with \"").concat(_.version, "\". ") + "If you are sure you have a compatible version of @babel/core, " + "it is likely that something in your build process is loading the " + "wrong version. Inspect the stack trace of this error to look for " + "the first entry that doesn't mention \"@babel/core\" or \"babel-core\" " + "to see what is calling Babel."); - filenameRelative = filenameRelative.replace(/\.(\w*?)$/, ""); + if (typeof limit === "number") { + Error.stackTraceLimit = limit; + } - moduleName += filenameRelative; + throw Object.assign(err, { + code: "BABEL_VERSION_UNSUPPORTED", + version: _.version, + range: range + }); +} - moduleName = moduleName.replace(/\\/g, "/"); +},{"../../":19,"../caching":2,"semver":1070}],8:[function(require,module,exports){ +(function (process){ +"use strict"; - if (opts.getModuleId) { - return opts.getModuleId(moduleName) || moduleName; - } else { - return moduleName; - } - }; - - File.prototype.resolveModuleSource = function resolveModuleSource(source) { - var resolveModuleSource = this.opts.resolveModuleSource; - if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename); - return source; - }; - - File.prototype.addImport = function addImport(source, imported) { - var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : imported; - - var alias = source + ":" + imported; - var id = this.dynamicImportIds[alias]; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getEnv = getEnv; - if (!id) { - source = this.resolveModuleSource(source); - id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name); +function getEnv() { + var defaultValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "development"; + return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; +} - var specifiers = []; +}).call(this,require('_process')) +},{"_process":1054}],9:[function(require,module,exports){ +"use strict"; - if (imported === "*") { - specifiers.push(t.importNamespaceSpecifier(id)); - } else if (imported === "default") { - specifiers.push(t.importDefaultSpecifier(id)); - } else { - specifiers.push(t.importSpecifier(id, t.identifier(imported))); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.loadOptions = loadOptions; +Object.defineProperty(exports, "default", { + enumerable: true, + get: function get() { + return _full.default; + } +}); +Object.defineProperty(exports, "loadPartialConfig", { + enumerable: true, + get: function get() { + return _partial.loadPartialConfig; + } +}); - var declar = t.importDeclaration(specifiers, t.stringLiteral(source)); - declar._blockHoist = 3; +var _full = _interopRequireDefault(require("./full")); - this.path.unshiftContainer("body", declar); - } +var _partial = require("./partial"); - return id; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - File.prototype.addHelper = function addHelper(name) { - var declar = this.declarations[name]; - if (declar) return declar; +function loadOptions(opts) { + var config = (0, _full.default)(opts); + return config ? config.options : null; +} - if (!this.usedHelpers[name]) { - this.metadata.usedHelpers.push(name); - this.usedHelpers[name] = true; - } +},{"./full":6,"./partial":11}],10:[function(require,module,exports){ +"use strict"; - var generator = this.get("helperGenerator"); - var runtime = this.get("helpersNamespace"); - if (generator) { - var res = generator(name); - if (res) return res; - } else if (runtime) { - return t.memberExpression(runtime, t.identifier(name)); - } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var ref = (0, _babelHelpers2.default)(name); - var uid = this.declarations[name] = this.scope.generateUidIdentifier(name); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createItemFromDescriptor = createItemFromDescriptor; +exports.createConfigItem = createConfigItem; +exports.getItemDescriptor = getItemDescriptor; - if (t.isFunctionExpression(ref) && !ref.id) { - ref.body._compact = true; - ref._generated = true; - ref.id = uid; - ref.type = "FunctionDeclaration"; - this.path.unshiftContainer("body", ref); - } else { - ref._compact = true; - this.scope.push({ - id: uid, - init: ref, - unique: true - }); - } +function _path() { + var data = _interopRequireDefault(require("path")); - return uid; + _path = function _path() { + return data; }; - File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) { - var stringIds = raw.elements.map(function (string) { - return string.value; - }); - var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(","); - - var declar = this.declarations[name]; - if (declar) return declar; + return data; +} - var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject"); +var _configDescriptors = require("./config-descriptors"); - var helperId = this.addHelper(helperName); - var init = t.callExpression(helperId, [strings, raw]); - init._compact = true; - this.scope.push({ - id: uid, - init: init, - _blockHoist: 1.9 }); - return uid; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - File.prototype.buildCodeFrameError = function buildCodeFrameError(node, msg) { - var Error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SyntaxError; +function createItemFromDescriptor(desc) { + return new ConfigItem(desc); +} - var loc = node && (node.loc || node._loc); +function createConfigItem(value) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$dirname = _ref.dirname, + dirname = _ref$dirname === void 0 ? "." : _ref$dirname, + type = _ref.type; - var err = new Error(msg); + var descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), { + type: type, + alias: "programmatic item" + }); + return createItemFromDescriptor(descriptor); +} - if (loc) { - err.loc = loc.start; - } else { - (0, _babelTraverse2.default)(node, errorVisitor, this.scope, err); +function getItemDescriptor(item) { + if (item instanceof ConfigItem) { + return item._descriptor; + } - err.message += " (This is an error on an internal node. Probably an internal error"; + return undefined; +} - if (err.loc) { - err.message += ". Location has been estimated."; - } +var ConfigItem = function ConfigItem(descriptor) { + _classCallCheck(this, ConfigItem); - err.message += ")"; - } + this._descriptor = descriptor; + Object.defineProperty(this, "_descriptor", { + enumerable: false + }); + this.value = this._descriptor.value; + this.options = this._descriptor.options; + this.dirname = this._descriptor.dirname; + this.name = this._descriptor.name; + this.file = this._descriptor.file ? { + request: this._descriptor.file.request, + resolved: this._descriptor.file.resolved + } : undefined; + Object.freeze(this); +}; - return err; - }; +Object.freeze(ConfigItem.prototype); - File.prototype.mergeSourceMap = function mergeSourceMap(map) { - var inputMap = this.opts.inputSourceMap; +},{"./config-descriptors":4,"path":1052}],11:[function(require,module,exports){ +"use strict"; - if (inputMap) { - var inputMapConsumer = new _sourceMap2.default.SourceMapConsumer(inputMap); - var outputMapConsumer = new _sourceMap2.default.SourceMapConsumer(map); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var mergedGenerator = new _sourceMap2.default.SourceMapGenerator({ - file: inputMapConsumer.file, - sourceRoot: inputMapConsumer.sourceRoot - }); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - var source = outputMapConsumer.sources[0]; +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - inputMapConsumer.eachMapping(function (mapping) { - var generatedPosition = outputMapConsumer.generatedPositionFor({ - line: mapping.generatedLine, - column: mapping.generatedColumn, - source: source - }); - if (generatedPosition.column != null) { - mergedGenerator.addMapping({ - source: mapping.source, +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - original: mapping.source == null ? null : { - line: mapping.originalLine, - column: mapping.originalColumn - }, +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadPrivatePartialConfig; +exports.loadPartialConfig = loadPartialConfig; - generated: generatedPosition - }); - } - }); +function _path() { + var data = _interopRequireDefault(require("path")); - var mergedMap = mergedGenerator.toJSON(); - inputMap.mappings = mergedMap.mappings; - return inputMap; - } else { - return map; - } + _path = function _path() { + return data; }; - File.prototype.parse = function parse(code) { - var parseCode = _babylon.parse; - var parserOpts = this.opts.parserOpts; - - if (parserOpts) { - parserOpts = (0, _assign2.default)({}, this.parserOpts, parserOpts); - - if (parserOpts.parser) { - if (typeof parserOpts.parser === "string") { - var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); - var parser = (0, _resolve2.default)(parserOpts.parser, dirname); - if (parser) { - parseCode = require(parser).parse; - } else { - throw new Error("Couldn't find parser " + parserOpts.parser + " with \"parse\" method " + ("relative to directory " + dirname)); - } - } else { - parseCode = parserOpts.parser; - } + return data; +} - parserOpts.parser = { - parse: function parse(source) { - return (0, _babylon.parse)(source, parserOpts); - } - }; - } - } +var _plugin = _interopRequireDefault(require("./plugin")); - this.log.debug("Parse start"); - var ast = parseCode(code, parserOpts || this.parserOpts); - this.log.debug("Parse stop"); - return ast; - }; +var _util = require("./util"); - File.prototype._addAst = function _addAst(ast) { - this.path = _babelTraverse.NodePath.get({ - hub: this.hub, - parentPath: null, - parent: ast, - container: ast, - key: "program" - }).setContext(); - this.scope = this.path.scope; - this.ast = ast; - this.getMetadata(); - }; +var _item = require("./item"); - File.prototype.addAst = function addAst(ast) { - this.log.debug("Start set AST"); - this._addAst(ast); - this.log.debug("End set AST"); - }; +var _configChain = require("./config-chain"); - File.prototype.transform = function transform() { - for (var i = 0; i < this.pluginPasses.length; i++) { - var pluginPasses = this.pluginPasses[i]; - this.call("pre", pluginPasses); - this.log.debug("Start transform traverse"); +var _environment = require("./helpers/environment"); - var visitor = _babelTraverse2.default.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod); - (0, _babelTraverse2.default)(this.ast, visitor, this.scope); +var _options = require("./validation/options"); - this.log.debug("End transform traverse"); - this.call("post", pluginPasses); - } +var _files = require("./files"); - return this.generate(); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - File.prototype.wrap = function wrap(code, callback) { - code = code + ""; +function resolveRootMode(rootDir, rootMode) { + switch (rootMode) { + case "root": + return rootDir; - try { - if (this.shouldIgnore()) { - return this.makeResult({ code: code, ignored: true }); - } else { - return callback(); - } - } catch (err) { - if (err._babel) { - throw err; - } else { - err._babel = true; + case "upward-optional": + { + var upwardRootDir = (0, _files.findConfigUpwards)(rootDir); + return upwardRootDir === null ? rootDir : upwardRootDir; } - var message = err.message = this.opts.filename + ": " + err.message; + case "upward": + { + var _upwardRootDir = (0, _files.findConfigUpwards)(rootDir); - var loc = err.loc; - if (loc) { - err.codeFrame = (0, _babelCodeFrame2.default)(code, loc.line, loc.column + 1, this.opts); - message += "\n" + err.codeFrame; + if (_upwardRootDir !== null) return _upwardRootDir; + throw Object.assign(new Error("Babel was run with rootMode:\"upward\" but a root could not " + "be found when searching upward from \"".concat(rootDir, "\"")), { + code: "BABEL_ROOT_NOT_FOUND", + dirname: rootDir + }); } - if (process.browser) { - err.message = message; - } + default: + throw new Error("Assertion failure - unknown rootMode value"); + } +} - if (err.stack) { - var newStack = err.stack.replace(err.message, message); - err.stack = newStack; - } +function loadPrivatePartialConfig(inputOpts) { + if (inputOpts != null && (_typeof(inputOpts) !== "object" || Array.isArray(inputOpts))) { + throw new Error("Babel options must be an object, null, or undefined"); + } - throw err; - } - }; + var args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {}; + var _args$envName = args.envName, + envName = _args$envName === void 0 ? (0, _environment.getEnv)() : _args$envName, + _args$cwd = args.cwd, + cwd = _args$cwd === void 0 ? "." : _args$cwd, + _args$root = args.root, + rootDir = _args$root === void 0 ? "." : _args$root, + _args$rootMode = args.rootMode, + rootMode = _args$rootMode === void 0 ? "root" : _args$rootMode, + caller = args.caller; - File.prototype.addCode = function addCode(code) { - code = (code || "") + ""; - code = this.parseInputSourceMap(code); - this.code = code; - }; + var absoluteCwd = _path().default.resolve(cwd); - File.prototype.parseCode = function parseCode() { - this.parseShebang(); - var ast = this.parse(this.code); - this.addAst(ast); + var absoluteRootDir = resolveRootMode(_path().default.resolve(absoluteCwd, rootDir), rootMode); + var context = { + filename: typeof args.filename === "string" ? _path().default.resolve(cwd, args.filename) : undefined, + cwd: absoluteCwd, + root: absoluteRootDir, + envName: envName, + caller: caller }; - - File.prototype.shouldIgnore = function shouldIgnore() { - var opts = this.opts; - return util.shouldIgnore(opts.filename, opts.ignore, opts.only); + var configChain = (0, _configChain.buildRootChain)(args, context); + if (!configChain) return null; + var options = {}; + configChain.options.forEach(function (opts) { + (0, _util.mergeOptions)(options, opts); + }); + options.babelrc = false; + options.configFile = false; + options.passPerPreset = false; + options.envName = context.envName; + options.cwd = context.cwd; + options.root = context.root; + options.filename = typeof context.filename === "string" ? context.filename : undefined; + options.plugins = configChain.plugins.map(function (descriptor) { + return (0, _item.createItemFromDescriptor)(descriptor); + }); + options.presets = configChain.presets.map(function (descriptor) { + return (0, _item.createItemFromDescriptor)(descriptor); + }); + return { + options: options, + context: context, + ignore: configChain.ignore, + babelrc: configChain.babelrc, + config: configChain.config }; +} - File.prototype.call = function call(key, pluginPasses) { - for (var _iterator3 = pluginPasses, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; +function loadPartialConfig(inputOpts) { + var result = loadPrivatePartialConfig(inputOpts); + if (!result) return null; + var options = result.options, + babelrc = result.babelrc, + ignore = result.ignore, + config = result.config; + (options.plugins || []).forEach(function (item) { + if (item.value instanceof _plugin.default) { + throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()"); + } + }); + return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined); +} - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } +var PartialConfig = +/*#__PURE__*/ +function () { + function PartialConfig(options, babelrc, ignore, config) { + _classCallCheck(this, PartialConfig); - var pass = _ref3; + this.options = options; + this.babelignore = ignore; + this.babelrc = babelrc; + this.config = config; + Object.freeze(this); + } - var plugin = pass.plugin; - var fn = plugin[key]; - if (fn) fn.call(pass, this); + _createClass(PartialConfig, [{ + key: "hasFilesystemConfig", + value: function hasFilesystemConfig() { + return this.babelrc !== undefined || this.config !== undefined; } - }; + }]); - File.prototype.parseInputSourceMap = function parseInputSourceMap(code) { - var opts = this.opts; + return PartialConfig; +}(); - if (opts.inputSourceMap !== false) { - var inputMap = _convertSourceMap2.default.fromSource(code); - if (inputMap) { - opts.inputSourceMap = inputMap.toObject(); - code = _convertSourceMap2.default.removeComments(code); - } - } +Object.freeze(PartialConfig.prototype); - return code; - }; +},{"./config-chain":3,"./files":5,"./helpers/environment":8,"./item":10,"./plugin":13,"./util":14,"./validation/options":16,"path":1052}],12:[function(require,module,exports){ +"use strict"; - File.prototype.parseShebang = function parseShebang() { - var shebangMatch = shebangRegex.exec(this.code); - if (shebangMatch) { - this.shebang = shebangMatch[0]; - this.code = this.code.replace(shebangRegex, ""); - } - }; +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } - File.prototype.makeResult = function makeResult(_ref4) { - var code = _ref4.code, - map = _ref4.map, - ast = _ref4.ast, - ignored = _ref4.ignored; +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } - var result = { - metadata: null, - options: this.opts, - ignored: !!ignored, - code: null, - ast: null, - map: map || null - }; +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } - if (this.opts.code) { - result.code = code; - } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } - if (this.opts.ast) { - result.ast = ast; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = pathToPattern; - if (this.opts.metadata) { - result.metadata = this.metadata; - } +function _path() { + var data = _interopRequireDefault(require("path")); - return result; + _path = function _path() { + return data; }; - File.prototype.generate = function generate() { - var opts = this.opts; - var ast = this.ast; + return data; +} - var result = { ast: ast }; - if (!opts.code) return this.makeResult(result); +function _escapeRegExp() { + var data = _interopRequireDefault(require("lodash/escapeRegExp")); - var gen = _babelGenerator2.default; - if (opts.generatorOpts.generator) { - gen = opts.generatorOpts.generator; + _escapeRegExp = function _escapeRegExp() { + return data; + }; - if (typeof gen === "string") { - var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); - var generator = (0, _resolve2.default)(gen, dirname); - if (generator) { - gen = require(generator).print; - } else { - throw new Error("Couldn't find generator " + gen + " with \"print\" method relative " + ("to directory " + dirname)); - } - } - } + return data; +} - this.log.debug("Generation start"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - var _result = gen(ast, opts.generatorOpts ? (0, _assign2.default)(opts, opts.generatorOpts) : opts, this.code); - result.code = _result.code; - result.map = _result.map; +var sep = "\\".concat(_path().default.sep); +var endSep = "(?:".concat(sep, "|$)"); +var substitution = "[^".concat(sep, "]+"); +var starPat = "(?:".concat(substitution).concat(sep, ")"); +var starPatLast = "(?:".concat(substitution).concat(endSep, ")"); +var starStarPat = "".concat(starPat, "*?"); +var starStarPatLast = "".concat(starPat, "*?").concat(starPatLast, "?"); - this.log.debug("Generation end"); +function pathToPattern(pattern, dirname) { + var parts = _path().default.resolve(dirname, pattern).split(_path().default.sep); - if (this.shebang) { - result.code = this.shebang + "\n" + result.code; - } + return new RegExp(["^"].concat(_toConsumableArray(parts.map(function (part, i) { + var last = i === parts.length - 1; + if (part === "**") return last ? starStarPatLast : starStarPat; + if (part === "*") return last ? starPatLast : starPat; - if (result.map) { - result.map = this.mergeSourceMap(result.map); + if (part.indexOf("*.") === 0) { + return substitution + (0, _escapeRegExp().default)(part.slice(1)) + (last ? endSep : sep); } - if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { - result.code += "\n" + _convertSourceMap2.default.fromObject(result.map).toComment(); - } + return (0, _escapeRegExp().default)(part) + (last ? endSep : sep); + }))).join("")); +} - if (opts.sourceMaps === "inline") { - result.map = null; - } +},{"lodash/escapeRegExp":1009,"path":1052}],13:[function(require,module,exports){ +"use strict"; - return this.makeResult(result); - }; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - return File; -}(_store2.default); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var Plugin = function Plugin(plugin, options, key) { + _classCallCheck(this, Plugin); + + this.key = plugin.name || key; + this.manipulateOptions = plugin.manipulateOptions; + this.post = plugin.post; + this.pre = plugin.pre; + this.visitor = plugin.visitor || {}; + this.parserOverride = plugin.parserOverride; + this.generatorOverride = plugin.generatorOverride; + this.options = options; +}; -exports.default = File; -exports.File = File; -}).call(this,require('_process')) -},{"../../helpers/resolve":14,"../../store":15,"../../util":31,"../internal-plugins/block-hoist":26,"../internal-plugins/shadow-functions":27,"../plugin-pass":29,"./logger":18,"./metadata":19,"./options/option-manager":23,"_process":525,"babel-code-frame":4,"babel-generator":44,"babel-helpers":60,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/assign":99,"babel-runtime/core-js/object/create":100,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112,"babel-traverse":118,"babel-types":151,"babylon":155,"convert-source-map":163,"lodash/defaults":470,"path":522,"source-map":552}],18:[function(require,module,exports){ +exports.default = Plugin; + +},{}],14:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.mergeOptions = mergeOptions; + +function mergeOptions(target, source) { + for (var _i = 0, _Object$keys = Object.keys(source); _i < _Object$keys.length; _i++) { + var k = _Object$keys[_i]; + + if (k === "parserOpts" && source.parserOpts) { + var parserOpts = source.parserOpts; + var targetObj = target.parserOpts = target.parserOpts || {}; + mergeDefaultFields(targetObj, parserOpts); + } else if (k === "generatorOpts" && source.generatorOpts) { + var generatorOpts = source.generatorOpts; + + var _targetObj = target.generatorOpts = target.generatorOpts || {}; + + mergeDefaultFields(_targetObj, generatorOpts); + } else { + var val = source[k]; + if (val !== undefined) target[k] = val; + } + } +} -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +function mergeDefaultFields(target, source) { + for (var _i2 = 0, _Object$keys2 = Object.keys(source); _i2 < _Object$keys2.length; _i2++) { + var k = _Object$keys2[_i2]; + var val = source[k]; + if (val !== undefined) target[k] = val; + } +} -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +},{}],15:[function(require,module,exports){ +"use strict"; -var _node = require("debug/node"); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -var _node2 = _interopRequireDefault(_node); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.msg = msg; +exports.access = access; +exports.assertRootMode = assertRootMode; +exports.assertSourceMaps = assertSourceMaps; +exports.assertCompact = assertCompact; +exports.assertSourceType = assertSourceType; +exports.assertCallerMetadata = assertCallerMetadata; +exports.assertInputSourceMap = assertInputSourceMap; +exports.assertString = assertString; +exports.assertFunction = assertFunction; +exports.assertBoolean = assertBoolean; +exports.assertObject = assertObject; +exports.assertArray = assertArray; +exports.assertIgnoreList = assertIgnoreList; +exports.assertConfigApplicableTest = assertConfigApplicableTest; +exports.assertConfigFileSearch = assertConfigFileSearch; +exports.assertBabelrcSearch = assertBabelrcSearch; +exports.assertPluginList = assertPluginList; + +function msg(loc) { + switch (loc.type) { + case "root": + return ""; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case "env": + return "".concat(msg(loc.parent), ".env[\"").concat(loc.name, "\"]"); -var verboseDebug = (0, _node2.default)("babel:verbose"); -var generalDebug = (0, _node2.default)("babel"); + case "overrides": + return "".concat(msg(loc.parent), ".overrides[").concat(loc.index, "]"); -var seenDeprecatedMessages = []; + case "option": + return "".concat(msg(loc.parent), ".").concat(loc.name); -var Logger = function () { - function Logger(file, filename) { - (0, _classCallCheck3.default)(this, Logger); + case "access": + return "".concat(msg(loc.parent), "[").concat(JSON.stringify(loc.name), "]"); - this.filename = filename; - this.file = file; + default: + throw new Error("Assertion failure: Unknown type ".concat(loc.type)); } +} - Logger.prototype._buildMessage = function _buildMessage(msg) { - var parts = "[BABEL] " + this.filename; - if (msg) parts += ": " + msg; - return parts; +function access(loc, name) { + return { + type: "access", + name: name, + parent: loc }; +} - Logger.prototype.warn = function warn(msg) { - console.warn(this._buildMessage(msg)); - }; +function assertRootMode(loc, value) { + if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") { + throw new Error("".concat(msg(loc), " must be a \"root\", \"upward\", \"upward-optional\" or undefined")); + } - Logger.prototype.error = function error(msg) { - var Constructor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error; + return value; +} - throw new Constructor(this._buildMessage(msg)); - }; +function assertSourceMaps(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") { + throw new Error("".concat(msg(loc), " must be a boolean, \"inline\", \"both\", or undefined")); + } - Logger.prototype.deprecate = function deprecate(msg) { - if (this.file.opts && this.file.opts.suppressDeprecationMessages) return; + return value; +} - msg = this._buildMessage(msg); +function assertCompact(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "auto") { + throw new Error("".concat(msg(loc), " must be a boolean, \"auto\", or undefined")); + } - if (seenDeprecatedMessages.indexOf(msg) >= 0) return; + return value; +} - seenDeprecatedMessages.push(msg); +function assertSourceType(loc, value) { + if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") { + throw new Error("".concat(msg(loc), " must be \"module\", \"script\", \"unambiguous\", or undefined")); + } - console.error(msg); - }; + return value; +} - Logger.prototype.verbose = function verbose(msg) { - if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg)); - }; +function assertCallerMetadata(loc, value) { + var obj = assertObject(loc, value); - Logger.prototype.debug = function debug(msg) { - if (generalDebug.enabled) generalDebug(this._buildMessage(msg)); - }; + if (obj) { + if (typeof obj["name"] !== "string") { + throw new Error("".concat(msg(loc), " set but does not contain \"name\" property string")); + } - Logger.prototype.deopt = function deopt(node, msg) { - this.debug(msg); - }; + for (var _i = 0, _Object$keys = Object.keys(obj); _i < _Object$keys.length; _i++) { + var prop = _Object$keys[_i]; + var propLoc = access(loc, prop); + var _value = obj[prop]; - return Logger; -}(); + if (_value != null && typeof _value !== "boolean" && typeof _value !== "string" && typeof _value !== "number") { + throw new Error("".concat(msg(propLoc), " must be null, undefined, a boolean, a string, or a number.")); + } + } + } -exports.default = Logger; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109,"debug/node":278}],19:[function(require,module,exports){ -"use strict"; + return value; +} -exports.__esModule = true; -exports.ImportDeclaration = exports.ModuleDeclaration = undefined; +function assertInputSourceMap(loc, value) { + if (value !== undefined && typeof value !== "boolean" && (_typeof(value) !== "object" || !value)) { + throw new Error("".concat(msg(loc), " must be a boolean, object, or undefined")); + } + + return value; +} -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function assertString(loc, value) { + if (value !== undefined && typeof value !== "string") { + throw new Error("".concat(msg(loc), " must be a string, or undefined")); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + return value; +} -exports.ExportDeclaration = ExportDeclaration; -exports.Scope = Scope; +function assertFunction(loc, value) { + if (value !== undefined && typeof value !== "function") { + throw new Error("".concat(msg(loc), " must be a function, or undefined")); + } -var _babelTypes = require("babel-types"); + return value; +} -var t = _interopRequireWildcard(_babelTypes); +function assertBoolean(loc, value) { + if (value !== undefined && typeof value !== "boolean") { + throw new Error("".concat(msg(loc), " must be a boolean, or undefined")); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return value; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function assertObject(loc, value) { + if (value !== undefined && (_typeof(value) !== "object" || Array.isArray(value) || !value)) { + throw new Error("".concat(msg(loc), " must be an object, or undefined")); + } -var ModuleDeclaration = exports.ModuleDeclaration = { - enter: function enter(path, file) { - var node = path.node; + return value; +} - if (node.source) { - node.source.value = file.resolveModuleSource(node.source.value); - } +function assertArray(loc, value) { + if (value != null && !Array.isArray(value)) { + throw new Error("".concat(msg(loc), " must be an array, or undefined")); } -}; -var ImportDeclaration = exports.ImportDeclaration = { - exit: function exit(path, file) { - var node = path.node; + return value; +} +function assertIgnoreList(loc, value) { + var arr = assertArray(loc, value); - var specifiers = []; - var imported = []; - file.metadata.modules.imports.push({ - source: node.source.value, - imported: imported, - specifiers: specifiers + if (arr) { + arr.forEach(function (item, i) { + return assertIgnoreItem(access(loc, i), item); }); + } - for (var _iterator = path.get("specifiers"), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + return arr; +} - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +function assertIgnoreItem(loc, value) { + if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) { + throw new Error("".concat(msg(loc), " must be an array of string/Function/RegExp values, or undefined")); + } - var specifier = _ref; + return value; +} - var local = specifier.node.local.name; +function assertConfigApplicableTest(loc, value) { + if (value === undefined) return value; - if (specifier.isImportDefaultSpecifier()) { - imported.push("default"); - specifiers.push({ - kind: "named", - imported: "default", - local: local - }); + if (Array.isArray(value)) { + value.forEach(function (item, i) { + if (!checkValidTest(item)) { + throw new Error("".concat(msg(access(loc, i)), " must be a string/Function/RegExp.")); } + }); + } else if (!checkValidTest(value)) { + throw new Error("".concat(msg(loc), " must be a string/Function/RegExp, or an array of those")); + } - if (specifier.isImportSpecifier()) { - var importedName = specifier.node.imported.name; - imported.push(importedName); - specifiers.push({ - kind: "named", - imported: importedName, - local: local - }); - } + return value; +} - if (specifier.isImportNamespaceSpecifier()) { - imported.push("*"); - specifiers.push({ - kind: "namespace", - local: local - }); - } - } +function checkValidTest(value) { + return typeof value === "string" || typeof value === "function" || value instanceof RegExp; +} + +function assertConfigFileSearch(loc, value) { + if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") { + throw new Error("".concat(msg(loc), " must be a undefined, a boolean, a string, ") + "got ".concat(JSON.stringify(value))); } -}; -function ExportDeclaration(path, file) { - var node = path.node; + return value; +} +function assertBabelrcSearch(loc, value) { + if (value === undefined || typeof value === "boolean") return value; + + if (Array.isArray(value)) { + value.forEach(function (item, i) { + if (!checkValidTest(item)) { + throw new Error("".concat(msg(access(loc, i)), " must be a string/Function/RegExp.")); + } + }); + } else if (!checkValidTest(value)) { + throw new Error("".concat(msg(loc), " must be a undefined, a boolean, a string/Function/RegExp ") + "or an array of those, got ".concat(JSON.stringify(value))); + } - var source = node.source ? node.source.value : null; - var exports = file.metadata.modules.exports; + return value; +} - var declar = path.get("declaration"); - if (declar.isStatement()) { - var bindings = declar.getBindingIdentifiers(); +function assertPluginList(loc, value) { + var arr = assertArray(loc, value); - for (var name in bindings) { - exports.exported.push(name); - exports.specifiers.push({ - kind: "local", - local: name, - exported: path.isExportDefaultDeclaration() ? "default" : name - }); - } + if (arr) { + arr.forEach(function (item, i) { + return assertPluginItem(access(loc, i), item); + }); } - if (path.isExportNamedDeclaration() && node.specifiers) { - for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + return arr; +} - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +function assertPluginItem(loc, value) { + if (Array.isArray(value)) { + if (value.length === 0) { + throw new Error("".concat(msg(loc), " must include an object")); + } - var specifier = _ref2; + if (value.length > 3) { + throw new Error("".concat(msg(loc), " may only be a two-tuple or three-tuple")); + } - var exported = specifier.exported.name; - exports.exported.push(exported); + assertPluginTarget(access(loc, 0), value[0]); - if (t.isExportDefaultSpecifier(specifier)) { - exports.specifiers.push({ - kind: "external", - local: exported, - exported: exported, - source: source - }); - } + if (value.length > 1) { + var opts = value[1]; - if (t.isExportNamespaceSpecifier(specifier)) { - exports.specifiers.push({ - kind: "external-namespace", - exported: exported, - source: source - }); + if (opts !== undefined && opts !== false && (_typeof(opts) !== "object" || Array.isArray(opts) || opts === null)) { + throw new Error("".concat(msg(access(loc, 1)), " must be an object, false, or undefined")); } + } - var local = specifier.local; - if (!local) continue; - - if (source) { - exports.specifiers.push({ - kind: "external", - local: local.name, - exported: exported, - source: source - }); - } + if (value.length === 3) { + var name = value[2]; - if (!source) { - exports.specifiers.push({ - kind: "local", - local: local.name, - exported: exported - }); + if (name !== undefined && typeof name !== "string") { + throw new Error("".concat(msg(access(loc, 2)), " must be a string, or undefined")); } } + } else { + assertPluginTarget(loc, value); } - if (path.isExportAllDeclaration()) { - exports.specifiers.push({ - kind: "external-all", - source: source - }); - } + return value; } -function Scope(path) { - path.skip(); -} -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],20:[function(require,module,exports){ -(function (process){ -"use strict"; +function assertPluginTarget(loc, value) { + if ((_typeof(value) !== "object" || !value) && typeof value !== "string" && typeof value !== "function") { + throw new Error("".concat(msg(loc), " must be a string, object, function")); + } -exports.__esModule = true; + return value; +} -var _assign = require("babel-runtime/core-js/object/assign"); +},{}],16:[function(require,module,exports){ +"use strict"; -var _assign2 = _interopRequireDefault(_assign); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -exports.default = buildConfigChain; +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -var _resolve = require("../../../helpers/resolve"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validate = validate; -var _resolve2 = _interopRequireDefault(_resolve); +var _plugin = _interopRequireDefault(require("../plugin")); -var _json = require("json5"); +var _removed = _interopRequireDefault(require("./removed")); -var _json2 = _interopRequireDefault(_json); +var _optionAssertions = require("./option-assertions"); -var _pathIsAbsolute = require("path-is-absolute"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} -var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute); +var ROOT_VALIDATORS = { + cwd: _optionAssertions.assertString, + root: _optionAssertions.assertString, + rootMode: _optionAssertions.assertRootMode, + configFile: _optionAssertions.assertConfigFileSearch, + caller: _optionAssertions.assertCallerMetadata, + filename: _optionAssertions.assertString, + filenameRelative: _optionAssertions.assertString, + code: _optionAssertions.assertBoolean, + ast: _optionAssertions.assertBoolean, + envName: _optionAssertions.assertString +}; +var BABELRC_VALIDATORS = { + babelrc: _optionAssertions.assertBoolean, + babelrcRoots: _optionAssertions.assertBabelrcSearch +}; +var NONPRESET_VALIDATORS = { + extends: _optionAssertions.assertString, + ignore: _optionAssertions.assertIgnoreList, + only: _optionAssertions.assertIgnoreList +}; +var COMMON_VALIDATORS = { + inputSourceMap: _optionAssertions.assertInputSourceMap, + presets: _optionAssertions.assertPluginList, + plugins: _optionAssertions.assertPluginList, + passPerPreset: _optionAssertions.assertBoolean, + env: assertEnvSet, + overrides: assertOverridesList, + test: _optionAssertions.assertConfigApplicableTest, + include: _optionAssertions.assertConfigApplicableTest, + exclude: _optionAssertions.assertConfigApplicableTest, + retainLines: _optionAssertions.assertBoolean, + comments: _optionAssertions.assertBoolean, + shouldPrintComment: _optionAssertions.assertFunction, + compact: _optionAssertions.assertCompact, + minified: _optionAssertions.assertBoolean, + auxiliaryCommentBefore: _optionAssertions.assertString, + auxiliaryCommentAfter: _optionAssertions.assertString, + sourceType: _optionAssertions.assertSourceType, + wrapPluginVisitorMethod: _optionAssertions.assertFunction, + highlightCode: _optionAssertions.assertBoolean, + sourceMaps: _optionAssertions.assertSourceMaps, + sourceMap: _optionAssertions.assertSourceMaps, + sourceFileName: _optionAssertions.assertString, + sourceRoot: _optionAssertions.assertString, + getModuleId: _optionAssertions.assertFunction, + moduleRoot: _optionAssertions.assertString, + moduleIds: _optionAssertions.assertBoolean, + moduleId: _optionAssertions.assertString, + parserOpts: _optionAssertions.assertObject, + generatorOpts: _optionAssertions.assertObject +}; + +function getSource(loc) { + return loc.type === "root" ? loc.source : getSource(loc.parent); +} + +function validate(type, opts) { + return validateNested({ + type: "root", + source: type + }, opts); +} -var _path = require("path"); +function validateNested(loc, opts) { + var type = getSource(loc); + assertNoDuplicateSourcemap(opts); + Object.keys(opts).forEach(function (key) { + var optLoc = { + type: "option", + name: key, + parent: loc + }; -var _path2 = _interopRequireDefault(_path); + if (type === "preset" && NONPRESET_VALIDATORS[key]) { + throw new Error("".concat((0, _optionAssertions.msg)(optLoc), " is not allowed in preset options")); + } -var _fs = require("fs"); + if (type !== "arguments" && ROOT_VALIDATORS[key]) { + throw new Error("".concat((0, _optionAssertions.msg)(optLoc), " is only allowed in root programmatic options")); + } -var _fs2 = _interopRequireDefault(_fs); + if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) { + if (type === "babelrcfile" || type === "extendsfile") { + throw new Error("".concat((0, _optionAssertions.msg)(optLoc), " is not allowed in .babelrc or \"extends\"ed files, only in root programmatic options, ") + "or babel.config.js/config file options"); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + throw new Error("".concat((0, _optionAssertions.msg)(optLoc), " is only allowed in root programmatic options, or babel.config.js/config file options")); + } -var existsCache = {}; -var jsonCache = {}; + var validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError; + validator(optLoc, opts[key]); + }); + return opts; +} -var BABELIGNORE_FILENAME = ".babelignore"; -var BABELRC_FILENAME = ".babelrc"; -var PACKAGE_FILENAME = "package.json"; +function throwUnknownError(loc) { + var key = loc.name; -function exists(filename) { - var cached = existsCache[filename]; - if (cached == null) { - return existsCache[filename] = _fs2.default.existsSync(filename); + if (_removed.default[key]) { + var _removed$default$key = _removed.default[key], + message = _removed$default$key.message, + _removed$default$key$ = _removed$default$key.version, + version = _removed$default$key$ === void 0 ? 5 : _removed$default$key$; + throw new ReferenceError("Using removed Babel ".concat(version, " option: ").concat((0, _optionAssertions.msg)(loc), " - ").concat(message)); } else { - return cached; + var unknownOptErr = "Unknown option: ".concat((0, _optionAssertions.msg)(loc), ". Check out https://babeljs.io/docs/en/babel-core/#options for more information about options."); + throw new ReferenceError(unknownOptErr); } } -function buildConfigChain() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var log = arguments[1]; +function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} - var filename = opts.filename; - var builder = new ConfigChainBuilder(log); +function assertNoDuplicateSourcemap(opts) { + if (has(opts, "sourceMap") && has(opts, "sourceMaps")) { + throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both"); + } +} - if (opts.babelrc !== false) { - builder.findConfigs(filename); +function assertEnvSet(loc, value) { + if (loc.parent.type === "env") { + throw new Error("".concat((0, _optionAssertions.msg)(loc), " is not allowed inside of another .env block")); } - builder.mergeConfig({ - options: opts, - alias: "base", - dirname: filename && _path2.default.dirname(filename) - }); + var parent = loc.parent; + var obj = (0, _optionAssertions.assertObject)(loc, value); - return builder.configs; -} + if (obj) { + for (var _i = 0, _Object$keys = Object.keys(obj); _i < _Object$keys.length; _i++) { + var envName = _Object$keys[_i]; + var env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]); + if (!env) continue; + var envLoc = { + type: "env", + name: envName, + parent: parent + }; + validateNested(envLoc, env); + } + } -var ConfigChainBuilder = function () { - function ConfigChainBuilder(log) { - (0, _classCallCheck3.default)(this, ConfigChainBuilder); + return obj; +} - this.resolvedConfigs = []; - this.configs = []; - this.log = log; +function assertOverridesList(loc, value) { + if (loc.parent.type === "env") { + throw new Error("".concat((0, _optionAssertions.msg)(loc), " is not allowed inside an .env block")); } - ConfigChainBuilder.prototype.findConfigs = function findConfigs(loc) { - if (!loc) return; - - if (!(0, _pathIsAbsolute2.default)(loc)) { - loc = _path2.default.join(process.cwd(), loc); - } + if (loc.parent.type === "overrides") { + throw new Error("".concat((0, _optionAssertions.msg)(loc), " is not allowed inside an .overrides block")); + } - var foundConfig = false; - var foundIgnore = false; + var parent = loc.parent; + var arr = (0, _optionAssertions.assertArray)(loc, value); - while (loc !== (loc = _path2.default.dirname(loc))) { - if (!foundConfig) { - var configLoc = _path2.default.join(loc, BABELRC_FILENAME); - if (exists(configLoc)) { - this.addConfig(configLoc); - foundConfig = true; - } + if (arr) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - var pkgLoc = _path2.default.join(loc, PACKAGE_FILENAME); - if (!foundConfig && exists(pkgLoc)) { - foundConfig = this.addConfig(pkgLoc, "babel", JSON); - } + try { + for (var _iterator = arr.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _step$value = _slicedToArray(_step.value, 2), + index = _step$value[0], + item = _step$value[1]; + + var objLoc = (0, _optionAssertions.access)(loc, index); + var env = (0, _optionAssertions.assertObject)(objLoc, item); + if (!env) throw new Error("".concat((0, _optionAssertions.msg)(objLoc), " must be an object")); + var overridesLoc = { + type: "overrides", + index: index, + parent: parent + }; + validateNested(overridesLoc, env); } - - if (!foundIgnore) { - var ignoreLoc = _path2.default.join(loc, BABELIGNORE_FILENAME); - if (exists(ignoreLoc)) { - this.addIgnoreConfig(ignoreLoc); - foundIgnore = true; + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; } } - - if (foundIgnore && foundConfig) return; } - }; - - ConfigChainBuilder.prototype.addIgnoreConfig = function addIgnoreConfig(loc) { - var file = _fs2.default.readFileSync(loc, "utf8"); - var lines = file.split("\n"); + } - lines = lines.map(function (line) { - return line.replace(/#(.*?)$/, "").trim(); - }).filter(function (line) { - return !!line; - }); + return arr; +} - if (lines.length) { - this.mergeConfig({ - options: { ignore: lines }, - alias: loc, - dirname: _path2.default.dirname(loc) - }); - } - }; +},{"../plugin":13,"./option-assertions":15,"./removed":18}],17:[function(require,module,exports){ +"use strict"; - ConfigChainBuilder.prototype.addConfig = function addConfig(loc, key) { - var json = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _json2.default; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - if (this.resolvedConfigs.indexOf(loc) >= 0) { - return false; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validatePluginObject = validatePluginObject; - this.resolvedConfigs.push(loc); +var _optionAssertions = require("./option-assertions"); - var content = _fs2.default.readFileSync(loc, "utf8"); - var options = void 0; +var VALIDATORS = { + name: _optionAssertions.assertString, + manipulateOptions: _optionAssertions.assertFunction, + pre: _optionAssertions.assertFunction, + post: _optionAssertions.assertFunction, + inherits: _optionAssertions.assertFunction, + visitor: assertVisitorMap, + parserOverride: _optionAssertions.assertFunction, + generatorOverride: _optionAssertions.assertFunction +}; - try { - options = jsonCache[content] = jsonCache[content] || json.parse(content); - if (key) options = options[key]; - } catch (err) { - err.message = loc + ": Error while parsing JSON - " + err.message; - throw err; - } +function assertVisitorMap(key, value) { + var obj = (0, _optionAssertions.assertObject)(key, value); - this.mergeConfig({ - options: options, - alias: loc, - dirname: _path2.default.dirname(loc) + if (obj) { + Object.keys(obj).forEach(function (prop) { + return assertVisitorHandler(prop, obj[prop]); }); - return !!options; - }; - - ConfigChainBuilder.prototype.mergeConfig = function mergeConfig(_ref) { - var options = _ref.options, - alias = _ref.alias, - loc = _ref.loc, - dirname = _ref.dirname; - - if (!options) { - return false; + if (obj.enter || obj.exit) { + throw new Error(".".concat(key, " cannot contain catch-all \"enter\" or \"exit\" handlers. Please target individual nodes.")); } + } - options = (0, _assign2.default)({}, options); - - dirname = dirname || process.cwd(); - loc = loc || alias; + return obj; +} - if (options.extends) { - var extendsLoc = (0, _resolve2.default)(options.extends, dirname); - if (extendsLoc) { - this.addConfig(extendsLoc); - } else { - if (this.log) this.log.error("Couldn't resolve extends clause of " + options.extends + " in " + alias); +function assertVisitorHandler(key, value) { + if (value && _typeof(value) === "object") { + Object.keys(value).forEach(function (handler) { + if (handler !== "enter" && handler !== "exit") { + throw new Error(".visitor[\"".concat(key, "\"] may only have .enter and/or .exit handlers.")); } - delete options.extends; - } - - this.configs.push({ - options: options, - alias: alias, - loc: loc, - dirname: dirname }); + } else if (typeof value !== "function") { + throw new Error(".visitor[\"".concat(key, "\"] must be a function")); + } - var envOpts = void 0; - var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development"; - if (options.env) { - envOpts = options.env[envKey]; - delete options.env; - } + return value; +} - this.mergeConfig({ - options: envOpts, - alias: alias + ".env." + envKey, - dirname: dirname - }); +function validatePluginObject(obj) { + var rootPath = { + type: "root", + source: "plugin" }; + Object.keys(obj).forEach(function (key) { + var validator = VALIDATORS[key]; + var optLoc = { + type: "option", + name: key, + parent: rootPath + }; + if (validator) validator(optLoc, obj[key]);else throw new Error(".".concat(key, " is not a valid Plugin property")); + }); + return obj; +} - return ConfigChainBuilder; -}(); - -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"../../../helpers/resolve":14,"_process":525,"babel-runtime/core-js/object/assign":99,"babel-runtime/helpers/classCallCheck":109,"fs":159,"json5":297,"path":522,"path-is-absolute":523}],21:[function(require,module,exports){ +},{"./option-assertions":15}],18:[function(require,module,exports){ "use strict"; -module.exports = { - filename: { - type: "filename", - description: "filename to use when reading from stdin - this will be used in source-maps, errors etc", - default: "unknown", - shorthand: "f" - }, - - filenameRelative: { - hidden: true, - type: "string" - }, - - inputSourceMap: { - hidden: true - }, - - env: { - hidden: true, - default: {} - }, - - mode: { - description: "", - hidden: true - }, - - retainLines: { - type: "boolean", - default: false, - description: "retain line numbers - will result in really ugly code" - }, - - highlightCode: { - description: "enable/disable ANSI syntax highlighting of code frames (on by default)", - type: "boolean", - default: true - }, - - suppressDeprecationMessages: { - type: "boolean", - default: false, - hidden: true - }, - - presets: { - type: "list", - description: "", - default: [] - }, - - plugins: { - type: "list", - default: [], - description: "" - }, - - ignore: { - type: "list", - description: "list of glob paths to **not** compile", - default: [] - }, - - only: { - type: "list", - description: "list of glob paths to **only** compile" - }, - - code: { - hidden: true, - default: true, - type: "boolean" - }, - - metadata: { - hidden: true, - default: true, - type: "boolean" - }, - - ast: { - hidden: true, - default: true, - type: "boolean" - }, - - extends: { - type: "string", - hidden: true +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = { + auxiliaryComment: { + message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" }, - - comments: { - type: "boolean", - default: true, - description: "write comments to generated output (true by default)" + blacklist: { + message: "Put the specific transforms you want in the `plugins` option" }, - - shouldPrintComment: { - hidden: true, - description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored" + breakConfig: { + message: "This is not a necessary option in Babel 6" }, - - wrapPluginVisitorMethod: { - hidden: true, - description: "optional callback to wrap all visitor methods" + experimental: { + message: "Put the specific transforms you want in the `plugins` option" }, - - compact: { - type: "booleanString", - default: "auto", - description: "do not include superfluous whitespace characters and line terminators [true|false|auto]" + externalHelpers: { + message: "Use the `external-helpers` plugin instead. " + "Check out http://babeljs.io/docs/plugins/external-helpers/" }, - - minified: { - type: "boolean", - default: false, - description: "save as much bytes when printing [true|false]" + extra: { + message: "" }, - - sourceMap: { - alias: "sourceMaps", - hidden: true + jsxPragma: { + message: "use the `pragma` option in the `react-jsx` plugin. " + "Check out http://babeljs.io/docs/plugins/transform-react-jsx/" }, - - sourceMaps: { - type: "booleanString", - description: "[true|false|inline]", - default: false, - shorthand: "s" + loose: { + message: "Specify the `loose` option for the relevant plugin you are using " + "or use a preset that sets the option." }, - - sourceMapTarget: { - type: "string", - description: "set `file` on returned source map" + metadataUsedHelpers: { + message: "Not required anymore as this is enabled by default" }, - - sourceFileName: { - type: "string", - description: "set `sources[0]` on returned source map" + modules: { + message: "Use the corresponding module transform plugin in the `plugins` option. " + "Check out http://babeljs.io/docs/plugins/#modules" }, - - sourceRoot: { - type: "filename", - description: "the root from which all sources are relative" + nonStandard: { + message: "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " + "Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" }, - - babelrc: { - description: "Whether or not to look up .babelrc and .babelignore files", - type: "boolean", - default: true + optional: { + message: "Put the specific transforms you want in the `plugins` option" }, - - sourceType: { - description: "", - default: "module" + sourceMapName: { + message: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves." }, - - auxiliaryCommentBefore: { - type: "string", - description: "print a comment before any injected non-user code" + stage: { + message: "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" }, - - auxiliaryCommentAfter: { - type: "string", - description: "print a comment after any injected non-user code" + whitelist: { + message: "Put the specific transforms you want in the `plugins` option" }, - resolveModuleSource: { - hidden: true - }, - - getModuleId: { - hidden: true - }, - - moduleRoot: { - type: "filename", - description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions" - }, - - moduleIds: { - type: "boolean", - default: false, - shorthand: "M", - description: "insert an explicit id for modules" - }, - - moduleId: { - description: "specify a custom name for module ids", - type: "string" + version: 6, + message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options" }, - - passPerPreset: { - description: "Whether to spawn a traversal pass per a preset. By default all presets are merged.", - type: "boolean", - default: false, - hidden: true - }, - - parserOpts: { - description: "Options to pass into the parser, or to change parsers (parserOpts.parser)", - default: false + metadata: { + version: 6, + message: "Generated plugin metadata is always included in the output result" }, - - generatorOpts: { - description: "Options to pass into the generator, or to change generators (generatorOpts.generator)", - default: false + sourceMapTarget: { + version: 6, + message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves." } }; -},{}],22:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.config = undefined; -exports.normaliseOptions = normaliseOptions; - -var _parsers = require("./parsers"); - -var parsers = _interopRequireWildcard(_parsers); - -var _config = require("./config"); - -var _config2 = _interopRequireDefault(_config); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -exports.config = _config2.default; -function normaliseOptions() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - for (var key in options) { - var val = options[key]; - if (val == null) continue; - - var opt = _config2.default[key]; - if (opt && opt.alias) opt = _config2.default[opt.alias]; - if (!opt) continue; - - var parser = parsers[opt.type]; - if (parser) val = parser(val); - - options[key] = val; - } +exports.default = _default; - return options; -} -},{"./config":21,"./parsers":24}],23:[function(require,module,exports){ -(function (process){ +},{}],19:[function(require,module,exports){ "use strict"; -exports.__esModule = true; - -var _objectWithoutProperties2 = require("babel-runtime/helpers/objectWithoutProperties"); - -var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _node = require("../../../api/node"); - -var context = _interopRequireWildcard(_node); - -var _plugin2 = require("../../plugin"); - -var _plugin3 = _interopRequireDefault(_plugin2); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _index = require("./index"); - -var _resolvePlugin = require("../../../helpers/resolve-plugin"); - -var _resolvePlugin2 = _interopRequireDefault(_resolvePlugin); - -var _resolvePreset = require("../../../helpers/resolve-preset"); - -var _resolvePreset2 = _interopRequireDefault(_resolvePreset); - -var _cloneDeepWith = require("lodash/cloneDeepWith"); - -var _cloneDeepWith2 = _interopRequireDefault(_cloneDeepWith); - -var _clone = require("lodash/clone"); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var _clone2 = _interopRequireDefault(_clone); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -var _merge = require("../../../helpers/merge"); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -var _merge2 = _interopRequireDefault(_merge); - -var _config2 = require("./config"); - -var _config3 = _interopRequireDefault(_config2); - -var _removed = require("./removed"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Plugin = Plugin; +Object.defineProperty(exports, "File", { + enumerable: true, + get: function get() { + return _file.default; + } +}); +Object.defineProperty(exports, "buildExternalHelpers", { + enumerable: true, + get: function get() { + return _buildExternalHelpers.default; + } +}); +Object.defineProperty(exports, "resolvePlugin", { + enumerable: true, + get: function get() { + return _files.resolvePlugin; + } +}); +Object.defineProperty(exports, "resolvePreset", { + enumerable: true, + get: function get() { + return _files.resolvePreset; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function get() { + return _package.version; + } +}); +Object.defineProperty(exports, "getEnv", { + enumerable: true, + get: function get() { + return _environment.getEnv; + } +}); +Object.defineProperty(exports, "tokTypes", { + enumerable: true, + get: function get() { + return _parser().tokTypes; + } +}); +Object.defineProperty(exports, "traverse", { + enumerable: true, + get: function get() { + return _traverse().default; + } +}); +Object.defineProperty(exports, "template", { + enumerable: true, + get: function get() { + return _template().default; + } +}); +Object.defineProperty(exports, "createConfigItem", { + enumerable: true, + get: function get() { + return _item.createConfigItem; + } +}); +Object.defineProperty(exports, "loadPartialConfig", { + enumerable: true, + get: function get() { + return _config.loadPartialConfig; + } +}); +Object.defineProperty(exports, "loadOptions", { + enumerable: true, + get: function get() { + return _config.loadOptions; + } +}); +Object.defineProperty(exports, "transform", { + enumerable: true, + get: function get() { + return _transform.transform; + } +}); +Object.defineProperty(exports, "transformSync", { + enumerable: true, + get: function get() { + return _transform.transformSync; + } +}); +Object.defineProperty(exports, "transformAsync", { + enumerable: true, + get: function get() { + return _transform.transformAsync; + } +}); +Object.defineProperty(exports, "transformFile", { + enumerable: true, + get: function get() { + return _transformFile.transformFile; + } +}); +Object.defineProperty(exports, "transformFileSync", { + enumerable: true, + get: function get() { + return _transformFile.transformFileSync; + } +}); +Object.defineProperty(exports, "transformFileAsync", { + enumerable: true, + get: function get() { + return _transformFile.transformFileAsync; + } +}); +Object.defineProperty(exports, "transformFromAst", { + enumerable: true, + get: function get() { + return _transformAst.transformFromAst; + } +}); +Object.defineProperty(exports, "transformFromAstSync", { + enumerable: true, + get: function get() { + return _transformAst.transformFromAstSync; + } +}); +Object.defineProperty(exports, "transformFromAstAsync", { + enumerable: true, + get: function get() { + return _transformAst.transformFromAstAsync; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parse.parse; + } +}); +Object.defineProperty(exports, "parseSync", { + enumerable: true, + get: function get() { + return _parse.parseSync; + } +}); +Object.defineProperty(exports, "parseAsync", { + enumerable: true, + get: function get() { + return _parse.parseAsync; + } +}); +exports.types = exports.OptionManager = exports.DEFAULT_EXTENSIONS = void 0; -var _removed2 = _interopRequireDefault(_removed); +var _file = _interopRequireDefault(require("./transformation/file/file")); -var _buildConfigChain = require("./build-config-chain"); +var _buildExternalHelpers = _interopRequireDefault(require("./tools/build-external-helpers")); -var _buildConfigChain2 = _interopRequireDefault(_buildConfigChain); +var _files = require("./config/files"); -var _path = require("path"); +var _package = require("../package.json"); -var _path2 = _interopRequireDefault(_path); +var _environment = require("./config/helpers/environment"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _types() { + var data = _interopRequireWildcard(require("@babel/types")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _types = function _types() { + return data; + }; -var OptionManager = function () { - function OptionManager(log) { - (0, _classCallCheck3.default)(this, OptionManager); + return data; +} - this.resolvedConfigs = []; - this.options = OptionManager.createBareOptions(); - this.log = log; +Object.defineProperty(exports, "types", { + enumerable: true, + get: function get() { + return _types(); } +}); - OptionManager.memoisePluginContainer = function memoisePluginContainer(fn, loc, i, alias) { - for (var _iterator = OptionManager.memoisedPlugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var cache = _ref; +function _parser() { + var data = require("@babel/parser"); - if (cache.container === fn) return cache.plugin; - } + _parser = function _parser() { + return data; + }; - var obj = void 0; + return data; +} - if (typeof fn === "function") { - obj = fn(context); - } else { - obj = fn; - } +function _traverse() { + var data = _interopRequireDefault(require("@babel/traverse")); - if ((typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) === "object") { - var _plugin = new _plugin3.default(obj, alias); - OptionManager.memoisedPlugins.push({ - container: fn, - plugin: _plugin - }); - return _plugin; - } else { - throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) + loc + i); - } + _traverse = function _traverse() { + return data; }; - OptionManager.createBareOptions = function createBareOptions() { - var opts = {}; + return data; +} - for (var _key in _config3.default) { - var opt = _config3.default[_key]; - opts[_key] = (0, _clone2.default)(opt.default); - } +function _template() { + var data = _interopRequireDefault(require("@babel/template")); - return opts; + _template = function _template() { + return data; }; - OptionManager.normalisePlugin = function normalisePlugin(plugin, loc, i, alias) { - plugin = plugin.__esModule ? plugin.default : plugin; - - if (!(plugin instanceof _plugin3.default)) { - if (typeof plugin === "function" || (typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin)) === "object") { - plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias); - } else { - throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin))); - } - } - - plugin.init(loc, i); + return data; +} - return plugin; - }; +var _item = require("./config/item"); - OptionManager.normalisePlugins = function normalisePlugins(loc, dirname, plugins) { - return plugins.map(function (val, i) { - var plugin = void 0, - options = void 0; +var _config = require("./config"); - if (!val) { - throw new TypeError("Falsy value found in plugins"); - } +var _transform = require("./transform"); - if (Array.isArray(val)) { - plugin = val[0]; - options = val[1]; - } else { - plugin = val; - } +var _transformFile = require("./transform-file"); - var alias = typeof plugin === "string" ? plugin : loc + "$" + i; +var _transformAst = require("./transform-ast"); - if (typeof plugin === "string") { - var pluginLoc = (0, _resolvePlugin2.default)(plugin, dirname); - if (pluginLoc) { - plugin = require(pluginLoc); - } else { - throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname)); - } - } +var _parse = require("./parse"); - plugin = OptionManager.normalisePlugin(plugin, loc, i, alias); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - return [plugin, options]; - }); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; - OptionManager.prototype.mergeOptions = function mergeOptions(_ref2) { - var _this = this; + return cache; +} - var rawOpts = _ref2.options, - extendingOpts = _ref2.extending, - alias = _ref2.alias, - loc = _ref2.loc, - dirname = _ref2.dirname; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - alias = alias || "foreign"; - if (!rawOpts) return; + var cache = _getRequireWildcardCache(); - if ((typeof rawOpts === "undefined" ? "undefined" : (0, _typeof3.default)(rawOpts)) !== "object" || Array.isArray(rawOpts)) { - this.log.error("Invalid options type for " + alias, TypeError); - } + if (cache && cache.has(obj)) { + return cache.get(obj); + } - var opts = (0, _cloneDeepWith2.default)(rawOpts, function (val) { - if (val instanceof _plugin3.default) { - return val; - } - }); + var newObj = {}; - dirname = dirname || process.cwd(); - loc = loc || alias; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var _key2 in opts) { - var option = _config3.default[_key2]; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (!option && this.log) { - if (_removed2.default[_key2]) { - this.log.error("Using removed Babel 5 option: " + alias + "." + _key2 + " - " + _removed2.default[_key2].message, ReferenceError); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); } else { - var unknownOptErr = "Unknown option: " + alias + "." + _key2 + ". Check out http://babeljs.io/docs/usage/options/ for more information about options."; - var presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options."; - - - this.log.error(unknownOptErr + "\n\n" + presetConfigErr, ReferenceError); + newObj[key] = obj[key]; } } } + } - (0, _index.normaliseOptions)(opts); - - if (opts.plugins) { - opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins); - } - - if (opts.presets) { - if (opts.passPerPreset) { - opts.presets = this.resolvePresets(opts.presets, dirname, function (preset, presetLoc) { - _this.mergeOptions({ - options: preset, - extending: preset, - alias: presetLoc, - loc: presetLoc, - dirname: dirname - }); - }); - } else { - this.mergePresets(opts.presets, dirname); - delete opts.presets; - } - } + newObj.default = obj; - if (rawOpts === extendingOpts) { - (0, _assign2.default)(extendingOpts, opts); - } else { - (0, _merge2.default)(extendingOpts || this.options, opts); - } - }; + if (cache) { + cache.set(obj, newObj); + } - OptionManager.prototype.mergePresets = function mergePresets(presets, dirname) { - var _this2 = this; + return newObj; +} - this.resolvePresets(presets, dirname, function (presetOpts, presetLoc) { - _this2.mergeOptions({ - options: presetOpts, - alias: presetLoc, - loc: presetLoc, - dirname: _path2.default.dirname(presetLoc || "") - }); - }); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - OptionManager.prototype.resolvePresets = function resolvePresets(presets, dirname, onResolve) { - return presets.map(function (val) { - var options = void 0; - if (Array.isArray(val)) { - if (val.length > 2) { - throw new Error("Unexpected extra options " + (0, _stringify2.default)(val.slice(2)) + " passed to preset."); - } +var DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]); +exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS; - var _val = val; - val = _val[0]; - options = _val[1]; - } +var OptionManager = +/*#__PURE__*/ +function () { + function OptionManager() { + _classCallCheck(this, OptionManager); + } - var presetLoc = void 0; - try { - if (typeof val === "string") { - presetLoc = (0, _resolvePreset2.default)(val, dirname); + _createClass(OptionManager, [{ + key: "init", + value: function init(opts) { + return (0, _config.loadOptions)(opts); + } + }]); - if (!presetLoc) { - throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname)); - } + return OptionManager; +}(); - val = require(presetLoc); - } +exports.OptionManager = OptionManager; - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.__esModule) { - if (val.default) { - val = val.default; - } else { - var _val2 = val, - __esModule = _val2.__esModule, - rest = (0, _objectWithoutProperties3.default)(_val2, ["__esModule"]); +function Plugin(alias) { + throw new Error("The (".concat(alias, ") Babel 5 plugin is being run with an unsupported Babel version.")); +} - val = rest; - } - } +},{"../package.json":37,"./config":9,"./config/files":5,"./config/helpers/environment":8,"./config/item":10,"./parse":20,"./tools/build-external-helpers":21,"./transform":24,"./transform-ast":22,"./transform-file":23,"./transformation/file/file":26,"@babel/parser":89,"@babel/template":167,"@babel/traverse":176,"@babel/types":242}],20:[function(require,module,exports){ +(function (process){ +"use strict"; - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.buildPreset) val = val.buildPreset; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseSync = parseSync; +exports.parseAsync = parseAsync; +exports.parse = void 0; - if (typeof val !== "function" && options !== undefined) { - throw new Error("Options " + (0, _stringify2.default)(options) + " passed to " + (presetLoc || "a preset") + " which does not accept options."); - } +var _config = _interopRequireDefault(require("./config")); - if (typeof val === "function") val = val(context, options, { dirname: dirname }); +var _normalizeFile = _interopRequireDefault(require("./transformation/normalize-file")); - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) !== "object") { - throw new Error("Unsupported preset format: " + val + "."); - } +var _normalizeOpts = _interopRequireDefault(require("./transformation/normalize-opts")); - onResolve && onResolve(val, presetLoc); - } catch (e) { - if (presetLoc) { - e.message += " (While processing preset: " + (0, _stringify2.default)(presetLoc) + ")"; - } - throw e; - } - return val; - }); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} + +var parse = function parse(code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } - OptionManager.prototype.normaliseOptions = function normaliseOptions() { - var opts = this.options; + if (callback === undefined) return parseSync(code, opts); + var config = (0, _config.default)(opts); - for (var _key3 in _config3.default) { - var option = _config3.default[_key3]; - var val = opts[_key3]; + if (config === null) { + return null; + } - if (!val && option.optional) continue; + var cb = callback; + process.nextTick(function () { + var ast = null; - if (option.alias) { - opts[option.alias] = opts[option.alias] || val; - } else { - opts[_key3] = val; - } + try { + var cfg = (0, _config.default)(opts); + if (cfg === null) return cb(null, null); + ast = (0, _normalizeFile.default)(cfg.passes, (0, _normalizeOpts.default)(cfg), code).ast; + } catch (err) { + return cb(err); } - }; - - OptionManager.prototype.init = function init() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - for (var _iterator2 = (0, _buildConfigChain2.default)(opts, this.log), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; + cb(null, ast); + }); +}; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } +exports.parse = parse; - var _config = _ref3; +function parseSync(code, opts) { + var config = (0, _config.default)(opts); - this.mergeOptions(_config); - } + if (config === null) { + return null; + } - this.normaliseOptions(opts); + return (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code).ast; +} - return this.options; - }; +function parseAsync(code, opts) { + return new Promise(function (res, rej) { + parse(code, opts, function (err, result) { + if (err == null) res(result);else rej(err); + }); + }); +} - return OptionManager; -}(); +}).call(this,require('_process')) +},{"./config":9,"./transformation/normalize-file":30,"./transformation/normalize-opts":31,"_process":1054}],21:[function(require,module,exports){ +"use strict"; -exports.default = OptionManager; +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } -OptionManager.memoisedPlugins = []; -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"../../../api/node":6,"../../../helpers/merge":9,"../../../helpers/resolve-plugin":12,"../../../helpers/resolve-preset":13,"../../plugin":30,"./build-config-chain":20,"./config":21,"./index":22,"./removed":25,"_process":525,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/core-js/object/assign":99,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/objectWithoutProperties":111,"babel-runtime/helpers/typeof":113,"lodash/clone":466,"lodash/cloneDeepWith":468,"path":522}],24:[function(require,module,exports){ -"use strict"; +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -exports.__esModule = true; -exports.filename = undefined; -exports.boolean = boolean; -exports.booleanString = booleanString; -exports.list = list; +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } -var _slash = require("slash"); +function _templateObject() { + var data = _taggedTemplateLiteral(["\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n "]); -var _slash2 = _interopRequireDefault(_slash); + _templateObject = function _templateObject() { + return data; + }; -var _util = require("../../../util"); + return data; +} -var util = _interopRequireWildcard(_util); +function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function helpers() { + var data = _interopRequireWildcard(require("@babel/helpers")); -var filename = exports.filename = _slash2.default; + helpers = function helpers() { + return data; + }; -function boolean(val) { - return !!val; + return data; } -function booleanString(val) { - return util.booleanify(val); +function _generator() { + var data = _interopRequireDefault(require("@babel/generator")); + + _generator = function _generator() { + return data; + }; + + return data; } -function list(val) { - return util.list(val); +function _template() { + var data = _interopRequireDefault(require("@babel/template")); + + _template = function _template() { + return data; + }; + + return data; } -},{"../../../util":31,"slash":541}],25:[function(require,module,exports){ -"use strict"; -module.exports = { - "auxiliaryComment": { - "message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" - }, - "blacklist": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "breakConfig": { - "message": "This is not a necessary option in Babel 6" - }, - "experimental": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "externalHelpers": { - "message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/" - }, - "extra": { - "message": "" - }, - "jsxPragma": { - "message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/" - }, +function t() { + var data = _interopRequireWildcard(require("@babel/types")); - "loose": { - "message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option." - }, - "metadataUsedHelpers": { - "message": "Not required anymore as this is enabled by default" - }, - "modules": { - "message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules" - }, - "nonStandard": { - "message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" - }, - "optional": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "sourceMapName": { - "message": "Use the `sourceMapTarget` option" - }, - "stage": { - "message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" - }, - "whitelist": { - "message": "Put the specific transforms you want in the `plugins` option" - } -}; -},{}],26:[function(require,module,exports){ -"use strict"; + t = function t() { + return data; + }; -exports.__esModule = true; + return data; +} -var _plugin = require("../plugin"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} -var _plugin2 = _interopRequireDefault(_plugin); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -var _sortBy = require("lodash/sortBy"); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; -var _sortBy2 = _interopRequireDefault(_sortBy); + return cache; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -exports.default = new _plugin2.default({ + var cache = _getRequireWildcardCache(); - name: "internal.blockHoist", + if (cache && cache.has(obj)) { + return cache.get(obj); + } - visitor: { - Block: { - exit: function exit(_ref) { - var node = _ref.node; + var newObj = {}; - var hasChange = false; - for (var i = 0; i < node.body.length; i++) { - var bodyNode = node.body[i]; - if (bodyNode && bodyNode._blockHoist != null) { - hasChange = true; - break; - } - } - if (!hasChange) return; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - node.body = (0, _sortBy2.default)(node.body, function (bodyNode) { - var priority = bodyNode && bodyNode._blockHoist; - if (priority == null) priority = 1; - if (priority === true) priority = 2; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - return -1 * priority; - }); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } } } -}); -module.exports = exports["default"]; -},{"../plugin":30,"lodash/sortBy":508}],27:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; + newObj.default = obj; -var _symbol = require("babel-runtime/core-js/symbol"); + if (cache) { + cache.set(obj, newObj); + } -var _symbol2 = _interopRequireDefault(_symbol); + return newObj; +} -var _plugin = require("../plugin"); +var buildUmdWrapper = function buildUmdWrapper(replacements) { + return _template().default(_templateObject())(replacements); +}; -var _plugin2 = _interopRequireDefault(_plugin); +function buildGlobal(whitelist) { + var namespace = t().identifier("babelHelpers"); + var body = []; + var container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body)); + var tree = t().program([t().expressionStatement(t().callExpression(container, [t().conditionalExpression(t().binaryExpression("===", t().unaryExpression("typeof", t().identifier("global")), t().stringLiteral("undefined")), t().identifier("self"), t().identifier("global"))]))]); + body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().assignmentExpression("=", t().memberExpression(t().identifier("global"), namespace), t().objectExpression([])))])); + buildHelpers(body, namespace, whitelist); + return tree; +} -var _babelTypes = require("babel-types"); +function buildModule(whitelist) { + var body = []; + var refs = buildHelpers(body, null, whitelist); + body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(function (name) { + return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name)); + }))); + return t().program(body, [], "module"); +} -var t = _interopRequireWildcard(_babelTypes); +function buildUmd(whitelist) { + var namespace = t().identifier("babelHelpers"); + var body = []; + body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))])); + buildHelpers(body, namespace, whitelist); + return t().program([buildUmdWrapper({ + FACTORY_PARAMETERS: t().identifier("global"), + BROWSER_ARGUMENTS: t().assignmentExpression("=", t().memberExpression(t().identifier("root"), namespace), t().objectExpression([])), + COMMON_ARGUMENTS: t().identifier("exports"), + AMD_ARGUMENTS: t().arrayExpression([t().stringLiteral("exports")]), + FACTORY_BODY: body, + UMD_ROOT: t().identifier("this") + })]); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function buildVar(whitelist) { + var namespace = t().identifier("babelHelpers"); + var body = []; + body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))])); + var tree = t().program(body); + buildHelpers(body, namespace, whitelist); + body.push(t().expressionStatement(namespace)); + return tree; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function buildHelpers(body, namespace, whitelist) { + var getHelperReference = function getHelperReference(name) { + return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier("_".concat(name)); + }; -var SUPER_THIS_BOUND = (0, _symbol2.default)("super this bound"); + var refs = {}; + helpers().list.forEach(function (name) { + if (whitelist && whitelist.indexOf(name) < 0) return; + var ref = refs[name] = getHelperReference(name); -var superVisitor = { - CallExpression: function CallExpression(path) { - if (!path.get("callee").isSuper()) return; + var _helpers$get = helpers().get(name, getHelperReference, ref), + nodes = _helpers$get.nodes; - var node = path.node; + body.push.apply(body, _toConsumableArray(nodes)); + }); + return refs; +} - if (node[SUPER_THIS_BOUND]) return; - node[SUPER_THIS_BOUND] = true; +function _default(whitelist) { + var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "global"; + var tree; + var build = { + global: buildGlobal, + module: buildModule, + umd: buildUmd, + var: buildVar + }[outputType]; - path.replaceWith(t.assignmentExpression("=", this.id, node)); + if (build) { + tree = build(whitelist); + } else { + throw new Error("Unsupported output type ".concat(outputType)); } -}; -exports.default = new _plugin2.default({ - name: "internal.shadowFunctions", + return (0, _generator().default)(tree).code; +} - visitor: { - ThisExpression: function ThisExpression(path) { - remap(path, "this"); - }, - ReferencedIdentifier: function ReferencedIdentifier(path) { - if (path.node.name === "arguments") { - remap(path, "arguments"); - } - } - } +},{"@babel/generator":51,"@babel/helpers":87,"@babel/template":167,"@babel/types":242}],22:[function(require,module,exports){ +(function (process){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true }); +exports.transformFromAstSync = transformFromAstSync; +exports.transformFromAstAsync = transformFromAstAsync; +exports.transformFromAst = void 0; +var _config = _interopRequireDefault(require("./config")); -function shouldShadow(path, shadowPath) { - if (path.is("_forceShadow")) { - return true; - } else { - return shadowPath; - } -} +var _transformation = require("./transformation"); -function remap(path, key) { - var shadowPath = path.inShadow(key); - if (!shouldShadow(path, shadowPath)) return; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - var shadowFunction = path.node._shadowedFunctionLiteral; +var transformFromAst = function transformFromAst(ast, code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } - var currentFunction = void 0; - var passedShadowFunction = false; + if (callback === undefined) return transformFromAstSync(ast, code, opts); + var cb = callback; + process.nextTick(function () { + var cfg; - var fnPath = path.find(function (innerPath) { - if (innerPath.parentPath && innerPath.parentPath.isClassProperty() && innerPath.key === "value") { - return true; - } - if (path === innerPath) return false; - if (innerPath.isProgram() || innerPath.isFunction()) { - currentFunction = currentFunction || innerPath; + try { + cfg = (0, _config.default)(opts); + if (cfg === null) return cb(null, null); + } catch (err) { + return cb(err); } - if (innerPath.isProgram()) { - passedShadowFunction = true; + if (!ast) return cb(new Error("No AST given")); + (0, _transformation.runAsync)(cfg, code, ast, cb); + }); +}; - return true; - } else if (innerPath.isFunction() && !innerPath.isArrowFunctionExpression()) { - if (shadowFunction) { - if (innerPath === shadowFunction || innerPath.node === shadowFunction.node) return true; - } else { - if (!innerPath.is("shadow")) return true; - } +exports.transformFromAst = transformFromAst; - passedShadowFunction = true; - return false; - } +function transformFromAstSync(ast, code, opts) { + var config = (0, _config.default)(opts); + if (config === null) return null; + if (!ast) throw new Error("No AST given"); + return (0, _transformation.runSync)(config, code, ast); +} - return false; +function transformFromAstAsync(ast, code, opts) { + return new Promise(function (res, rej) { + transformFromAst(ast, code, opts, function (err, result) { + if (err == null) res(result);else rej(err); + }); }); +} - if (shadowFunction && fnPath.isProgram() && !shadowFunction.isProgram()) { - fnPath = path.findParent(function (p) { - return p.isProgram() || p.isFunction(); - }); - } +}).call(this,require('_process')) +},{"./config":9,"./transformation":29,"_process":1054}],23:[function(require,module,exports){ +"use strict"; - if (fnPath === currentFunction) return; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFileSync = transformFileSync; +exports.transformFileAsync = transformFileAsync; +exports.transformFile = void 0; - if (!passedShadowFunction) return; +var transformFile = function transformFile(filename, opts, callback) { + if (typeof opts === "function") { + callback = opts; + } - var cached = fnPath.getData(key); - if (cached) return path.replaceWith(cached); + callback(new Error("Transforming files is not supported in browsers"), null); +}; - var id = path.scope.generateUidIdentifier(key); +exports.transformFile = transformFile; - fnPath.setData(key, id); +function transformFileSync() { + throw new Error("Transforming files is not supported in browsers"); +} - var classPath = fnPath.findParent(function (p) { - return p.isClass(); - }); - var hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass); +function transformFileAsync() { + return Promise.reject(new Error("Transforming files is not supported in browsers")); +} - if (key === "this" && fnPath.isMethod({ kind: "constructor" }) && hasSuperClass) { - fnPath.scope.push({ id: id }); +},{}],24:[function(require,module,exports){ +(function (process){ +"use strict"; - fnPath.traverse(superVisitor, { id: id }); - } else { - var init = key === "this" ? t.thisExpression() : t.identifier(key); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformSync = transformSync; +exports.transformAsync = transformAsync; +exports.transform = void 0; - if (shadowFunction) init._shadowedFunctionLiteral = shadowFunction; +var _config = _interopRequireDefault(require("./config")); - fnPath.scope.push({ id: id, init: init }); - } +var _transformation = require("./transformation"); - return path.replaceWith(id); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; } -module.exports = exports["default"]; -},{"../plugin":30,"babel-runtime/core-js/symbol":104,"babel-types":151}],28:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _normalizeAst = require("../helpers/normalize-ast"); +var transform = function transform(code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } -var _normalizeAst2 = _interopRequireDefault(_normalizeAst); + if (callback === undefined) return transformSync(code, opts); + var cb = callback; + process.nextTick(function () { + var cfg; -var _plugin = require("./plugin"); + try { + cfg = (0, _config.default)(opts); + if (cfg === null) return cb(null, null); + } catch (err) { + return cb(err); + } -var _plugin2 = _interopRequireDefault(_plugin); + (0, _transformation.runAsync)(cfg, code, null, cb); + }); +}; -var _file = require("./file"); +exports.transform = transform; -var _file2 = _interopRequireDefault(_file); +function transformSync(code, opts) { + var config = (0, _config.default)(opts); + if (config === null) return null; + return (0, _transformation.runSync)(config, code); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function transformAsync(code, opts) { + return new Promise(function (res, rej) { + transform(code, opts, function (err, result) { + if (err == null) res(result);else rej(err); + }); + }); +} -var Pipeline = function () { - function Pipeline() { - (0, _classCallCheck3.default)(this, Pipeline); - } +}).call(this,require('_process')) +},{"./config":9,"./transformation":29,"_process":1054}],25:[function(require,module,exports){ +"use strict"; - Pipeline.prototype.lint = function lint(code) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadBlockHoistPlugin; - opts.code = false; - opts.mode = "lint"; - return this.transform(code, opts); - }; +function _sortBy() { + var data = _interopRequireDefault(require("lodash/sortBy")); - Pipeline.prototype.pretransform = function pretransform(code, opts) { - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.parseCode(code); - return file; - }); + _sortBy = function _sortBy() { + return data; }; - Pipeline.prototype.transform = function transform(code, opts) { - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.parseCode(code); - return file.transform(); - }); - }; + return data; +} - Pipeline.prototype.analyse = function analyse(code) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var visitor = arguments[2]; +var _config = _interopRequireDefault(require("../config")); - opts.code = false; - if (visitor) { - opts.plugins = opts.plugins || []; - opts.plugins.push(new _plugin2.default({ visitor: visitor })); - } - return this.transform(code, opts).metadata; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - Pipeline.prototype.transformFromAst = function transformFromAst(ast, code, opts) { - ast = (0, _normalizeAst2.default)(ast); +var LOADED_PLUGIN; - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.addAst(ast); - return file.transform(); +function loadBlockHoistPlugin() { + if (!LOADED_PLUGIN) { + var config = (0, _config.default)({ + babelrc: false, + configFile: false, + plugins: [blockHoistPlugin] }); - }; + LOADED_PLUGIN = config ? config.passes[0][0] : undefined; + if (!LOADED_PLUGIN) throw new Error("Assertion failure"); + } - return Pipeline; -}(); + return LOADED_PLUGIN; +} -exports.default = Pipeline; -module.exports = exports["default"]; -},{"../helpers/normalize-ast":10,"./file":17,"./plugin":30,"babel-runtime/helpers/classCallCheck":109}],29:[function(require,module,exports){ -"use strict"; +var blockHoistPlugin = { + name: "internal.blockHoist", + visitor: { + Block: { + exit: function exit(_ref) { + var node = _ref.node; + var hasChange = false; -exports.__esModule = true; + for (var i = 0; i < node.body.length; i++) { + var bodyNode = node.body[i]; + + if (bodyNode && bodyNode._blockHoist != null) { + hasChange = true; + break; + } + } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + if (!hasChange) return; + node.body = (0, _sortBy().default)(node.body, function (bodyNode) { + var priority = bodyNode && bodyNode._blockHoist; + if (priority == null) priority = 1; + if (priority === true) priority = 2; + return -1 * priority; + }); + } + } + } +}; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +},{"../config":9,"lodash/sortBy":1040}],26:[function(require,module,exports){ +"use strict"; -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -var _inherits2 = require("babel-runtime/helpers/inherits"); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -var _inherits3 = _interopRequireDefault(_inherits2); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; -var _store = require("../store"); +function helpers() { + var data = _interopRequireWildcard(require("@babel/helpers")); -var _store2 = _interopRequireDefault(_store); + helpers = function helpers() { + return data; + }; -var _file5 = require("./file"); + return data; +} -var _file6 = _interopRequireDefault(_file5); +function _traverse() { + var data = _interopRequireWildcard(require("@babel/traverse")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _traverse = function _traverse() { + return data; + }; -var PluginPass = function (_Store) { - (0, _inherits3.default)(PluginPass, _Store); + return data; +} - function PluginPass(file, plugin) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - (0, _classCallCheck3.default)(this, PluginPass); +function _codeFrame() { + var data = require("@babel/code-frame"); - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + _codeFrame = function _codeFrame() { + return data; + }; - _this.plugin = plugin; - _this.key = plugin.key; - _this.file = file; - _this.opts = options; - return _this; - } + return data; +} - PluginPass.prototype.addHelper = function addHelper() { - var _file; +function t() { + var data = _interopRequireWildcard(require("@babel/types")); - return (_file = this.file).addHelper.apply(_file, arguments); + t = function t() { + return data; }; - PluginPass.prototype.addImport = function addImport() { - var _file2; + return data; +} + +function _semver() { + var data = _interopRequireDefault(require("semver")); - return (_file2 = this.file).addImport.apply(_file2, arguments); + _semver = function _semver() { + return data; }; - PluginPass.prototype.getModuleName = function getModuleName() { - var _file3; + return data; +} - return (_file3 = this.file).getModuleName.apply(_file3, arguments); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - PluginPass.prototype.buildCodeFrameError = function buildCodeFrameError() { - var _file4; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - return (_file4 = this.file).buildCodeFrameError.apply(_file4, arguments); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; - return PluginPass; -}(_store2.default); + return cache; +} -exports.default = PluginPass; -module.exports = exports["default"]; -},{"../store":15,"./file":17,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112}],30:[function(require,module,exports){ -"use strict"; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -exports.__esModule = true; + var cache = _getRequireWildcardCache(); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + var newObj = {}; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + newObj.default = obj; -var _inherits2 = require("babel-runtime/helpers/inherits"); + if (cache) { + cache.set(obj, newObj); + } -var _inherits3 = _interopRequireDefault(_inherits2); + return newObj; +} -var _optionManager = require("./file/options/option-manager"); +var errorVisitor = { + enter: function enter(path, state) { + var loc = path.node.loc; -var _optionManager2 = _interopRequireDefault(_optionManager); + if (loc) { + state.loc = loc; + path.stop(); + } + } +}; -var _babelMessages = require("babel-messages"); +var File = +/*#__PURE__*/ +function () { + function File(options, _ref) { + var _this = this; -var messages = _interopRequireWildcard(_babelMessages); + var code = _ref.code, + ast = _ref.ast, + inputMap = _ref.inputMap; + + _classCallCheck(this, File); + + this._map = new Map(); + this.declarations = {}; + this.path = null; + this.ast = {}; + this.metadata = {}; + this.code = ""; + this.inputMap = null; + this.hub = { + file: this, + getCode: function getCode() { + return _this.code; + }, + getScope: function getScope() { + return _this.scope; + }, + addHelper: this.addHelper.bind(this), + buildError: this.buildCodeFrameError.bind(this) + }; + this.opts = options; + this.code = code; + this.ast = ast; + this.inputMap = inputMap; + this.path = _traverse().NodePath.get({ + hub: this.hub, + parentPath: null, + parent: this.ast, + container: this.ast, + key: "program" + }).setContext(); + this.scope = this.path.scope; + } -var _store = require("../store"); + _createClass(File, [{ + key: "set", + value: function set(key, val) { + if (key === "helpersNamespace") { + throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'."); + } -var _store2 = _interopRequireDefault(_store); - -var _babelTraverse = require("babel-traverse"); - -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + this._map.set(key, val); + } + }, { + key: "get", + value: function get(key) { + return this._map.get(key); + } + }, { + key: "has", + value: function has(key) { + return this._map.has(key); + } + }, { + key: "getModuleName", + value: function getModuleName() { + var _this$opts = this.opts, + filename = _this$opts.filename, + _this$opts$filenameRe = _this$opts.filenameRelative, + filenameRelative = _this$opts$filenameRe === void 0 ? filename : _this$opts$filenameRe, + moduleId = _this$opts.moduleId, + _this$opts$moduleIds = _this$opts.moduleIds, + moduleIds = _this$opts$moduleIds === void 0 ? !!moduleId : _this$opts$moduleIds, + getModuleId = _this$opts.getModuleId, + sourceRootTmp = _this$opts.sourceRoot, + _this$opts$moduleRoot = _this$opts.moduleRoot, + moduleRoot = _this$opts$moduleRoot === void 0 ? sourceRootTmp : _this$opts$moduleRoot, + _this$opts$sourceRoot = _this$opts.sourceRoot, + sourceRoot = _this$opts$sourceRoot === void 0 ? moduleRoot : _this$opts$sourceRoot; + if (!moduleIds) return null; -var _assign = require("lodash/assign"); + if (moduleId != null && !getModuleId) { + return moduleId; + } -var _assign2 = _interopRequireDefault(_assign); + var moduleName = moduleRoot != null ? moduleRoot + "/" : ""; -var _clone = require("lodash/clone"); + if (filenameRelative) { + var sourceRootReplacer = sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : ""; + moduleName += filenameRelative.replace(sourceRootReplacer, "").replace(/\.(\w*?)$/, ""); + } -var _clone2 = _interopRequireDefault(_clone); + moduleName = moduleName.replace(/\\/g, "/"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (getModuleId) { + return getModuleId(moduleName) || moduleName; + } else { + return moduleName; + } + } + }, { + key: "addImport", + value: function addImport() { + throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'."); + } + }, { + key: "availableHelper", + value: function availableHelper(name, versionRange) { + var minVersion; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + try { + minVersion = helpers().minVersion(name); + } catch (err) { + if (err.code !== "BABEL_HELPER_UNKNOWN") throw err; + return false; + } -var GLOBAL_VISITOR_PROPS = ["enter", "exit"]; + if (typeof versionRange !== "string") return true; + if (_semver().default.valid(versionRange)) versionRange = "^".concat(versionRange); + return !_semver().default.intersects("<".concat(minVersion), versionRange) && !_semver().default.intersects(">=8.0.0", versionRange); + } + }, { + key: "addHelper", + value: function addHelper(name) { + var _this2 = this; -var Plugin = function (_Store) { - (0, _inherits3.default)(Plugin, _Store); + var declar = this.declarations[name]; + if (declar) return t().cloneNode(declar); + var generator = this.get("helperGenerator"); - function Plugin(plugin, key) { - (0, _classCallCheck3.default)(this, Plugin); + if (generator) { + var res = generator(name); + if (res) return res; + } - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + helpers().ensure(name); + var uid = this.declarations[name] = this.scope.generateUidIdentifier(name); + var dependencies = {}; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - _this.initialized = false; - _this.raw = (0, _assign2.default)({}, plugin); - _this.key = _this.take("name") || key; + try { + for (var _iterator = helpers().getDependencies(name)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var dep = _step.value; + dependencies[dep] = this.addHelper(dep); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } - _this.manipulateOptions = _this.take("manipulateOptions"); - _this.post = _this.take("post"); - _this.pre = _this.take("pre"); - _this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {}); - return _this; - } + var _helpers$get = helpers().get(name, function (dep) { + return dependencies[dep]; + }, uid, Object.keys(this.scope.getAllBindings())), + nodes = _helpers$get.nodes, + globals = _helpers$get.globals; - Plugin.prototype.take = function take(key) { - var val = this.raw[key]; - delete this.raw[key]; - return val; - }; + globals.forEach(function (name) { + if (_this2.path.scope.hasBinding(name, true)) { + _this2.path.scope.rename(name); + } + }); + nodes.forEach(function (node) { + node._compact = true; + }); + this.path.unshiftContainer("body", nodes); + this.path.get("body").forEach(function (path) { + if (nodes.indexOf(path.node) === -1) return; + if (path.isVariableDeclaration()) _this2.scope.registerDeclaration(path); + }); + return uid; + } + }, { + key: "addTemplateObject", + value: function addTemplateObject() { + throw new Error("This function has been moved into the template literal transform itself."); + } + }, { + key: "buildCodeFrameError", + value: function buildCodeFrameError(node, msg) { + var Error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SyntaxError; + var loc = node && (node.loc || node._loc); + + if (!loc && node) { + var state = { + loc: null + }; + (0, _traverse().default)(node, errorVisitor, this.scope, state); + loc = state.loc; + var txt = "This is an error on an internal node. Probably an internal error."; + if (loc) txt += " Location has been estimated."; + msg += " (".concat(txt, ")"); + } - Plugin.prototype.chain = function chain(target, key) { - if (!target[key]) return this[key]; - if (!this[key]) return target[key]; + if (loc) { + var _this$opts$highlightC = this.opts.highlightCode, + highlightCode = _this$opts$highlightC === void 0 ? true : _this$opts$highlightC; + msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, { + start: { + line: loc.start.line, + column: loc.start.column + 1 + }, + end: loc.end && loc.start.line === loc.end.line ? { + line: loc.end.line, + column: loc.end.column + 1 + } : undefined + }, { + highlightCode: highlightCode + }); + } - var fns = [target[key], this[key]]; + return new Error(msg); + } + }, { + key: "shebang", + get: function get() { + var interpreter = this.path.node.interpreter; + return interpreter ? interpreter.value : ""; + }, + set: function set(value) { + if (value) { + this.path.get("interpreter").replaceWith(t().interpreterDirective(value)); + } else { + this.path.get("interpreter").remove(); + } + } + }]); - return function () { - var val = void 0; + return File; +}(); - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } +exports.default = File; - for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +},{"@babel/code-frame":1,"@babel/helpers":87,"@babel/traverse":176,"@babel/types":242,"semver":1070}],27:[function(require,module,exports){ +"use strict"; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generateCode; - var fn = _ref; +function _convertSourceMap() { + var data = _interopRequireDefault(require("convert-source-map")); - if (fn) { - var ret = fn.apply(this, args); - if (ret != null) val = ret; - } - } - return val; - }; + _convertSourceMap = function _convertSourceMap() { + return data; }; - Plugin.prototype.maybeInherit = function maybeInherit(loc) { - var inherits = this.take("inherits"); - if (!inherits) return; + return data; +} - inherits = _optionManager2.default.normalisePlugin(inherits, loc, "inherits"); +function _generator() { + var data = _interopRequireDefault(require("@babel/generator")); - this.manipulateOptions = this.chain(inherits, "manipulateOptions"); - this.post = this.chain(inherits, "post"); - this.pre = this.chain(inherits, "pre"); - this.visitor = _babelTraverse2.default.visitors.merge([inherits.visitor, this.visitor]); + _generator = function _generator() { + return data; }; - Plugin.prototype.init = function init(loc, i) { - if (this.initialized) return; - this.initialized = true; + return data; +} - this.maybeInherit(loc); +var _mergeMap = _interopRequireDefault(require("./merge-map")); - for (var key in this.raw) { - throw new Error(messages.get("pluginInvalidProperty", loc, i, key)); - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) { - for (var _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; +function generateCode(pluginPasses, file) { + var opts = file.opts, + ast = file.ast, + code = file.code, + inputMap = file.inputMap; + var results = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + try { + for (var _iterator = pluginPasses[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var plugins = _step.value; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - var key = _ref2; + try { + for (var _iterator2 = plugins[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var plugin = _step2.value; + var generatorOverride = plugin.generatorOverride; + + if (generatorOverride) { + var _result2 = generatorOverride(ast, opts.generatorOpts, code, _generator().default); - if (visitor[key]) { - throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " + "Please target individual nodes."); + if (_result2 !== undefined) results.push(_result2); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } } } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } - _babelTraverse2.default.explode(visitor); - return visitor; - }; - - return Plugin; -}(_store2.default); - -exports.default = Plugin; -module.exports = exports["default"]; -},{"../store":15,"./file/options/option-manager":23,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112,"babel-traverse":118,"lodash/assign":463,"lodash/clone":466}],31:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.inspect = exports.inherits = undefined; + var result; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (results.length === 0) { + result = (0, _generator().default)(ast, opts.generatorOpts, code); + } else if (results.length === 1) { + result = results[0]; -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (typeof result.then === "function") { + throw new Error("You appear to be using an async codegen plugin, " + "which your current version of Babel does not support. " + "If you're using a published plugin, " + "you may need to upgrade your @babel/core version."); + } + } else { + throw new Error("More than one plugin attempted to override codegen."); + } -var _util = require("util"); + var _result = result, + outputCode = _result.code, + outputMap = _result.map; -Object.defineProperty(exports, "inherits", { - enumerable: true, - get: function get() { - return _util.inherits; - } -}); -Object.defineProperty(exports, "inspect", { - enumerable: true, - get: function get() { - return _util.inspect; + if (outputMap && inputMap) { + outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap); } -}); -exports.canCompile = canCompile; -exports.list = list; -exports.regexify = regexify; -exports.arrayify = arrayify; -exports.booleanify = booleanify; -exports.shouldIgnore = shouldIgnore; -var _escapeRegExp = require("lodash/escapeRegExp"); + if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { + outputCode += "\n" + _convertSourceMap().default.fromObject(outputMap).toComment(); + } -var _escapeRegExp2 = _interopRequireDefault(_escapeRegExp); + if (opts.sourceMaps === "inline") { + outputMap = null; + } -var _startsWith = require("lodash/startsWith"); + return { + outputCode: outputCode, + outputMap: outputMap + }; +} -var _startsWith2 = _interopRequireDefault(_startsWith); +},{"./merge-map":28,"@babel/generator":51,"convert-source-map":302}],28:[function(require,module,exports){ +"use strict"; -var _minimatch = require("minimatch"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mergeSourceMap; -var _minimatch2 = _interopRequireDefault(_minimatch); +function _sourceMap() { + var data = _interopRequireDefault(require("source-map")); -var _includes = require("lodash/includes"); + _sourceMap = function _sourceMap() { + return data; + }; -var _includes2 = _interopRequireDefault(_includes); + return data; +} -var _isRegExp = require("lodash/isRegExp"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} -var _isRegExp2 = _interopRequireDefault(_isRegExp); +function mergeSourceMap(inputMap, map) { + var input = buildMappingData(inputMap); + var output = buildMappingData(map); + var mergedGenerator = new (_sourceMap().default.SourceMapGenerator)(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; -var _path = require("path"); + try { + for (var _iterator = input.sources[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref = _step.value; + var source = _ref.source; -var _path2 = _interopRequireDefault(_path); + if (typeof source.content === "string") { + mergedGenerator.setSourceContent(source.path, source.content); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } -var _slash = require("slash"); + if (output.sources.length === 1) { + var defaultSource = output.sources[0]; + var insertedMappings = new Map(); + eachInputGeneratedRange(input, function (generated, original, source) { + eachOverlappingGeneratedOutputRange(defaultSource, generated, function (item) { + var key = makeMappingKey(item); + if (insertedMappings.has(key)) return; + insertedMappings.set(key, item); + mergedGenerator.addMapping({ + source: source.path, + original: { + line: original.line, + column: original.columnStart + }, + generated: { + line: item.line, + column: item.columnStart + }, + name: original.name + }); + }); + }); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; -var _slash2 = _interopRequireDefault(_slash); + try { + for (var _iterator2 = insertedMappings.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var item = _step2.value; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (item.columnEnd === Infinity) { + continue; + } -function canCompile(filename, altExts) { - var exts = altExts || canCompile.EXTENSIONS; - var ext = _path2.default.extname(filename); - return (0, _includes2.default)(exts, ext); -} + var clearItem = { + line: item.line, + columnStart: item.columnEnd + }; + var key = makeMappingKey(clearItem); -canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"]; + if (insertedMappings.has(key)) { + continue; + } -function list(val) { - if (!val) { - return []; - } else if (Array.isArray(val)) { - return val; - } else if (typeof val === "string") { - return val.split(","); - } else { - return [val]; + mergedGenerator.addMapping({ + generated: { + line: clearItem.line, + column: clearItem.columnStart + } + }); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } } -} -function regexify(val) { - if (!val) { - return new RegExp(/.^/); - } + var result = mergedGenerator.toJSON(); - if (Array.isArray(val)) { - val = new RegExp(val.map(_escapeRegExp2.default).join("|"), "i"); + if (typeof input.sourceRoot === "string") { + result.sourceRoot = input.sourceRoot; } - if (typeof val === "string") { - val = (0, _slash2.default)(val); + return result; +} - if ((0, _startsWith2.default)(val, "./") || (0, _startsWith2.default)(val, "*/")) val = val.slice(2); - if ((0, _startsWith2.default)(val, "**/")) val = val.slice(3); +function makeMappingKey(item) { + return "".concat(item.line, "/").concat(item.columnStart); +} - var regex = _minimatch2.default.makeRe(val, { nocase: true }); - return new RegExp(regex.source.slice(1, -1), "i"); - } +function eachOverlappingGeneratedOutputRange(outputFile, inputGeneratedRange, callback) { + var overlappingOriginal = filterApplicableOriginalRanges(outputFile, inputGeneratedRange); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; - if ((0, _isRegExp2.default)(val)) { - return val; + try { + for (var _iterator3 = overlappingOriginal[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _ref2 = _step3.value; + var generated = _ref2.generated; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = generated[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var item = _step4.value; + callback(item); + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } } +} - throw new TypeError("illegal type for regexify"); +function filterApplicableOriginalRanges(_ref5, _ref6) { + var mappings = _ref5.mappings; + var line = _ref6.line, + columnStart = _ref6.columnStart, + columnEnd = _ref6.columnEnd; + return filterSortedArray(mappings, function (_ref7) { + var outOriginal = _ref7.original; + if (line > outOriginal.line) return -1; + if (line < outOriginal.line) return 1; + if (columnStart >= outOriginal.columnEnd) return -1; + if (columnEnd <= outOriginal.columnStart) return 1; + return 0; + }); } -function arrayify(val, mapFn) { - if (!val) return []; - if (typeof val === "boolean") return arrayify([val], mapFn); - if (typeof val === "string") return arrayify(list(val), mapFn); +function eachInputGeneratedRange(map, callback) { + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; - if (Array.isArray(val)) { - if (mapFn) val = val.map(mapFn); - return val; - } + try { + for (var _iterator5 = map.sources[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var _ref3 = _step5.value; + var source = _ref3.source, + mappings = _ref3.mappings; + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; - return [val]; -} + try { + for (var _iterator6 = mappings[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var _ref4 = _step6.value; + var original = _ref4.original, + generated = _ref4.generated; + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; -function booleanify(val) { - if (val === "true" || val == 1) { - return true; + try { + for (var _iterator7 = generated[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var item = _step7.value; + callback(item, original, source); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } } +} - if (val === "false" || val == 0 || !val) { - return false; - } +function buildMappingData(map) { + var consumer = new (_sourceMap().default.SourceMapConsumer)(Object.assign({}, map, { + sourceRoot: null + })); + var sources = new Map(); + var mappings = new Map(); + var last = null; + consumer.computeColumnSpans(); + consumer.eachMapping(function (m) { + if (m.originalLine === null) return; + var source = sources.get(m.source); + + if (!source) { + source = { + path: m.source, + content: consumer.sourceContentFor(m.source, true) + }; + sources.set(m.source, source); + } - return val; -} + var sourceData = mappings.get(source); -function shouldIgnore(filename) { - var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var only = arguments[2]; + if (!sourceData) { + sourceData = { + source: source, + mappings: [] + }; + mappings.set(source, sourceData); + } - filename = filename.replace(/\\/g, "/"); + var obj = { + line: m.originalLine, + columnStart: m.originalColumn, + columnEnd: Infinity, + name: m.name + }; - if (only) { - for (var _iterator = only, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (last && last.source === source && last.mapping.line === m.originalLine) { + last.mapping.columnEnd = m.originalColumn; + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + last = { + source: source, + mapping: obj + }; + sourceData.mappings.push({ + original: obj, + generated: consumer.allGeneratedPositionsFor({ + source: m.source, + line: m.originalLine, + column: m.originalColumn + }).map(function (item) { + return { + line: item.line, + columnStart: item.column, + columnEnd: item.lastColumn + 1 + }; + }) + }); + }, null, _sourceMap().default.SourceMapConsumer.ORIGINAL_ORDER); + return { + file: map.file, + sourceRoot: map.sourceRoot, + sources: Array.from(mappings.values()) + }; +} + +function findInsertionLocation(array, callback) { + var left = 0; + var right = array.length; - var pattern = _ref; + while (left < right) { + var mid = Math.floor((left + right) / 2); + var item = array[mid]; + var result = callback(item); - if (_shouldIgnore(pattern, filename)) return false; + if (result === 0) { + left = mid; + break; } - return true; - } else if (ignore.length) { - for (var _iterator2 = ignore, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + if (result >= 0) { + right = mid; + } else { + left = mid + 1; + } + } - var _pattern = _ref2; + var i = left; - if (_shouldIgnore(_pattern, filename)) return true; + if (i < array.length) { + while (i >= 0 && callback(array[i]) >= 0) { + i--; } + + return i + 1; } - return false; + return i; } -function _shouldIgnore(pattern, filename) { - if (typeof pattern === "function") { - return pattern(filename); - } else { - return pattern.test(filename); +function filterSortedArray(array, callback) { + var start = findInsertionLocation(array, callback); + var results = []; + + for (var i = start; i < array.length && callback(array[i]) === 0; i++) { + results.push(array[i]); } -} -},{"babel-runtime/core-js/get-iterator":95,"lodash/escapeRegExp":472,"lodash/includes":482,"lodash/isRegExp":494,"lodash/startsWith":509,"minimatch":519,"path":522,"slash":541,"util":560}],32:[function(require,module,exports){ -module.exports={ - "_from": "babel-core@^6.22.1", - "_id": "babel-core@6.26.0", - "_inBundle": false, - "_integrity": "sha1-rzL3izGm/O8RnIew/Y2XU/A6C7g=", - "_location": "/babel-core", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "babel-core@^6.22.1", - "name": "babel-core", - "escapedName": "babel-core", - "rawSpec": "^6.22.1", - "saveSpec": null, - "fetchSpec": "^6.22.1" - }, - "_requiredBy": [ - "#DEV:/", - "/babel-register", - "/babelify", - "/karma-babel-preprocessor" - ], - "_resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.26.0.tgz", - "_shasum": "af32f78b31a6fcef119c87b0fd8d9753f03a0bb8", - "_spec": "babel-core@^6.22.1", - "_where": "/Users/juanjodiaz/Documents/code/OSS libs/noVNC", - "author": { - "name": "Sebastian McKenzie", - "email": "sebmck@gmail.com" - }, - "bundleDependencies": false, - "dependencies": { - "babel-code-frame": "^6.26.0", - "babel-generator": "^6.26.0", - "babel-helpers": "^6.24.1", - "babel-messages": "^6.23.0", - "babel-register": "^6.26.0", - "babel-runtime": "^6.26.0", - "babel-template": "^6.26.0", - "babel-traverse": "^6.26.0", - "babel-types": "^6.26.0", - "babylon": "^6.18.0", - "convert-source-map": "^1.5.0", - "debug": "^2.6.8", - "json5": "^0.5.1", - "lodash": "^4.17.4", - "minimatch": "^3.0.4", - "path-is-absolute": "^1.0.1", - "private": "^0.1.7", - "slash": "^1.0.0", - "source-map": "^0.5.6" - }, - "deprecated": false, - "description": "Babel compiler core.", - "devDependencies": { - "babel-helper-fixtures": "^6.26.0", - "babel-helper-transform-fixture-test-runner": "^6.26.0", - "babel-polyfill": "^6.26.0" - }, - "homepage": "https://babeljs.io/", - "keywords": [ - "6to5", - "babel", - "classes", - "const", - "es6", - "harmony", - "let", - "modules", - "transpile", - "transpiler", - "var", - "babel-core", - "compiler" - ], - "license": "MIT", - "name": "babel-core", - "repository": { - "type": "git", - "url": "https://github.com/babel/babel/tree/master/packages/babel-core" - }, - "scripts": { - "bench": "make bench", - "test": "make test" - }, - "version": "6.26.0" + + return results; } -},{}],33:[function(require,module,exports){ +},{"source-map":1081}],29:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -var _trimRight = require("trim-right"); +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -var _trimRight2 = _interopRequireDefault(_trimRight); +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.runAsync = runAsync; +exports.runSync = runSync; -var SPACES_RE = /^[ \t]+$/; +function _traverse() { + var data = _interopRequireDefault(require("@babel/traverse")); -var Buffer = function () { - function Buffer(map) { - (0, _classCallCheck3.default)(this, Buffer); - this._map = null; - this._buf = []; - this._last = ""; - this._queue = []; - this._position = { - line: 1, - column: 0 - }; - this._sourcePosition = { - identifierName: null, - line: null, - column: null, - filename: null - }; + _traverse = function _traverse() { + return data; + }; - this._map = map; - } + return data; +} - Buffer.prototype.get = function get() { - this._flush(); +var _pluginPass = _interopRequireDefault(require("./plugin-pass")); - var map = this._map; - var result = { - code: (0, _trimRight2.default)(this._buf.join("")), - map: null, - rawMappings: map && map.getRawMappings() - }; +var _blockHoistPlugin = _interopRequireDefault(require("./block-hoist-plugin")); - if (map) { - Object.defineProperty(result, "map", { - configurable: true, - enumerable: true, - get: function get() { - return this.map = map.get(); - }, - set: function set(value) { - Object.defineProperty(this, "map", { value: value, writable: true }); - } - }); - } +var _normalizeOpts = _interopRequireDefault(require("./normalize-opts")); - return result; - }; +var _normalizeFile = _interopRequireDefault(require("./normalize-file")); - Buffer.prototype.append = function append(str) { - this._flush(); - var _sourcePosition = this._sourcePosition, - line = _sourcePosition.line, - column = _sourcePosition.column, - filename = _sourcePosition.filename, - identifierName = _sourcePosition.identifierName; +var _generate = _interopRequireDefault(require("./file/generate")); - this._append(str, line, column, identifierName, filename); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - Buffer.prototype.queue = function queue(str) { - if (str === "\n") while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { - this._queue.shift(); - }var _sourcePosition2 = this._sourcePosition, - line = _sourcePosition2.line, - column = _sourcePosition2.column, - filename = _sourcePosition2.filename, - identifierName = _sourcePosition2.identifierName; +function runAsync(config, code, ast, callback) { + var result; - this._queue.unshift([str, line, column, identifierName, filename]); - }; + try { + result = runSync(config, code, ast); + } catch (err) { + return callback(err); + } + + return callback(null, result); +} + +function runSync(config, code, ast) { + var file = (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); + var opts = file.opts; + + try { + transformFile(file, config.passes); + } catch (e) { + var _opts$filename; + + e.message = "".concat((_opts$filename = opts.filename) !== null && _opts$filename !== void 0 ? _opts$filename : "unknown", ": ").concat(e.message); - Buffer.prototype._flush = function _flush() { - var item = void 0; - while (item = this._queue.pop()) { - this._append.apply(this, item); + if (!e.code) { + e.code = "BABEL_TRANSFORM_ERROR"; } - }; - Buffer.prototype._append = function _append(str, line, column, identifierName, filename) { - if (this._map && str[0] !== "\n") { - this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename); + throw e; + } + + var outputCode, outputMap; + + try { + if (opts.code !== false) { + var _ref = (0, _generate.default)(config.passes, file); + + outputCode = _ref.outputCode; + outputMap = _ref.outputMap; } + } catch (e) { + var _opts$filename2; - this._buf.push(str); - this._last = str[str.length - 1]; + e.message = "".concat((_opts$filename2 = opts.filename) !== null && _opts$filename2 !== void 0 ? _opts$filename2 : "unknown", ": ").concat(e.message); - for (var i = 0; i < str.length; i++) { - if (str[i] === "\n") { - this._position.line++; - this._position.column = 0; - } else { - this._position.column++; - } + if (!e.code) { + e.code = "BABEL_GENERATE_ERROR"; } - }; - Buffer.prototype.removeTrailingNewline = function removeTrailingNewline() { - if (this._queue.length > 0 && this._queue[0][0] === "\n") this._queue.shift(); - }; + throw e; + } - Buffer.prototype.removeLastSemicolon = function removeLastSemicolon() { - if (this._queue.length > 0 && this._queue[0][0] === ";") this._queue.shift(); + return { + metadata: file.metadata, + options: opts, + ast: opts.ast === true ? file.ast : null, + code: outputCode === undefined ? null : outputCode, + map: outputMap === undefined ? null : outputMap, + sourceType: file.ast.program.sourceType }; +} - Buffer.prototype.endsWith = function endsWith(suffix) { - if (suffix.length === 1) { - var last = void 0; - if (this._queue.length > 0) { - var str = this._queue[0][0]; - last = str[str.length - 1]; - } else { - last = this._last; +function transformFile(file, pluginPasses) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = pluginPasses[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var pluginPairs = _step.value; + var passPairs = []; + var passes = []; + var visitors = []; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = pluginPairs.concat([(0, _blockHoistPlugin.default)()])[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var plugin = _step2.value; + var pass = new _pluginPass.default(file, plugin.key, plugin.options); + passPairs.push([plugin, pass]); + passes.push(pass); + visitors.push(plugin.visitor); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } } - return last === suffix; - } + for (var _i = 0, _passPairs = passPairs; _i < _passPairs.length; _i++) { + var _passPairs$_i = _slicedToArray(_passPairs[_i], 2), + _plugin = _passPairs$_i[0], + _pass = _passPairs$_i[1]; + + var fn = _plugin.pre; + + if (fn) { + var result = fn.call(_pass, file); + + if (isThenable(result)) { + throw new Error("You appear to be using an plugin with an async .pre, " + "which your current version of Babel does not support. " + "If you're using a published plugin, you may need to upgrade " + "your @babel/core version."); + } + } + } + + var visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); + + (0, _traverse().default)(file.ast, visitor, file.scope); + + for (var _i2 = 0, _passPairs2 = passPairs; _i2 < _passPairs2.length; _i2++) { + var _passPairs2$_i = _slicedToArray(_passPairs2[_i2], 2), + _plugin2 = _passPairs2$_i[0], + _pass2 = _passPairs2$_i[1]; + + var _fn = _plugin2.post; + + if (_fn) { + var _result = _fn.call(_pass2, file); - var end = this._last + this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - if (suffix.length <= end.length) { - return end.slice(-suffix.length) === suffix; + if (isThenable(_result)) { + throw new Error("You appear to be using an plugin with an async .post, " + "which your current version of Babel does not support. " + "If you're using a published plugin, you may need to upgrade " + "your @babel/core version."); + } + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } + } +} - return false; - }; +function isThenable(val) { + return !!val && (_typeof(val) === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; +} - Buffer.prototype.hasContent = function hasContent() { - return this._queue.length > 0 || !!this._last; - }; +},{"./block-hoist-plugin":25,"./file/generate":27,"./normalize-file":30,"./normalize-opts":31,"./plugin-pass":32,"@babel/traverse":176}],30:[function(require,module,exports){ +"use strict"; - Buffer.prototype.source = function source(prop, loc) { - if (prop && !loc) return; +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - var pos = loc ? loc[prop] : null; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - this._sourcePosition.identifierName = loc && loc.identifierName || null; - this._sourcePosition.line = pos ? pos.line : null; - this._sourcePosition.column = pos ? pos.column : null; - this._sourcePosition.filename = loc && loc.filename || null; - }; +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - Buffer.prototype.withSource = function withSource(prop, loc, cb) { - if (!this._map) return cb(); +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - var originalLine = this._sourcePosition.line; - var originalColumn = this._sourcePosition.column; - var originalFilename = this._sourcePosition.filename; - var originalIdentifierName = this._sourcePosition.identifierName; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - this.source(prop, loc); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeFile; - cb(); +function _path() { + var data = _interopRequireDefault(require("path")); - this._sourcePosition.line = originalLine; - this._sourcePosition.column = originalColumn; - this._sourcePosition.filename = originalFilename; - this._sourcePosition.identifierName = originalIdentifierName; + _path = function _path() { + return data; }; - Buffer.prototype.getCurrentColumn = function getCurrentColumn() { - var extra = this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - var lastIndex = extra.lastIndexOf("\n"); + return data; +} + +function _debug() { + var data = _interopRequireDefault(require("debug")); - return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; + _debug = function _debug() { + return data; }; - Buffer.prototype.getCurrentLine = function getCurrentLine() { - var extra = this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); + return data; +} - var count = 0; - for (var i = 0; i < extra.length; i++) { - if (extra[i] === "\n") count++; - } +function _cloneDeep() { + var data = _interopRequireDefault(require("lodash/cloneDeep")); - return this._position.line + count; + _cloneDeep = function _cloneDeep() { + return data; }; - return Buffer; -}(); - -exports.default = Buffer; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109,"trim-right":556}],34:[function(require,module,exports){ -"use strict"; + return data; +} -exports.__esModule = true; -exports.File = File; -exports.Program = Program; -exports.BlockStatement = BlockStatement; -exports.Noop = Noop; -exports.Directive = Directive; +function t() { + var data = _interopRequireWildcard(require("@babel/types")); -var _types = require("./types"); + t = function t() { + return data; + }; -Object.defineProperty(exports, "DirectiveLiteral", { - enumerable: true, - get: function get() { - return _types.StringLiteral; - } -}); -function File(node) { - this.print(node.program, node); + return data; } -function Program(node) { - this.printInnerComments(node, false); +function _convertSourceMap() { + var data = _interopRequireDefault(require("convert-source-map")); - this.printSequence(node.directives, node); - if (node.directives && node.directives.length) this.newline(); + _convertSourceMap = function _convertSourceMap() { + return data; + }; - this.printSequence(node.body, node); + return data; } -function BlockStatement(node) { - this.token("{"); - this.printInnerComments(node); +function _parser() { + var data = require("@babel/parser"); - var hasDirectives = node.directives && node.directives.length; + _parser = function _parser() { + return data; + }; - if (node.body.length || hasDirectives) { - this.newline(); + return data; +} - this.printSequence(node.directives, node, { indent: true }); - if (hasDirectives) this.newline(); +function _codeFrame() { + var data = require("@babel/code-frame"); - this.printSequence(node.body, node, { indent: true }); - this.removeTrailingNewline(); + _codeFrame = function _codeFrame() { + return data; + }; - this.source("end", node.loc); + return data; +} - if (!this.endsWith("\n")) this.newline(); +var _file = _interopRequireDefault(require("./file/file")); - this.rightBrace(); - } else { - this.source("end", node.loc); - this.token("}"); - } -} +var _missingPluginHelper = _interopRequireDefault(require("./util/missing-plugin-helper")); -function Noop() {} +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -function Directive(node) { - this.print(node.value, node); - this.semicolon(); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + + return cache; } -},{"./types":43}],35:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.ClassDeclaration = ClassDeclaration; -exports.ClassBody = ClassBody; -exports.ClassProperty = ClassProperty; -exports.ClassMethod = ClassMethod; -function ClassDeclaration(node) { - this.printJoin(node.decorators, node); - this.word("class"); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - if (node.id) { - this.space(); - this.print(node.id, node); + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); } - this.print(node.typeParameters, node); + var newObj = {}; - if (node.superClass) { - this.space(); - this.word("extends"); - this.space(); - this.print(node.superClass, node); - this.print(node.superTypeParameters, node); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } } - if (node.implements) { - this.space(); - this.word("implements"); - this.space(); - this.printList(node.implements, node); + newObj.default = obj; + + if (cache) { + cache.set(obj, newObj); } - this.space(); - this.print(node.body, node); + return newObj; } -exports.ClassExpression = ClassDeclaration; -function ClassBody(node) { - this.token("{"); - this.printInnerComments(node); - if (node.body.length === 0) { - this.token("}"); - } else { - this.newline(); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - this.indent(); - this.printSequence(node.body, node); - this.dedent(); +var debug = (0, _debug().default)("babel:transform:file"); - if (!this.endsWith("\n")) this.newline(); +function normalizeFile(pluginPasses, options, code, ast) { + code = "".concat(code || ""); - this.rightBrace(); + if (ast) { + if (ast.type === "Program") { + ast = t().file(ast, [], []); + } else if (ast.type !== "File") { + throw new Error("AST root must be a Program or File node"); + } + + ast = (0, _cloneDeep().default)(ast); + } else { + ast = parser(pluginPasses, options, code); } -} -function ClassProperty(node) { - this.printJoin(node.decorators, node); + var inputMap = null; - if (node.static) { - this.word("static"); - this.space(); - } - if (node.computed) { - this.token("["); - this.print(node.key, node); - this.token("]"); - } else { - this._variance(node); - this.print(node.key, node); - } - this.print(node.typeAnnotation, node); - if (node.value) { - this.space(); - this.token("="); - this.space(); - this.print(node.value, node); - } - this.semicolon(); -} + if (options.inputSourceMap !== false) { + if (_typeof(options.inputSourceMap) === "object") { + inputMap = _convertSourceMap().default.fromObject(options.inputSourceMap); + } -function ClassMethod(node) { - this.printJoin(node.decorators, node); + if (!inputMap) { + var lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast); - if (node.static) { - this.word("static"); - this.space(); - } + if (lastComment) { + try { + inputMap = _convertSourceMap().default.fromComment(lastComment); + } catch (err) { + debug("discarding unknown inline input sourcemap", err); + } + } + } - if (node.kind === "constructorCall") { - this.word("call"); - this.space(); + if (!inputMap) { + var _lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast); + + if (typeof options.filename === "string" && _lastComment) { + try { + inputMap = _convertSourceMap().default.fromMapFileComment("//".concat(_lastComment), _path().default.dirname(options.filename)); + } catch (err) { + debug("discarding unknown file input sourcemap", err); + } + } else if (_lastComment) { + debug("discarding un-loadable file input sourcemap"); + } + } } - this._method(node); + return new _file.default(options, { + code: code, + ast: ast, + inputMap: inputMap + }); } -},{}],36:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.LogicalExpression = exports.BinaryExpression = exports.AwaitExpression = exports.YieldExpression = undefined; -exports.UnaryExpression = UnaryExpression; -exports.DoExpression = DoExpression; -exports.ParenthesizedExpression = ParenthesizedExpression; -exports.UpdateExpression = UpdateExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.NewExpression = NewExpression; -exports.SequenceExpression = SequenceExpression; -exports.ThisExpression = ThisExpression; -exports.Super = Super; -exports.Decorator = Decorator; -exports.CallExpression = CallExpression; -exports.Import = Import; -exports.EmptyStatement = EmptyStatement; -exports.ExpressionStatement = ExpressionStatement; -exports.AssignmentPattern = AssignmentPattern; -exports.AssignmentExpression = AssignmentExpression; -exports.BindExpression = BindExpression; -exports.MemberExpression = MemberExpression; -exports.MetaProperty = MetaProperty; +function parser(pluginPasses, _ref, code) { + var parserOpts = _ref.parserOpts, + _ref$highlightCode = _ref.highlightCode, + highlightCode = _ref$highlightCode === void 0 ? true : _ref$highlightCode, + _ref$filename = _ref.filename, + filename = _ref$filename === void 0 ? "unknown" : _ref$filename; + + try { + var results = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = pluginPasses[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var plugins = _step.value; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; -var _babelTypes = require("babel-types"); + try { + for (var _iterator2 = plugins[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var plugin = _step2.value; + var parserOverride = plugin.parserOverride; -var t = _interopRequireWildcard(_babelTypes); + if (parserOverride) { + var ast = parserOverride(code, parserOpts, _parser().parse); + if (ast !== undefined) results.push(ast); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } -var _node = require("../node"); + if (results.length === 0) { + return (0, _parser().parse)(code, parserOpts); + } else if (results.length === 1) { + if (typeof results[0].then === "function") { + throw new Error("You appear to be using an async parser plugin, " + "which your current version of Babel does not support. " + "If you're using a published plugin, you may need to upgrade " + "your @babel/core version."); + } -var n = _interopRequireWildcard(_node); + return results[0]; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + throw new Error("More than one plugin attempted to override parsing."); + } catch (err) { + if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") { + err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file."; + } -function UnaryExpression(node) { - if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof") { - this.word(node.operator); - this.space(); - } else { - this.token(node.operator); - } + var loc = err.loc, + missingPlugin = err.missingPlugin; - this.print(node.argument, node); -} + if (loc) { + var codeFrame = (0, _codeFrame().codeFrameColumns)(code, { + start: { + line: loc.line, + column: loc.column + 1 + } + }, { + highlightCode: highlightCode + }); -function DoExpression(node) { - this.word("do"); - this.space(); - this.print(node.body, node); -} + if (missingPlugin) { + err.message = "".concat(filename, ": ") + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame); + } else { + err.message = "".concat(filename, ": ").concat(err.message, "\n\n") + codeFrame; + } -function ParenthesizedExpression(node) { - this.token("("); - this.print(node.expression, node); - this.token(")"); -} + err.code = "BABEL_PARSE_ERROR"; + } -function UpdateExpression(node) { - if (node.prefix) { - this.token(node.operator); - this.print(node.argument, node); - } else { - this.print(node.argument, node); - this.token(node.operator); + throw err; } } -function ConditionalExpression(node) { - this.print(node.test, node); - this.space(); - this.token("?"); - this.space(); - this.print(node.consequent, node); - this.space(); - this.token(":"); - this.space(); - this.print(node.alternate, node); -} +var INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/; +var EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=(?:[^\s'"`]+?)[ \t]*$/; -function NewExpression(node, parent) { - this.word("new"); - this.space(); - this.print(node.callee, node); - if (node.arguments.length === 0 && this.format.minified && !t.isCallExpression(parent, { callee: node }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) return; +function extractCommentsFromList(regex, comments, lastComment) { + if (comments) { + comments = comments.filter(function (_ref2) { + var value = _ref2.value; - this.token("("); - this.printList(node.arguments, node); - this.token(")"); -} + if (regex.test(value)) { + lastComment = value; + return false; + } -function SequenceExpression(node) { - this.printList(node.expressions, node); -} + return true; + }); + } -function ThisExpression() { - this.word("this"); + return [comments, lastComment]; } -function Super() { - this.word("super"); -} +function extractComments(regex, ast) { + var lastComment = null; + t().traverseFast(ast, function (node) { + var _extractCommentsFromL = extractCommentsFromList(regex, node.leadingComments, lastComment); -function Decorator(node) { - this.token("@"); - this.print(node.expression, node); - this.newline(); -} + var _extractCommentsFromL2 = _slicedToArray(_extractCommentsFromL, 2); -function commaSeparatorNewline() { - this.token(","); - this.newline(); + node.leadingComments = _extractCommentsFromL2[0]; + lastComment = _extractCommentsFromL2[1]; - if (!this.endsWith("\n")) this.space(); -} + var _extractCommentsFromL3 = extractCommentsFromList(regex, node.innerComments, lastComment); -function CallExpression(node) { - this.print(node.callee, node); + var _extractCommentsFromL4 = _slicedToArray(_extractCommentsFromL3, 2); - this.token("("); + node.innerComments = _extractCommentsFromL4[0]; + lastComment = _extractCommentsFromL4[1]; - var isPrettyCall = node._prettyCall; + var _extractCommentsFromL5 = extractCommentsFromList(regex, node.trailingComments, lastComment); - var separator = void 0; - if (isPrettyCall) { - separator = commaSeparatorNewline; - this.newline(); - this.indent(); - } + var _extractCommentsFromL6 = _slicedToArray(_extractCommentsFromL5, 2); - this.printList(node.arguments, node, { separator: separator }); + node.trailingComments = _extractCommentsFromL6[0]; + lastComment = _extractCommentsFromL6[1]; + }); + return lastComment; +} - if (isPrettyCall) { - this.newline(); - this.dedent(); - } +},{"./file/file":26,"./util/missing-plugin-helper":33,"@babel/code-frame":1,"@babel/parser":89,"@babel/types":242,"convert-source-map":302,"debug":34,"lodash/cloneDeep":1005,"path":1052}],31:[function(require,module,exports){ +"use strict"; - this.token(")"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeOptions; + +function _path() { + var data = _interopRequireDefault(require("path")); + + _path = function _path() { + return data; + }; + + return data; } -function Import() { - this.word("import"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; } -function buildYieldAwait(keyword) { - return function (node) { - this.word(keyword); +function normalizeOptions(config) { + var _config$options = config.options, + filename = _config$options.filename, + cwd = _config$options.cwd, + _config$options$filen = _config$options.filenameRelative, + filenameRelative = _config$options$filen === void 0 ? typeof filename === "string" ? _path().default.relative(cwd, filename) : "unknown" : _config$options$filen, + _config$options$sourc = _config$options.sourceType, + sourceType = _config$options$sourc === void 0 ? "module" : _config$options$sourc, + inputSourceMap = _config$options.inputSourceMap, + _config$options$sourc2 = _config$options.sourceMaps, + sourceMaps = _config$options$sourc2 === void 0 ? !!inputSourceMap : _config$options$sourc2, + moduleRoot = _config$options.moduleRoot, + _config$options$sourc3 = _config$options.sourceRoot, + sourceRoot = _config$options$sourc3 === void 0 ? moduleRoot : _config$options$sourc3, + _config$options$sourc4 = _config$options.sourceFileName, + sourceFileName = _config$options$sourc4 === void 0 ? _path().default.basename(filenameRelative) : _config$options$sourc4, + _config$options$comme = _config$options.comments, + comments = _config$options$comme === void 0 ? true : _config$options$comme, + _config$options$compa = _config$options.compact, + compact = _config$options$compa === void 0 ? "auto" : _config$options$compa; + var opts = config.options; + var options = Object.assign({}, opts, { + parserOpts: Object.assign({ + sourceType: _path().default.extname(filenameRelative) === ".mjs" ? "module" : sourceType, + sourceFileName: filename, + plugins: [] + }, opts.parserOpts), + generatorOpts: Object.assign({ + filename: filename, + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + retainLines: opts.retainLines, + comments: comments, + shouldPrintComment: opts.shouldPrintComment, + compact: compact, + minified: opts.minified, + sourceMaps: sourceMaps, + sourceRoot: sourceRoot, + sourceFileName: sourceFileName + }, opts.generatorOpts) + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (node.delegate) { - this.token("*"); - } + try { + for (var _iterator = config.passes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var plugins = _step.value; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - if (node.argument) { - this.space(); - var terminatorState = this.startTerminatorless(); - this.print(node.argument, node); - this.endTerminatorless(terminatorState); + try { + for (var _iterator2 = plugins[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var plugin = _step2.value; + + if (plugin.manipulateOptions) { + plugin.manipulateOptions(options, options.parserOpts); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } } - }; + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return options; } -var YieldExpression = exports.YieldExpression = buildYieldAwait("yield"); -var AwaitExpression = exports.AwaitExpression = buildYieldAwait("await"); +},{"path":1052}],32:[function(require,module,exports){ +"use strict"; -function EmptyStatement() { - this.semicolon(true); -} +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function ExpressionStatement(node) { - this.print(node.expression, node); - this.semicolon(); -} +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -function AssignmentPattern(node) { - this.print(node.left, node); - if (node.left.optional) this.token("?"); - this.print(node.left.typeAnnotation, node); - this.space(); - this.token("="); - this.space(); - this.print(node.right, node); -} +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -function AssignmentExpression(node, parent) { - var parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - if (parens) { - this.token("("); - } +var PluginPass = +/*#__PURE__*/ +function () { + function PluginPass(file, key, options) { + _classCallCheck(this, PluginPass); - this.print(node.left, node); + this._map = new Map(); + this.key = key; + this.file = file; + this.opts = options || {}; + this.cwd = file.opts.cwd; + this.filename = file.opts.filename; + } + + _createClass(PluginPass, [{ + key: "set", + value: function set(key, val) { + this._map.set(key, val); + } + }, { + key: "get", + value: function get(key) { + return this._map.get(key); + } + }, { + key: "availableHelper", + value: function availableHelper(name, versionRange) { + return this.file.availableHelper(name, versionRange); + } + }, { + key: "addHelper", + value: function addHelper(name) { + return this.file.addHelper(name); + } + }, { + key: "addImport", + value: function addImport() { + return this.file.addImport(); + } + }, { + key: "getModuleName", + value: function getModuleName() { + return this.file.getModuleName(); + } + }, { + key: "buildCodeFrameError", + value: function buildCodeFrameError(node, msg, Error) { + return this.file.buildCodeFrameError(node, msg, Error); + } + }]); - this.space(); - if (node.operator === "in" || node.operator === "instanceof") { - this.word(node.operator); - } else { - this.token(node.operator); - } - this.space(); + return PluginPass; +}(); - this.print(node.right, node); +exports.default = PluginPass; - if (parens) { - this.token(")"); +},{}],33:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generateMissingPluginMessage; +var pluginNameMap = { + classProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://git.io/vb4yQ" + }, + transform: { + name: "@babel/plugin-proposal-class-properties", + url: "https://git.io/vb4SL" + } + }, + decorators: { + syntax: { + name: "@babel/plugin-syntax-decorators", + url: "https://git.io/vb4y9" + }, + transform: { + name: "@babel/plugin-proposal-decorators", + url: "https://git.io/vb4ST" + } + }, + doExpressions: { + syntax: { + name: "@babel/plugin-syntax-do-expressions", + url: "https://git.io/vb4yh" + }, + transform: { + name: "@babel/plugin-proposal-do-expressions", + url: "https://git.io/vb4S3" + } + }, + dynamicImport: { + syntax: { + name: "@babel/plugin-syntax-dynamic-import", + url: "https://git.io/vb4Sv" + } + }, + exportDefaultFrom: { + syntax: { + name: "@babel/plugin-syntax-export-default-from", + url: "https://git.io/vb4SO" + }, + transform: { + name: "@babel/plugin-proposal-export-default-from", + url: "https://git.io/vb4yH" + } + }, + exportNamespaceFrom: { + syntax: { + name: "@babel/plugin-syntax-export-namespace-from", + url: "https://git.io/vb4Sf" + }, + transform: { + name: "@babel/plugin-proposal-export-namespace-from", + url: "https://git.io/vb4SG" + } + }, + flow: { + syntax: { + name: "@babel/plugin-syntax-flow", + url: "https://git.io/vb4yb" + }, + transform: { + name: "@babel/plugin-transform-flow-strip-types", + url: "https://git.io/vb49g" + } + }, + functionBind: { + syntax: { + name: "@babel/plugin-syntax-function-bind", + url: "https://git.io/vb4y7" + }, + transform: { + name: "@babel/plugin-proposal-function-bind", + url: "https://git.io/vb4St" + } + }, + functionSent: { + syntax: { + name: "@babel/plugin-syntax-function-sent", + url: "https://git.io/vb4yN" + }, + transform: { + name: "@babel/plugin-proposal-function-sent", + url: "https://git.io/vb4SZ" + } + }, + importMeta: { + syntax: { + name: "@babel/plugin-syntax-import-meta", + url: "https://git.io/vbKK6" + } + }, + jsx: { + syntax: { + name: "@babel/plugin-syntax-jsx", + url: "https://git.io/vb4yA" + }, + transform: { + name: "@babel/plugin-transform-react-jsx", + url: "https://git.io/vb4yd" + } + }, + logicalAssignment: { + syntax: { + name: "@babel/plugin-syntax-logical-assignment-operators", + url: "https://git.io/vAlBp" + }, + transform: { + name: "@babel/plugin-proposal-logical-assignment-operators", + url: "https://git.io/vAlRe" + } + }, + nullishCoalescingOperator: { + syntax: { + name: "@babel/plugin-syntax-nullish-coalescing-operator", + url: "https://git.io/vb4yx" + }, + transform: { + name: "@babel/plugin-proposal-nullish-coalescing-operator", + url: "https://git.io/vb4Se" + } + }, + numericSeparator: { + syntax: { + name: "@babel/plugin-syntax-numeric-separator", + url: "https://git.io/vb4Sq" + }, + transform: { + name: "@babel/plugin-proposal-numeric-separator", + url: "https://git.io/vb4yS" + } + }, + optionalChaining: { + syntax: { + name: "@babel/plugin-syntax-optional-chaining", + url: "https://git.io/vb4Sc" + }, + transform: { + name: "@babel/plugin-proposal-optional-chaining", + url: "https://git.io/vb4Sk" + } + }, + pipelineOperator: { + syntax: { + name: "@babel/plugin-syntax-pipeline-operator", + url: "https://git.io/vb4yj" + }, + transform: { + name: "@babel/plugin-proposal-pipeline-operator", + url: "https://git.io/vb4SU" + } + }, + throwExpressions: { + syntax: { + name: "@babel/plugin-syntax-throw-expressions", + url: "https://git.io/vb4SJ" + }, + transform: { + name: "@babel/plugin-proposal-throw-expressions", + url: "https://git.io/vb4yF" + } + }, + typescript: { + syntax: { + name: "@babel/plugin-syntax-typescript", + url: "https://git.io/vb4SC" + }, + transform: { + name: "@babel/plugin-transform-typescript", + url: "https://git.io/vb4Sm" + } + }, + asyncGenerators: { + syntax: { + name: "@babel/plugin-syntax-async-generators", + url: "https://git.io/vb4SY" + }, + transform: { + name: "@babel/plugin-proposal-async-generator-functions", + url: "https://git.io/vb4yp" + } + }, + objectRestSpread: { + syntax: { + name: "@babel/plugin-syntax-object-rest-spread", + url: "https://git.io/vb4y5" + }, + transform: { + name: "@babel/plugin-proposal-object-rest-spread", + url: "https://git.io/vb4Ss" + } + }, + optionalCatchBinding: { + syntax: { + name: "@babel/plugin-syntax-optional-catch-binding", + url: "https://git.io/vb4Sn" + }, + transform: { + name: "@babel/plugin-proposal-optional-catch-binding", + url: "https://git.io/vb4SI" + } } -} +}; -function BindExpression(node) { - this.print(node.object, node); - this.token("::"); - this.print(node.callee, node); -} +var getNameURLCombination = function getNameURLCombination(_ref) { + var name = _ref.name, + url = _ref.url; + return "".concat(name, " (").concat(url, ")"); +}; -exports.BinaryExpression = AssignmentExpression; -exports.LogicalExpression = AssignmentExpression; -function MemberExpression(node) { - this.print(node.object, node); +function generateMissingPluginMessage(missingPluginName, loc, codeFrame) { + var helpMessage = "Support for the experimental syntax '".concat(missingPluginName, "' isn't currently enabled ") + "(".concat(loc.line, ":").concat(loc.column + 1, "):\n\n") + codeFrame; + var pluginInfo = pluginNameMap[missingPluginName]; - if (!node.computed && t.isMemberExpression(node.property)) { - throw new TypeError("Got a MemberExpression for MemberExpression property"); - } + if (pluginInfo) { + var syntaxPlugin = pluginInfo.syntax, + transformPlugin = pluginInfo.transform; - var computed = node.computed; - if (t.isLiteral(node.property) && typeof node.property.value === "number") { - computed = true; + if (syntaxPlugin) { + if (transformPlugin) { + var transformPluginInfo = getNameURLCombination(transformPlugin); + helpMessage += "\n\nAdd ".concat(transformPluginInfo, " to the 'plugins' section of your Babel config ") + "to enable transformation."; + } else { + var syntaxPluginInfo = getNameURLCombination(syntaxPlugin); + helpMessage += "\n\nAdd ".concat(syntaxPluginInfo, " to the 'plugins' section of your Babel config ") + "to enable parsing."; + } + } } - if (computed) { - this.token("["); - this.print(node.property, node); - this.token("]"); - } else { - this.token("."); - this.print(node.property, node); - } + return helpMessage; } -function MetaProperty(node) { - this.print(node.meta, node); - this.token("."); - this.print(node.property, node); -} -},{"../node":45,"babel-types":151}],37:[function(require,module,exports){ +},{}],34:[function(require,module,exports){ +(function (process){ "use strict"; -exports.__esModule = true; -exports.TypeParameterDeclaration = exports.StringLiteralTypeAnnotation = exports.NumericLiteralTypeAnnotation = exports.GenericTypeAnnotation = exports.ClassImplements = undefined; -exports.AnyTypeAnnotation = AnyTypeAnnotation; -exports.ArrayTypeAnnotation = ArrayTypeAnnotation; -exports.BooleanTypeAnnotation = BooleanTypeAnnotation; -exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; -exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; -exports.DeclareClass = DeclareClass; -exports.DeclareFunction = DeclareFunction; -exports.DeclareInterface = DeclareInterface; -exports.DeclareModule = DeclareModule; -exports.DeclareModuleExports = DeclareModuleExports; -exports.DeclareTypeAlias = DeclareTypeAlias; -exports.DeclareOpaqueType = DeclareOpaqueType; -exports.DeclareVariable = DeclareVariable; -exports.DeclareExportDeclaration = DeclareExportDeclaration; -exports.ExistentialTypeParam = ExistentialTypeParam; -exports.FunctionTypeAnnotation = FunctionTypeAnnotation; -exports.FunctionTypeParam = FunctionTypeParam; -exports.InterfaceExtends = InterfaceExtends; -exports._interfaceish = _interfaceish; -exports._variance = _variance; -exports.InterfaceDeclaration = InterfaceDeclaration; -exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; -exports.MixedTypeAnnotation = MixedTypeAnnotation; -exports.EmptyTypeAnnotation = EmptyTypeAnnotation; -exports.NullableTypeAnnotation = NullableTypeAnnotation; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -var _types = require("./types"); +/* eslint-env browser */ -Object.defineProperty(exports, "NumericLiteralTypeAnnotation", { - enumerable: true, - get: function get() { - return _types.NumericLiteral; - } -}); -Object.defineProperty(exports, "StringLiteralTypeAnnotation", { - enumerable: true, - get: function get() { - return _types.StringLiteral; - } -}); -exports.NumberTypeAnnotation = NumberTypeAnnotation; -exports.StringTypeAnnotation = StringTypeAnnotation; -exports.ThisTypeAnnotation = ThisTypeAnnotation; -exports.TupleTypeAnnotation = TupleTypeAnnotation; -exports.TypeofTypeAnnotation = TypeofTypeAnnotation; -exports.TypeAlias = TypeAlias; -exports.OpaqueType = OpaqueType; -exports.TypeAnnotation = TypeAnnotation; -exports.TypeParameter = TypeParameter; -exports.TypeParameterInstantiation = TypeParameterInstantiation; -exports.ObjectTypeAnnotation = ObjectTypeAnnotation; -exports.ObjectTypeCallProperty = ObjectTypeCallProperty; -exports.ObjectTypeIndexer = ObjectTypeIndexer; -exports.ObjectTypeProperty = ObjectTypeProperty; -exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; -exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; -exports.UnionTypeAnnotation = UnionTypeAnnotation; -exports.TypeCastExpression = TypeCastExpression; -exports.VoidTypeAnnotation = VoidTypeAnnotation; +/** + * This is the web browser implementation of `debug()`. + */ +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +/** + * Colors. + */ -var _babelTypes = require("babel-types"); +exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33']; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ +// eslint-disable-next-line complexity -var t = _interopRequireWildcard(_babelTypes); +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } // Internet Explorer and Edge do not support colors. -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -function AnyTypeAnnotation() { - this.word("any"); -} + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 -function ArrayTypeAnnotation(node) { - this.print(node.elementType, node); - this.token("["); - this.token("]"); -} -function BooleanTypeAnnotation() { - this.word("boolean"); + return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } +/** + * Colorize log arguments if enabled. + * + * @api public + */ -function BooleanLiteralTypeAnnotation(node) { - this.word(node.value ? "true" : "false"); -} -function NullLiteralTypeAnnotation() { - this.word("null"); -} +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); -function DeclareClass(node, parent) { - if (!t.isDeclareExportDeclaration(parent)) { - this.word("declare"); - this.space(); + if (!this.useColors) { + return; } - this.word("class"); - this.space(); - this._interfaceish(node); -} -function DeclareFunction(node, parent) { - if (!t.isDeclareExportDeclaration(parent)) { - this.word("declare"); - this.space(); - } - this.word("function"); - this.space(); - this.print(node.id, node); - this.print(node.id.typeAnnotation.typeAnnotation, node); - this.semicolon(); -} + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into -function DeclareInterface(node) { - this.word("declare"); - this.space(); - this.InterfaceDeclaration(node); -} + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function (match) { + if (match === '%%') { + return; + } -function DeclareModule(node) { - this.word("declare"); - this.space(); - this.word("module"); - this.space(); - this.print(node.id, node); - this.space(); - this.print(node.body, node); -} + index++; -function DeclareModuleExports(node) { - this.word("declare"); - this.space(); - this.word("module"); - this.token("."); - this.word("exports"); - this.print(node.typeAnnotation, node); + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + args.splice(lastC, 0, c); } +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ -function DeclareTypeAlias(node) { - this.word("declare"); - this.space(); - this.TypeAlias(node); -} - -function DeclareOpaqueType(node, parent) { - if (!t.isDeclareExportDeclaration(parent)) { - this.word("declare"); - this.space(); - } - this.OpaqueType(node); -} - -function DeclareVariable(node, parent) { - if (!t.isDeclareExportDeclaration(parent)) { - this.word("declare"); - this.space(); - } - this.word("var"); - this.space(); - this.print(node.id, node); - this.print(node.id.typeAnnotation, node); - this.semicolon(); -} -function DeclareExportDeclaration(node) { - this.word("declare"); - this.space(); - this.word("export"); - this.space(); - if (node.default) { - this.word("default"); - this.space(); - } +function log() { + var _console; - FlowExportDeclaration.apply(this, arguments); + // This hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments); } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -function FlowExportDeclaration(node) { - if (node.declaration) { - var declar = node.declaration; - this.print(declar, node); - if (!t.isStatement(declar)) this.semicolon(); - } else { - this.token("{"); - if (node.specifiers.length) { - this.space(); - this.printList(node.specifiers, node); - this.space(); - } - this.token("}"); - if (node.source) { - this.space(); - this.word("from"); - this.space(); - this.print(node.source, node); +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); } - - this.semicolon(); + } catch (error) {// Swallow + // XXX (@Qix-) should we be logging these? } } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -function ExistentialTypeParam() { - this.token("*"); -} -function FunctionTypeAnnotation(node, parent) { - this.print(node.typeParameters, node); - this.token("("); - this.printList(node.params, node); +function load() { + var r; - if (node.rest) { - if (node.params.length) { - this.token(","); - this.space(); - } - this.token("..."); - this.print(node.rest, node); - } + try { + r = exports.storage.getItem('debug'); + } catch (error) {} // Swallow + // XXX (@Qix-) should we be logging these? + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - this.token(")"); - if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") { - this.token(":"); - } else { - this.space(); - this.token("=>"); + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; } - this.space(); - this.print(node.returnType, node); -} - -function FunctionTypeParam(node) { - this.print(node.name, node); - if (node.optional) this.token("?"); - this.token(":"); - this.space(); - this.print(node.typeAnnotation, node); + return r; } +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ -function InterfaceExtends(node) { - this.print(node.id, node); - this.print(node.typeParameters, node); -} -exports.ClassImplements = InterfaceExtends; -exports.GenericTypeAnnotation = InterfaceExtends; -function _interfaceish(node) { - this.print(node.id, node); - this.print(node.typeParameters, node); - if (node.extends.length) { - this.space(); - this.word("extends"); - this.space(); - this.printList(node.extends, node); - } - if (node.mixins && node.mixins.length) { - this.space(); - this.word("mixins"); - this.space(); - this.printList(node.mixins, node); +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) {// Swallow + // XXX (@Qix-) should we be logging these? } - this.space(); - this.print(node.body, node); } -function _variance(node) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); +module.exports = require('./common')(exports); +var formatters = module.exports.formatters; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; } -} +}; -function InterfaceDeclaration(node) { - this.word("interface"); - this.space(); - this._interfaceish(node); -} +}).call(this,require('_process')) +},{"./common":35,"_process":1054}],35:[function(require,module,exports){ +"use strict"; -function andSeparator() { - this.space(); - this.token("&"); - this.space(); -} +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } -function IntersectionTypeAnnotation(node) { - this.printJoin(node.types, node, { separator: andSeparator }); -} +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } -function MixedTypeAnnotation() { - this.word("mixed"); -} +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -function EmptyTypeAnnotation() { - this.word("empty"); -} +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } -function NullableTypeAnnotation(node) { - this.token("?"); - this.print(node.typeAnnotation, node); -} +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + Object.keys(env).forEach(function (key) { + createDebug[key] = env[key]; + }); + /** + * Active `debug` instances. + */ + + createDebug.instances = []; + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + + createDebug.formatters = {}; + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + + function selectColor(namespace) { + var hash = 0; + + for (var i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + + createDebug.selectColor = selectColor; + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + + function createDebug(namespace) { + var prevTime; + + function debug() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } -function NumberTypeAnnotation() { - this.word("number"); -} + // Disabled? + if (!debug.enabled) { + return; + } -function StringTypeAnnotation() { - this.word("string"); -} + var self = debug; // Set `diff` timestamp -function ThisTypeAnnotation() { - this.word("this"); -} + var curr = Number(new Date()); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); -function TupleTypeAnnotation(node) { - this.token("["); - this.printList(node.types, node); - this.token("]"); -} + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } // Apply any `formatters` transformations -function TypeofTypeAnnotation(node) { - this.word("typeof"); - this.space(); - this.print(node.argument, node); -} -function TypeAlias(node) { - this.word("type"); - this.space(); - this.print(node.id, node); - this.print(node.typeParameters, node); - this.space(); - this.token("="); - this.space(); - this.print(node.right, node); - this.semicolon(); -} -function OpaqueType(node) { - this.word("opaque"); - this.space(); - this.word("type"); - this.space(); - this.print(node.id, node); - this.print(node.typeParameters, node); - if (node.supertype) { - this.token(":"); - this.space(); - this.print(node.supertype, node); - } - if (node.impltype) { - this.space(); - this.token("="); - this.space(); - this.print(node.impltype, node); - } - this.semicolon(); -} + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return match; + } -function TypeAnnotation(node) { - this.token(":"); - this.space(); - if (node.optional) this.token("?"); - this.print(node.typeAnnotation, node); -} + index++; + var formatter = createDebug.formatters[format]; -function TypeParameter(node) { - this._variance(node); + if (typeof formatter === 'function') { + var val = args[index]; + match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` - this.word(node.name); + args.splice(index, 1); + index--; + } - if (node.bound) { - this.print(node.bound, node); - } + return match; + }); // Apply env-specific formatting (colors, etc.) - if (node.default) { - this.space(); - this.token("="); - this.space(); - this.print(node.default, node); + createDebug.formatArgs.call(self, args); + var logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = createDebug.enabled(namespace); + debug.useColors = createDebug.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + debug.extend = extend; // Debug.formatArgs = formatArgs; + // debug.rawLog = rawLog; + // env-specific initialization logic for debug instances + + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + createDebug.instances.push(debug); + return debug; } -} -function TypeParameterInstantiation(node) { - this.token("<"); - this.printList(node.params, node, {}); - this.token(">"); -} + function destroy() { + var index = createDebug.instances.indexOf(this); -exports.TypeParameterDeclaration = TypeParameterInstantiation; -function ObjectTypeAnnotation(node) { - var _this = this; + if (index !== -1) { + createDebug.instances.splice(index, 1); + return true; + } - if (node.exact) { - this.token("{|"); - } else { - this.token("{"); + return false; } - var props = node.properties.concat(node.callProperties, node.indexers); + function extend(namespace, delimiter) { + var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ - if (props.length) { - this.space(); - this.printJoin(props, node, { - addNewlines: function addNewlines(leading) { - if (leading && !props[0]) return 1; - }, + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.names = []; + createDebug.skips = []; + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - indent: true, - statement: true, - iterator: function iterator() { - if (props.length !== 1) { - if (_this.format.flowCommaSeparator) { - _this.token(","); - } else { - _this.semicolon(); - } - _this.space(); - } + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; } - }); - this.space(); - } + namespaces = split[i].replace(/\*/g, '.*?'); - if (node.exact) { - this.token("|}"); - } else { - this.token("}"); - } -} + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } -function ObjectTypeCallProperty(node) { - if (node.static) { - this.word("static"); - this.space(); + for (i = 0; i < createDebug.instances.length; i++) { + var instance = createDebug.instances[i]; + instance.enabled = createDebug.enabled(instance.namespace); + } } - this.print(node.value, node); -} + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ -function ObjectTypeIndexer(node) { - if (node.static) { - this.word("static"); - this.space(); - } - this._variance(node); - this.token("["); - this.print(node.id, node); - this.token(":"); - this.space(); - this.print(node.key, node); - this.token("]"); - this.token(":"); - this.space(); - this.print(node.value, node); -} -function ObjectTypeProperty(node) { - if (node.static) { - this.word("static"); - this.space(); + function disable() { + var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) { + return '-' + namespace; + }))).join(','); + createDebug.enable(''); + return namespaces; } - this._variance(node); - this.print(node.key, node); - if (node.optional) this.token("?"); - this.token(":"); - this.space(); - this.print(node.value, node); -} - -function ObjectTypeSpreadProperty(node) { - this.token("..."); - this.print(node.argument, node); -} + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ -function QualifiedTypeIdentifier(node) { - this.print(node.qualification, node); - this.token("."); - this.print(node.id, node); -} -function orSeparator() { - this.space(); - this.token("|"); - this.space(); -} + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } -function UnionTypeAnnotation(node) { - this.printJoin(node.types, node, { separator: orSeparator }); -} + var i; + var len; -function TypeCastExpression(node) { - this.token("("); - this.print(node.expression, node); - this.print(node.typeAnnotation, node); - this.token(")"); -} + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } -function VoidTypeAnnotation() { - this.word("void"); -} -},{"./types":43,"babel-types":151}],38:[function(require,module,exports){ -"use strict"; + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } -exports.__esModule = true; + return false; + } + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -var _getIterator3 = _interopRequireDefault(_getIterator2); + function toNamespace(regexp) { + return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*'); + } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ -exports.JSXAttribute = JSXAttribute; -exports.JSXIdentifier = JSXIdentifier; -exports.JSXNamespacedName = JSXNamespacedName; -exports.JSXMemberExpression = JSXMemberExpression; -exports.JSXSpreadAttribute = JSXSpreadAttribute; -exports.JSXExpressionContainer = JSXExpressionContainer; -exports.JSXSpreadChild = JSXSpreadChild; -exports.JSXText = JSXText; -exports.JSXElement = JSXElement; -exports.JSXOpeningElement = JSXOpeningElement; -exports.JSXClosingElement = JSXClosingElement; -exports.JSXEmptyExpression = JSXEmptyExpression; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } -function JSXAttribute(node) { - this.print(node.name, node); - if (node.value) { - this.token("="); - this.print(node.value, node); + return val; } -} -function JSXIdentifier(node) { - this.word(node.name); + createDebug.enable(createDebug.load()); + return createDebug; } -function JSXNamespacedName(node) { - this.print(node.namespace, node); - this.token(":"); - this.print(node.name, node); -} +module.exports = setup; -function JSXMemberExpression(node) { - this.print(node.object, node); - this.token("."); - this.print(node.property, node); -} +},{"ms":36}],36:[function(require,module,exports){ +"use strict"; -function JSXSpreadAttribute(node) { - this.token("{"); - this.token("..."); - this.print(node.argument, node); - this.token("}"); -} +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -function JSXExpressionContainer(node) { - this.token("{"); - this.print(node.expression, node); - this.token("}"); -} +/** + * Helpers. + */ +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ -function JSXSpreadChild(node) { - this.token("{"); - this.token("..."); - this.print(node.expression, node); - this.token("}"); -} +module.exports = function (val, options) { + options = options || {}; -function JSXText(node) { - this.token(node.value); -} + var type = _typeof(val); -function JSXElement(node) { - var open = node.openingElement; - this.print(open, node); - if (open.selfClosing) return; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } - this.indent(); - for (var _iterator = node.children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)); +}; +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - var child = _ref; +function parse(str) { + str = String(str); - this.print(child, node); + if (str.length > 100) { + return; } - this.dedent(); - - this.print(node.closingElement, node); -} -function spaceSeparator() { - this.space(); -} + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); -function JSXOpeningElement(node) { - this.token("<"); - this.print(node.name, node); - if (node.attributes.length > 0) { - this.space(); - this.printJoin(node.attributes, node, { separator: spaceSeparator }); - } - if (node.selfClosing) { - this.space(); - this.token("/>"); - } else { - this.token(">"); + if (!match) { + return; } -} -function JSXClosingElement(node) { - this.token(""); -} + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); -function JSXEmptyExpression() {} -},{"babel-runtime/core-js/get-iterator":95}],39:[function(require,module,exports){ -"use strict"; + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; -exports.__esModule = true; -exports.FunctionDeclaration = undefined; -exports._params = _params; -exports._method = _method; -exports.FunctionExpression = FunctionExpression; -exports.ArrowFunctionExpression = ArrowFunctionExpression; + case 'weeks': + case 'week': + case 'w': + return n * w; -var _babelTypes = require("babel-types"); + case 'days': + case 'day': + case 'd': + return n * d; -var t = _interopRequireWildcard(_babelTypes); + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; -function _params(node) { - var _this = this; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; - this.print(node.typeParameters, node); - this.token("("); - this.printList(node.params, node, { - iterator: function iterator(node) { - if (node.optional) _this.token("?"); - _this.print(node.typeAnnotation, node); - } - }); - this.token(")"); + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; - if (node.returnType) { - this.print(node.returnType, node); + default: + return undefined; } } +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -function _method(node) { - var kind = node.kind; - var key = node.key; - if (kind === "method" || kind === "init") { - if (node.generator) { - this.token("*"); - } +function fmtShort(ms) { + var msAbs = Math.abs(ms); + + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; } - if (kind === "get" || kind === "set") { - this.word(kind); - this.space(); + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; } - if (node.async) { - this.word("async"); - this.space(); + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; } - if (node.computed) { - this.token("["); - this.print(key, node); - this.token("]"); - } else { - this.print(key, node); + if (msAbs >= s) { + return Math.round(ms / s) + 's'; } - this._params(node); - this.space(); - this.print(node.body, node); + return ms + 'ms'; } +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -function FunctionExpression(node) { - if (node.async) { - this.word("async"); - this.space(); - } - this.word("function"); - if (node.generator) this.token("*"); - if (node.id) { - this.space(); - this.print(node.id, node); - } else { - this.space(); - } +function fmtLong(ms) { + var msAbs = Math.abs(ms); - this._params(node); - this.space(); - this.print(node.body, node); -} + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } -exports.FunctionDeclaration = FunctionExpression; -function ArrowFunctionExpression(node) { - if (node.async) { - this.word("async"); - this.space(); + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); } - var firstParam = node.params[0]; + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } - if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) { - this.print(firstParam, node); - } else { - this._params(node); + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); } - this.space(); - this.token("=>"); - this.space(); + return ms + ' ms'; +} +/** + * Pluralization helper. + */ - this.print(node.body, node); + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } -function hasTypes(node, param) { - return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; +},{}],37:[function(require,module,exports){ +module.exports={ + "_from": "@babel/core@*", + "_id": "@babel/core@7.7.2", + "_inBundle": false, + "_integrity": "sha512-eeD7VEZKfhK1KUXGiyPFettgF3m513f8FoBSWiQ1xTvl1RAopLs42Wp9+Ze911I6H0N9lNqJMDgoZT7gHsipeQ==", + "_location": "/@babel/core", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/core@*", + "name": "@babel/core", + "escapedName": "@babel%2fcore", + "scope": "@babel", + "rawSpec": "*", + "saveSpec": null, + "fetchSpec": "*" + }, + "_requiredBy": [ + "#DEV:/" + ], + "_resolved": "https://registry.npmjs.org/@babel/core/-/core-7.7.2.tgz", + "_shasum": "ea5b99693bcfc058116f42fa1dd54da412b29d91", + "_spec": "@babel/core@*", + "_where": "/local/home/ossman/devel/noVNC", + "author": { + "name": "Sebastian McKenzie", + "email": "sebmck@gmail.com" + }, + "browser": { + "./lib/config/files/index.js": "./lib/config/files/index-browser.js", + "./lib/transform-file.js": "./lib/transform-file-browser.js" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/code-frame": "^7.5.5", + "@babel/generator": "^7.7.2", + "@babel/helpers": "^7.7.0", + "@babel/parser": "^7.7.2", + "@babel/template": "^7.7.0", + "@babel/traverse": "^7.7.2", + "@babel/types": "^7.7.2", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "json5": "^2.1.0", + "lodash": "^4.17.13", + "resolve": "^1.3.2", + "semver": "^5.4.1", + "source-map": "^0.5.0" + }, + "deprecated": false, + "description": "Babel compiler core.", + "devDependencies": { + "@babel/helper-transform-fixture-test-runner": "^7.6.4" + }, + "engines": { + "node": ">=6.9.0" + }, + "gitHead": "35f4d1276310bac6fede4a6f86a5c76f951e179e", + "homepage": "https://babeljs.io/", + "keywords": [ + "6to5", + "babel", + "classes", + "const", + "es6", + "harmony", + "let", + "modules", + "transpile", + "transpiler", + "var", + "babel-core", + "compiler" + ], + "license": "MIT", + "main": "lib/index.js", + "name": "@babel/core", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel/tree/master/packages/babel-core" + }, + "version": "7.7.2" } -},{"babel-types":151}],40:[function(require,module,exports){ + +},{}],38:[function(require,module,exports){ "use strict"; -exports.__esModule = true; -exports.ImportSpecifier = ImportSpecifier; -exports.ImportDefaultSpecifier = ImportDefaultSpecifier; -exports.ExportDefaultSpecifier = ExportDefaultSpecifier; -exports.ExportSpecifier = ExportSpecifier; -exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; -exports.ExportAllDeclaration = ExportAllDeclaration; -exports.ExportNamedDeclaration = ExportNamedDeclaration; -exports.ExportDefaultDeclaration = ExportDefaultDeclaration; -exports.ImportDeclaration = ImportDeclaration; -exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } -var _babelTypes = require("babel-types"); +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } -var t = _interopRequireWildcard(_babelTypes); +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } -function ImportSpecifier(node) { - if (node.importKind === "type" || node.importKind === "typeof") { - this.word(node.importKind); - this.space(); - } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - this.print(node.imported, node); - if (node.local && node.local.name !== node.imported.name) { - this.space(); - this.word("as"); - this.space(); - this.print(node.local, node); - } -} +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -function ImportDefaultSpecifier(node) { - this.print(node.local, node); -} +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -function ExportDefaultSpecifier(node) { - this.print(node.exported, node); -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var SPACES_RE = /^[ \t]+$/; -function ExportSpecifier(node) { - this.print(node.local, node); - if (node.exported && node.local.name !== node.exported.name) { - this.space(); - this.word("as"); - this.space(); - this.print(node.exported, node); +var Buffer = +/*#__PURE__*/ +function () { + function Buffer(map) { + _classCallCheck(this, Buffer); + + this._map = null; + this._buf = []; + this._last = ""; + this._queue = []; + this._position = { + line: 1, + column: 0 + }; + this._sourcePosition = { + identifierName: null, + line: null, + column: null, + filename: null + }; + this._disallowedPop = null; + this._map = map; } -} -function ExportNamespaceSpecifier(node) { - this.token("*"); - this.space(); - this.word("as"); - this.space(); - this.print(node.exported, node); -} + _createClass(Buffer, [{ + key: "get", + value: function get() { + this._flush(); -function ExportAllDeclaration(node) { - this.word("export"); - this.space(); - this.token("*"); - this.space(); - this.word("from"); - this.space(); - this.print(node.source, node); - this.semicolon(); -} + var map = this._map; + var result = { + code: this._buf.join("").trimRight(), + map: null, + rawMappings: map && map.getRawMappings() + }; -function ExportNamedDeclaration() { - this.word("export"); - this.space(); - ExportDeclaration.apply(this, arguments); -} + if (map) { + Object.defineProperty(result, "map", { + configurable: true, + enumerable: true, + get: function get() { + return this.map = map.get(); + }, + set: function set(value) { + Object.defineProperty(this, "map", { + value: value, + writable: true + }); + } + }); + } -function ExportDefaultDeclaration() { - this.word("export"); - this.space(); - this.word("default"); - this.space(); - ExportDeclaration.apply(this, arguments); -} + return result; + } + }, { + key: "append", + value: function append(str) { + this._flush(); + + var _this$_sourcePosition = this._sourcePosition, + line = _this$_sourcePosition.line, + column = _this$_sourcePosition.column, + filename = _this$_sourcePosition.filename, + identifierName = _this$_sourcePosition.identifierName, + force = _this$_sourcePosition.force; + + this._append(str, line, column, identifierName, filename, force); + } + }, { + key: "queue", + value: function queue(str) { + if (str === "\n") { + while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { + this._queue.shift(); + } + } -function ExportDeclaration(node) { - if (node.declaration) { - var declar = node.declaration; - this.print(declar, node); - if (!t.isStatement(declar)) this.semicolon(); - } else { - if (node.exportKind === "type") { - this.word("type"); - this.space(); + var _this$_sourcePosition2 = this._sourcePosition, + line = _this$_sourcePosition2.line, + column = _this$_sourcePosition2.column, + filename = _this$_sourcePosition2.filename, + identifierName = _this$_sourcePosition2.identifierName, + force = _this$_sourcePosition2.force; + + this._queue.unshift([str, line, column, identifierName, filename, force]); } + }, { + key: "_flush", + value: function _flush() { + var item; - var specifiers = node.specifiers.slice(0); + while (item = this._queue.pop()) { + this._append.apply(this, _toConsumableArray(item)); + } + } + }, { + key: "_append", + value: function _append(str, line, column, identifierName, filename, force) { + if (this._map && str[0] !== "\n") { + this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename, force); + } - var hasSpecial = false; - while (true) { - var first = specifiers[0]; - if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) { - hasSpecial = true; - this.print(specifiers.shift(), node); - if (specifiers.length) { - this.token(","); - this.space(); + this._buf.push(str); + + this._last = str[str.length - 1]; + + for (var i = 0; i < str.length; i++) { + if (str[i] === "\n") { + this._position.line++; + this._position.column = 0; + } else { + this._position.column++; } - } else { - break; } } - - if (specifiers.length || !specifiers.length && !hasSpecial) { - this.token("{"); - if (specifiers.length) { - this.space(); - this.printList(specifiers, node); - this.space(); + }, { + key: "removeTrailingNewline", + value: function removeTrailingNewline() { + if (this._queue.length > 0 && this._queue[0][0] === "\n") { + this._queue.shift(); } - this.token("}"); } - - if (node.source) { - this.space(); - this.word("from"); - this.space(); - this.print(node.source, node); + }, { + key: "removeLastSemicolon", + value: function removeLastSemicolon() { + if (this._queue.length > 0 && this._queue[0][0] === ";") { + this._queue.shift(); + } } + }, { + key: "endsWith", + value: function endsWith(suffix) { + if (suffix.length === 1) { + var last; - this.semicolon(); - } -} + if (this._queue.length > 0) { + var str = this._queue[0][0]; + last = str[str.length - 1]; + } else { + last = this._last; + } -function ImportDeclaration(node) { - this.word("import"); - this.space(); + return last === suffix; + } - if (node.importKind === "type" || node.importKind === "typeof") { - this.word(node.importKind); - this.space(); - } + var end = this._last + this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); - var specifiers = node.specifiers.slice(0); - if (specifiers && specifiers.length) { - while (true) { - var first = specifiers[0]; - if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) { - this.print(specifiers.shift(), node); - if (specifiers.length) { - this.token(","); - this.space(); - } - } else { - break; + if (suffix.length <= end.length) { + return end.slice(-suffix.length) === suffix; } - } - if (specifiers.length) { - this.token("{"); - this.space(); - this.printList(specifiers, node); - this.space(); - this.token("}"); + return false; } + }, { + key: "hasContent", + value: function hasContent() { + return this._queue.length > 0 || !!this._last; + } + }, { + key: "exactSource", + value: function exactSource(loc, cb) { + this.source("start", loc, true); + cb(); + this.source("end", loc); + + this._disallowPop("start", loc); + } + }, { + key: "source", + value: function source(prop, loc, force) { + if (prop && !loc) return; + + this._normalizePosition(prop, loc, this._sourcePosition, force); + } + }, { + key: "withSource", + value: function withSource(prop, loc, cb) { + if (!this._map) return cb(); + var originalLine = this._sourcePosition.line; + var originalColumn = this._sourcePosition.column; + var originalFilename = this._sourcePosition.filename; + var originalIdentifierName = this._sourcePosition.identifierName; + this.source(prop, loc); + cb(); + + if ((!this._sourcePosition.force || this._sourcePosition.line !== originalLine || this._sourcePosition.column !== originalColumn || this._sourcePosition.filename !== originalFilename) && (!this._disallowedPop || this._disallowedPop.line !== originalLine || this._disallowedPop.column !== originalColumn || this._disallowedPop.filename !== originalFilename)) { + this._sourcePosition.line = originalLine; + this._sourcePosition.column = originalColumn; + this._sourcePosition.filename = originalFilename; + this._sourcePosition.identifierName = originalIdentifierName; + this._sourcePosition.force = false; + this._disallowedPop = null; + } + } + }, { + key: "_disallowPop", + value: function _disallowPop(prop, loc) { + if (prop && !loc) return; + this._disallowedPop = this._normalizePosition(prop, loc); + } + }, { + key: "_normalizePosition", + value: function _normalizePosition(prop, loc, targetObj, force) { + var pos = loc ? loc[prop] : null; + + if (targetObj === undefined) { + targetObj = { + identifierName: null, + line: null, + column: null, + filename: null, + force: false + }; + } - this.space(); - this.word("from"); - this.space(); - } + var origLine = targetObj.line; + var origColumn = targetObj.column; + var origFilename = targetObj.filename; + targetObj.identifierName = prop === "start" && loc && loc.identifierName || null; + targetObj.line = pos ? pos.line : null; + targetObj.column = pos ? pos.column : null; + targetObj.filename = loc && loc.filename || null; - this.print(node.source, node); - this.semicolon(); -} + if (force || targetObj.line !== origLine || targetObj.column !== origColumn || targetObj.filename !== origFilename) { + targetObj.force = force; + } -function ImportNamespaceSpecifier(node) { - this.token("*"); - this.space(); - this.word("as"); - this.space(); - this.print(node.local, node); -} -},{"babel-types":151}],41:[function(require,module,exports){ -"use strict"; + return targetObj; + } + }, { + key: "getCurrentColumn", + value: function getCurrentColumn() { + var extra = this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); -exports.__esModule = true; -exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForAwaitStatement = exports.ForOfStatement = exports.ForInStatement = undefined; + var lastIndex = extra.lastIndexOf("\n"); + return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; + } + }, { + key: "getCurrentLine", + value: function getCurrentLine() { + var extra = this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + var count = 0; -var _getIterator3 = _interopRequireDefault(_getIterator2); + for (var i = 0; i < extra.length; i++) { + if (extra[i] === "\n") count++; + } -exports.WithStatement = WithStatement; -exports.IfStatement = IfStatement; -exports.ForStatement = ForStatement; -exports.WhileStatement = WhileStatement; -exports.DoWhileStatement = DoWhileStatement; -exports.LabeledStatement = LabeledStatement; -exports.TryStatement = TryStatement; -exports.CatchClause = CatchClause; -exports.SwitchStatement = SwitchStatement; -exports.SwitchCase = SwitchCase; -exports.DebuggerStatement = DebuggerStatement; -exports.VariableDeclaration = VariableDeclaration; -exports.VariableDeclarator = VariableDeclarator; + return this._position.line + count; + } + }]); + + return Buffer; +}(); -var _babelTypes = require("babel-types"); +exports.default = Buffer; -var t = _interopRequireWildcard(_babelTypes); +},{}],39:[function(require,module,exports){ +"use strict"; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.File = File; +exports.Program = Program; +exports.BlockStatement = BlockStatement; +exports.Noop = Noop; +exports.Directive = Directive; +exports.DirectiveLiteral = DirectiveLiteral; +exports.InterpreterDirective = InterpreterDirective; +exports.Placeholder = Placeholder; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function File(node) { + if (node.program) { + this.print(node.program.interpreter, node); + } -function WithStatement(node) { - this.word("with"); - this.space(); - this.token("("); - this.print(node.object, node); - this.token(")"); - this.printBlock(node); + this.print(node.program, node); } -function IfStatement(node) { - this.word("if"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.space(); - - var needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); - if (needsBlock) { - this.token("{"); - this.newline(); - this.indent(); - } +function Program(node) { + this.printInnerComments(node, false); + this.printSequence(node.directives, node); + if (node.directives && node.directives.length) this.newline(); + this.printSequence(node.body, node); +} - this.printAndIndentOnComments(node.consequent, node); +function BlockStatement(node) { + this.token("{"); + this.printInnerComments(node); + var hasDirectives = node.directives && node.directives.length; - if (needsBlock) { - this.dedent(); + if (node.body.length || hasDirectives) { this.newline(); + this.printSequence(node.directives, node, { + indent: true + }); + if (hasDirectives) this.newline(); + this.printSequence(node.body, node, { + indent: true + }); + this.removeTrailingNewline(); + this.source("end", node.loc); + if (!this.endsWith("\n")) this.newline(); + this.rightBrace(); + } else { + this.source("end", node.loc); this.token("}"); } - - if (node.alternate) { - if (this.endsWith("}")) this.space(); - this.word("else"); - this.space(); - this.printAndIndentOnComments(node.alternate, node); - } } -function getLastStatement(statement) { - if (!t.isStatement(statement.body)) return statement; - return getLastStatement(statement.body); +function Noop() {} + +function Directive(node) { + this.print(node.value, node); + this.semicolon(); } -function ForStatement(node) { - this.word("for"); - this.space(); - this.token("("); +var unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/; +var unescapedDoubleQuoteRE = /(?:^|[^\\])(?:\\\\)*"/; - this.inForStatementInitCounter++; - this.print(node.init, node); - this.inForStatementInitCounter--; - this.token(";"); +function DirectiveLiteral(node) { + var raw = this.getPossibleRaw(node); - if (node.test) { - this.space(); - this.print(node.test, node); + if (raw != null) { + this.token(raw); + return; } - this.token(";"); - if (node.update) { - this.space(); - this.print(node.update, node); + var value = node.value; + + if (!unescapedDoubleQuoteRE.test(value)) { + this.token("\"".concat(value, "\"")); + } else if (!unescapedSingleQuoteRE.test(value)) { + this.token("'".concat(value, "'")); + } else { + throw new Error("Malformed AST: it is not possible to print a directive containing" + " both unescaped single and double quotes."); } +} - this.token(")"); - this.printBlock(node); +function InterpreterDirective(node) { + this.token("#!".concat(node.value, "\n")); } -function WhileStatement(node) { - this.word("while"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.printBlock(node); +function Placeholder(node) { + this.token("%%"); + this.print(node.name); + this.token("%%"); + + if (node.expectedNode === "Statement") { + this.semicolon(); + } } -var buildForXStatement = function buildForXStatement(op) { - return function (node) { - this.word("for"); - this.space(); - if (op === "await") { - this.word("await"); - this.space(); - } - this.token("("); +},{}],40:[function(require,module,exports){ +"use strict"; - this.print(node.left, node); - this.space(); - this.word(op === "await" ? "of" : op); - this.space(); - this.print(node.right, node); - this.token(")"); - this.printBlock(node); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClassExpression = exports.ClassDeclaration = ClassDeclaration; +exports.ClassBody = ClassBody; +exports.ClassProperty = ClassProperty; +exports.ClassPrivateProperty = ClassPrivateProperty; +exports.ClassMethod = ClassMethod; +exports.ClassPrivateMethod = ClassPrivateMethod; +exports._classMethodHead = _classMethodHead; + +var t = _interopRequireWildcard(require("@babel/types")); + +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); + + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; -}; -var ForInStatement = exports.ForInStatement = buildForXStatement("in"); -var ForOfStatement = exports.ForOfStatement = buildForXStatement("of"); -var ForAwaitStatement = exports.ForAwaitStatement = buildForXStatement("await"); + return cache; +} -function DoWhileStatement(node) { - this.word("do"); - this.space(); - this.print(node.body, node); - this.space(); - this.word("while"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.semicolon(); -} +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -function buildLabelStatement(prefix) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "label"; + var cache = _getRequireWildcardCache(); - return function (node) { - this.word(prefix); + if (cache && cache.has(obj)) { + return cache.get(obj); + } - var label = node[key]; - if (label) { - this.space(); + var newObj = {}; - var terminatorState = this.startTerminatorless(); - this.print(label, node); - this.endTerminatorless(terminatorState); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } } + } - this.semicolon(); - }; -} + newObj.default = obj; -var ContinueStatement = exports.ContinueStatement = buildLabelStatement("continue"); -var ReturnStatement = exports.ReturnStatement = buildLabelStatement("return", "argument"); -var BreakStatement = exports.BreakStatement = buildLabelStatement("break"); -var ThrowStatement = exports.ThrowStatement = buildLabelStatement("throw", "argument"); + if (cache) { + cache.set(obj, newObj); + } -function LabeledStatement(node) { - this.print(node.label, node); - this.token(":"); - this.space(); - this.print(node.body, node); + return newObj; } -function TryStatement(node) { - this.word("try"); - this.space(); - this.print(node.block, node); - this.space(); - - if (node.handlers) { - this.print(node.handlers[0], node); - } else { - this.print(node.handler, node); +function ClassDeclaration(node, parent) { + if (!this.format.decoratorsBeforeExport || !t.isExportDefaultDeclaration(parent) && !t.isExportNamedDeclaration(parent)) { + this.printJoin(node.decorators, node); } - if (node.finalizer) { - this.space(); - this.word("finally"); + if (node.declare) { + this.word("declare"); this.space(); - this.print(node.finalizer, node); } -} -function CatchClause(node) { - this.word("catch"); - this.space(); - this.token("("); - this.print(node.param, node); - this.token(")"); - this.space(); - this.print(node.body, node); -} + if (node.abstract) { + this.word("abstract"); + this.space(); + } -function SwitchStatement(node) { - this.word("switch"); - this.space(); - this.token("("); - this.print(node.discriminant, node); - this.token(")"); - this.space(); - this.token("{"); + this.word("class"); - this.printSequence(node.cases, node, { - indent: true, - addNewlines: function addNewlines(leading, cas) { - if (!leading && node.cases[node.cases.length - 1] === cas) return -1; - } - }); + if (node.id) { + this.space(); + this.print(node.id, node); + } - this.token("}"); -} + this.print(node.typeParameters, node); -function SwitchCase(node) { - if (node.test) { - this.word("case"); + if (node.superClass) { this.space(); - this.print(node.test, node); - this.token(":"); - } else { - this.word("default"); - this.token(":"); + this.word("extends"); + this.space(); + this.print(node.superClass, node); + this.print(node.superTypeParameters, node); } - if (node.consequent.length) { - this.newline(); - this.printSequence(node.consequent, node, { indent: true }); + if (node.implements) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); } -} -function DebuggerStatement() { - this.word("debugger"); - this.semicolon(); + this.space(); + this.print(node.body, node); } -function variableDeclarationIdent() { - this.token(","); - this.newline(); - if (this.endsWith("\n")) for (var i = 0; i < 4; i++) { - this.space(true); - } -} +function ClassBody(node) { + this.token("{"); + this.printInnerComments(node); -function constDeclarationIdent() { - this.token(","); - this.newline(); - if (this.endsWith("\n")) for (var i = 0; i < 6; i++) { - this.space(true); + if (node.body.length === 0) { + this.token("}"); + } else { + this.newline(); + this.indent(); + this.printSequence(node.body, node); + this.dedent(); + if (!this.endsWith("\n")) this.newline(); + this.rightBrace(); } } -function VariableDeclaration(node, parent) { - this.word(node.kind); - this.space(); - - var hasInits = false; - - if (!t.isFor(parent)) { - for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +function ClassProperty(node) { + this.printJoin(node.decorators, node); + this.tsPrintClassMemberModifiers(node, true); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (node.computed) { + this.token("["); + this.print(node.key, node); + this.token("]"); + } else { + this._variance(node); - var declar = _ref; + this.print(node.key, node); + } - if (declar.init) { - hasInits = true; - } - } + if (node.optional) { + this.token("?"); } - var separator = void 0; - if (hasInits) { - separator = node.kind === "const" ? constDeclarationIdent : variableDeclarationIdent; + if (node.definite) { + this.token("!"); } - this.printList(node.declarations, node, { separator: separator }); + this.print(node.typeAnnotation, node); - if (t.isFor(parent)) { - if (parent.left === node || parent.init === node) return; + if (node.value) { + this.space(); + this.token("="); + this.space(); + this.print(node.value, node); } this.semicolon(); } -function VariableDeclarator(node) { - this.print(node.id, node); - this.print(node.id.typeAnnotation, node); - if (node.init) { +function ClassPrivateProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } + + this.print(node.key, node); + this.print(node.typeAnnotation, node); + + if (node.value) { this.space(); this.token("="); this.space(); - this.print(node.init, node); + this.print(node.value, node); } -} -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],42:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.TaggedTemplateExpression = TaggedTemplateExpression; -exports.TemplateElement = TemplateElement; -exports.TemplateLiteral = TemplateLiteral; -function TaggedTemplateExpression(node) { - this.print(node.tag, node); - this.print(node.quasi, node); + this.semicolon(); } -function TemplateElement(node, parent) { - var isFirst = parent.quasis[0] === node; - var isLast = parent.quasis[parent.quasis.length - 1] === node; - - var value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); +function ClassMethod(node) { + this._classMethodHead(node); - this.token(value); + this.space(); + this.print(node.body, node); } -function TemplateLiteral(node) { - var quasis = node.quasis; +function ClassPrivateMethod(node) { + this._classMethodHead(node); - for (var i = 0; i < quasis.length; i++) { - this.print(quasis[i], node); + this.space(); + this.print(node.body, node); +} - if (i + 1 < quasis.length) { - this.print(node.expressions[i], node); - } - } +function _classMethodHead(node) { + this.printJoin(node.decorators, node); + this.tsPrintClassMemberModifiers(node, false); + + this._methodHead(node); } -},{}],43:[function(require,module,exports){ + +},{"@babel/types":242}],41:[function(require,module,exports){ "use strict"; -exports.__esModule = true; -exports.ArrayPattern = exports.ObjectPattern = exports.RestProperty = exports.SpreadProperty = exports.SpreadElement = undefined; -exports.Identifier = Identifier; -exports.RestElement = RestElement; -exports.ObjectExpression = ObjectExpression; -exports.ObjectMethod = ObjectMethod; -exports.ObjectProperty = ObjectProperty; -exports.ArrayExpression = ArrayExpression; -exports.RegExpLiteral = RegExpLiteral; -exports.BooleanLiteral = BooleanLiteral; -exports.NullLiteral = NullLiteral; -exports.NumericLiteral = NumericLiteral; -exports.StringLiteral = StringLiteral; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UnaryExpression = UnaryExpression; +exports.DoExpression = DoExpression; +exports.ParenthesizedExpression = ParenthesizedExpression; +exports.UpdateExpression = UpdateExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.NewExpression = NewExpression; +exports.SequenceExpression = SequenceExpression; +exports.ThisExpression = ThisExpression; +exports.Super = Super; +exports.Decorator = Decorator; +exports.OptionalMemberExpression = OptionalMemberExpression; +exports.OptionalCallExpression = OptionalCallExpression; +exports.CallExpression = CallExpression; +exports.Import = Import; +exports.EmptyStatement = EmptyStatement; +exports.ExpressionStatement = ExpressionStatement; +exports.AssignmentPattern = AssignmentPattern; +exports.LogicalExpression = exports.BinaryExpression = exports.AssignmentExpression = AssignmentExpression; +exports.BindExpression = BindExpression; +exports.MemberExpression = MemberExpression; +exports.MetaProperty = MetaProperty; +exports.PrivateName = PrivateName; +exports.V8IntrinsicIdentifier = V8IntrinsicIdentifier; +exports.AwaitExpression = exports.YieldExpression = void 0; + +var t = _interopRequireWildcard(require("@babel/types")); -var _babelTypes = require("babel-types"); +var n = _interopRequireWildcard(require("../node")); -var t = _interopRequireWildcard(_babelTypes); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -var _jsesc = require("jsesc"); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; -var _jsesc2 = _interopRequireDefault(_jsesc); + return cache; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var cache = _getRequireWildcardCache(); -function Identifier(node) { - if (node.variance) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); - } + if (cache && cache.has(obj)) { + return cache.get(obj); } - this.word(node.name); -} + var newObj = {}; -function RestElement(node) { - this.token("..."); - this.print(node.argument, node); -} + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -exports.SpreadElement = RestElement; -exports.SpreadProperty = RestElement; -exports.RestProperty = RestElement; -function ObjectExpression(node) { - var props = node.properties; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - this.token("{"); - this.printInnerComments(node); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } - if (props.length) { - this.space(); - this.printList(props, node, { indent: true, statement: true }); + newObj.default = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; +} + +function UnaryExpression(node) { + if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof" || node.operator === "throw") { + this.word(node.operator); this.space(); + } else { + this.token(node.operator); } - this.token("}"); + this.print(node.argument, node); } -exports.ObjectPattern = ObjectExpression; -function ObjectMethod(node) { - this.printJoin(node.decorators, node); - this._method(node); +function DoExpression(node) { + this.word("do"); + this.space(); + this.print(node.body, node); } -function ObjectProperty(node) { - this.printJoin(node.decorators, node); +function ParenthesizedExpression(node) { + this.token("("); + this.print(node.expression, node); + this.token(")"); +} - if (node.computed) { - this.token("["); - this.print(node.key, node); - this.token("]"); +function UpdateExpression(node) { + if (node.prefix) { + this.token(node.operator); + this.print(node.argument, node); } else { - if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) { - this.print(node.value, node); - return; - } - - this.print(node.key, node); - - if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { - return; - } + this.startTerminatorless(true); + this.print(node.argument, node); + this.endTerminatorless(); + this.token(node.operator); } +} +function ConditionalExpression(node) { + this.print(node.test, node); + this.space(); + this.token("?"); + this.space(); + this.print(node.consequent, node); + this.space(); this.token(":"); this.space(); - this.print(node.value, node); + this.print(node.alternate, node); } -function ArrayExpression(node) { - var elems = node.elements; - var len = elems.length; +function NewExpression(node, parent) { + this.word("new"); + this.space(); + this.print(node.callee, node); - this.token("["); - this.printInnerComments(node); + if (this.format.minified && node.arguments.length === 0 && !node.optional && !t.isCallExpression(parent, { + callee: node + }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) { + return; + } - for (var i = 0; i < elems.length; i++) { - var elem = elems[i]; - if (elem) { - if (i > 0) this.space(); - this.print(elem, node); - if (i < len - 1) this.token(","); - } else { - this.token(","); - } + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + + if (node.optional) { + this.token("?."); } - this.token("]"); + this.token("("); + this.printList(node.arguments, node); + this.token(")"); } -exports.ArrayPattern = ArrayExpression; -function RegExpLiteral(node) { - this.word("/" + node.pattern + "/" + node.flags); +function SequenceExpression(node) { + this.printList(node.expressions, node); } -function BooleanLiteral(node) { - this.word(node.value ? "true" : "false"); +function ThisExpression() { + this.word("this"); } -function NullLiteral() { - this.word("null"); +function Super() { + this.word("super"); } -function NumericLiteral(node) { - var raw = this.getPossibleRaw(node); - var value = node.value + ""; - if (raw == null) { - this.number(value); - } else if (this.format.minified) { - this.number(raw.length < value.length ? raw : value); - } else { - this.number(raw); - } +function Decorator(node) { + this.token("@"); + this.print(node.expression, node); + this.newline(); } -function StringLiteral(node, parent) { - var raw = this.getPossibleRaw(node); - if (!this.format.minified && raw != null) { - this.token(raw); - return; +function OptionalMemberExpression(node) { + this.print(node.object, node); + + if (!node.computed && t.isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); } - var opts = { - quotes: t.isJSX(parent) ? "double" : this.format.quotes, - wrap: true - }; - if (this.format.jsonCompatibleStrings) { - opts.json = true; + var computed = node.computed; + + if (t.isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; } - var val = (0, _jsesc2.default)(node.value, opts); - return this.token(val); -} -},{"babel-types":151,"jsesc":296}],44:[function(require,module,exports){ -"use strict"; + if (node.optional) { + this.token("?."); + } -exports.__esModule = true; -exports.CodeGenerator = undefined; + if (computed) { + this.token("["); + this.print(node.property, node); + this.token("]"); + } else { + if (!node.optional) { + this.token("."); + } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + this.print(node.property, node); + } +} -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +function OptionalCallExpression(node) { + this.print(node.callee, node); + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + if (node.optional) { + this.token("?."); + } -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + this.token("("); + this.printList(node.arguments, node); + this.token(")"); +} -var _inherits2 = require("babel-runtime/helpers/inherits"); +function CallExpression(node) { + this.print(node.callee, node); + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + this.token("("); + this.printList(node.arguments, node); + this.token(")"); +} -var _inherits3 = _interopRequireDefault(_inherits2); +function Import() { + this.word("import"); +} -exports.default = function (ast, opts, code) { - var gen = new Generator(ast, opts, code); - return gen.generate(); -}; +function buildYieldAwait(keyword) { + return function (node) { + this.word(keyword); -var _detectIndent = require("detect-indent"); + if (node.delegate) { + this.token("*"); + } -var _detectIndent2 = _interopRequireDefault(_detectIndent); + if (node.argument) { + this.space(); + var terminatorState = this.startTerminatorless(); + this.print(node.argument, node); + this.endTerminatorless(terminatorState); + } + }; +} -var _sourceMap = require("./source-map"); +var YieldExpression = buildYieldAwait("yield"); +exports.YieldExpression = YieldExpression; +var AwaitExpression = buildYieldAwait("await"); +exports.AwaitExpression = AwaitExpression; -var _sourceMap2 = _interopRequireDefault(_sourceMap); +function EmptyStatement() { + this.semicolon(true); +} -var _babelMessages = require("babel-messages"); +function ExpressionStatement(node) { + this.print(node.expression, node); + this.semicolon(); +} -var messages = _interopRequireWildcard(_babelMessages); +function AssignmentPattern(node) { + this.print(node.left, node); + if (node.left.optional) this.token("?"); + this.print(node.left.typeAnnotation, node); + this.space(); + this.token("="); + this.space(); + this.print(node.right, node); +} -var _printer = require("./printer"); +function AssignmentExpression(node, parent) { + var parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); -var _printer2 = _interopRequireDefault(_printer); + if (parens) { + this.token("("); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + this.print(node.left, node); + this.space(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (node.operator === "in" || node.operator === "instanceof") { + this.word(node.operator); + } else { + this.token(node.operator); + } -var Generator = function (_Printer) { - (0, _inherits3.default)(Generator, _Printer); + this.space(); + this.print(node.right, node); - function Generator(ast) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var code = arguments[2]; - (0, _classCallCheck3.default)(this, Generator); + if (parens) { + this.token(")"); + } +} - var tokens = ast.tokens || []; - var format = normalizeOptions(code, opts, tokens); - var map = opts.sourceMaps ? new _sourceMap2.default(opts, code) : null; +function BindExpression(node) { + this.print(node.object, node); + this.token("::"); + this.print(node.callee, node); +} - var _this = (0, _possibleConstructorReturn3.default)(this, _Printer.call(this, format, map, tokens)); +function MemberExpression(node) { + this.print(node.object, node); - _this.ast = ast; - return _this; + if (!node.computed && t.isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); } - Generator.prototype.generate = function generate() { - return _Printer.prototype.generate.call(this, this.ast); - }; + var computed = node.computed; - return Generator; -}(_printer2.default); + if (t.isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } -function normalizeOptions(code, opts, tokens) { - var style = " "; - if (code && typeof code === "string") { - var indent = (0, _detectIndent2.default)(code).indent; - if (indent && indent !== " ") style = indent; + if (computed) { + this.token("["); + this.print(node.property, node); + this.token("]"); + } else { + this.token("."); + this.print(node.property, node); } +} - var format = { - auxiliaryCommentBefore: opts.auxiliaryCommentBefore, - auxiliaryCommentAfter: opts.auxiliaryCommentAfter, - shouldPrintComment: opts.shouldPrintComment, - retainLines: opts.retainLines, - retainFunctionParens: opts.retainFunctionParens, - comments: opts.comments == null || opts.comments, - compact: opts.compact, - minified: opts.minified, - concise: opts.concise, - quotes: opts.quotes || findCommonStringDelimiter(code, tokens), - jsonCompatibleStrings: opts.jsonCompatibleStrings, - indent: { - adjustMultilineComment: true, - style: style, - base: 0 - }, - flowCommaSeparator: opts.flowCommaSeparator - }; +function MetaProperty(node) { + this.print(node.meta, node); + this.token("."); + this.print(node.property, node); +} - if (format.minified) { - format.compact = true; +function PrivateName(node) { + this.token("#"); + this.print(node.id, node); +} - format.shouldPrintComment = format.shouldPrintComment || function () { - return format.comments; - }; - } else { - format.shouldPrintComment = format.shouldPrintComment || function (value) { - return format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0; - }; - } +function V8IntrinsicIdentifier(node) { + this.token("%"); + this.word(node.name); +} - if (format.compact === "auto") { - format.compact = code.length > 500000; +},{"../node":52,"@babel/types":242}],42:[function(require,module,exports){ +"use strict"; - if (format.compact) { - console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "500KB")); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AnyTypeAnnotation = AnyTypeAnnotation; +exports.ArrayTypeAnnotation = ArrayTypeAnnotation; +exports.BooleanTypeAnnotation = BooleanTypeAnnotation; +exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; +exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; +exports.DeclareClass = DeclareClass; +exports.DeclareFunction = DeclareFunction; +exports.InferredPredicate = InferredPredicate; +exports.DeclaredPredicate = DeclaredPredicate; +exports.DeclareInterface = DeclareInterface; +exports.DeclareModule = DeclareModule; +exports.DeclareModuleExports = DeclareModuleExports; +exports.DeclareTypeAlias = DeclareTypeAlias; +exports.DeclareOpaqueType = DeclareOpaqueType; +exports.DeclareVariable = DeclareVariable; +exports.DeclareExportDeclaration = DeclareExportDeclaration; +exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration; +exports.EnumDeclaration = EnumDeclaration; +exports.EnumBooleanBody = EnumBooleanBody; +exports.EnumNumberBody = EnumNumberBody; +exports.EnumStringBody = EnumStringBody; +exports.EnumSymbolBody = EnumSymbolBody; +exports.EnumDefaultedMember = EnumDefaultedMember; +exports.EnumBooleanMember = EnumBooleanMember; +exports.EnumNumberMember = EnumNumberMember; +exports.EnumStringMember = EnumStringMember; +exports.ExistsTypeAnnotation = ExistsTypeAnnotation; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.FunctionTypeParam = FunctionTypeParam; +exports.GenericTypeAnnotation = exports.ClassImplements = exports.InterfaceExtends = InterfaceExtends; +exports._interfaceish = _interfaceish; +exports._variance = _variance; +exports.InterfaceDeclaration = InterfaceDeclaration; +exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation; +exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; +exports.MixedTypeAnnotation = MixedTypeAnnotation; +exports.EmptyTypeAnnotation = EmptyTypeAnnotation; +exports.NullableTypeAnnotation = NullableTypeAnnotation; +exports.NumberTypeAnnotation = NumberTypeAnnotation; +exports.StringTypeAnnotation = StringTypeAnnotation; +exports.ThisTypeAnnotation = ThisTypeAnnotation; +exports.TupleTypeAnnotation = TupleTypeAnnotation; +exports.TypeofTypeAnnotation = TypeofTypeAnnotation; +exports.TypeAlias = TypeAlias; +exports.TypeAnnotation = TypeAnnotation; +exports.TypeParameterDeclaration = exports.TypeParameterInstantiation = TypeParameterInstantiation; +exports.TypeParameter = TypeParameter; +exports.OpaqueType = OpaqueType; +exports.ObjectTypeAnnotation = ObjectTypeAnnotation; +exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot; +exports.ObjectTypeCallProperty = ObjectTypeCallProperty; +exports.ObjectTypeIndexer = ObjectTypeIndexer; +exports.ObjectTypeProperty = ObjectTypeProperty; +exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; +exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; +exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.TypeCastExpression = TypeCastExpression; +exports.Variance = Variance; +exports.VoidTypeAnnotation = VoidTypeAnnotation; +Object.defineProperty(exports, "NumberLiteralTypeAnnotation", { + enumerable: true, + get: function get() { + return _types2.NumericLiteral; } - - if (format.compact) { - format.indent.adjustMultilineComment = false; +}); +Object.defineProperty(exports, "StringLiteralTypeAnnotation", { + enumerable: true, + get: function get() { + return _types2.StringLiteral; } +}); - return format; -} - -function findCommonStringDelimiter(code, tokens) { - var DEFAULT_STRING_DELIMITER = "double"; - if (!code) { - return DEFAULT_STRING_DELIMITER; - } +var t = _interopRequireWildcard(require("@babel/types")); - var occurrences = { - single: 0, - double: 0 - }; +var _modules = require("./modules"); - var checked = 0; +var _types2 = require("./types"); - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - if (token.type.label !== "string") continue; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - var raw = code.slice(token.start, token.end); - if (raw[0] === "'") { - occurrences.single++; - } else { - occurrences.double++; - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - checked++; - if (checked >= 3) break; - } - if (occurrences.single > occurrences.double) { - return "single"; - } else { - return "double"; - } + return cache; } -var CodeGenerator = exports.CodeGenerator = function () { - function CodeGenerator(ast, opts, code) { - (0, _classCallCheck3.default)(this, CodeGenerator); - - this._generator = new Generator(ast, opts, code); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; } - CodeGenerator.prototype.generate = function generate() { - return this._generator.generate(); - }; - - return CodeGenerator; -}(); -},{"./printer":48,"./source-map":49,"babel-messages":61,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112,"detect-indent":282}],45:[function(require,module,exports){ -"use strict"; + var cache = _getRequireWildcardCache(); -exports.__esModule = true; + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + var newObj = {}; -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -var _keys = require("babel-runtime/core-js/object/keys"); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -var _keys2 = _interopRequireDefault(_keys); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } -exports.needsWhitespace = needsWhitespace; -exports.needsWhitespaceBefore = needsWhitespaceBefore; -exports.needsWhitespaceAfter = needsWhitespaceAfter; -exports.needsParens = needsParens; + newObj.default = obj; -var _whitespace = require("./whitespace"); + if (cache) { + cache.set(obj, newObj); + } -var _whitespace2 = _interopRequireDefault(_whitespace); + return newObj; +} -var _parentheses = require("./parentheses"); +function AnyTypeAnnotation() { + this.word("any"); +} -var parens = _interopRequireWildcard(_parentheses); +function ArrayTypeAnnotation(node) { + this.print(node.elementType, node); + this.token("["); + this.token("]"); +} -var _babelTypes = require("babel-types"); +function BooleanTypeAnnotation() { + this.word("boolean"); +} -var t = _interopRequireWildcard(_babelTypes); +function BooleanLiteralTypeAnnotation(node) { + this.word(node.value ? "true" : "false"); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function NullLiteralTypeAnnotation() { + this.word("null"); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function DeclareClass(node, parent) { + if (!t.isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } -function expandAliases(obj) { - var newObj = {}; + this.word("class"); + this.space(); - function add(type, func) { - var fn = newObj[type]; - newObj[type] = fn ? function (node, parent, stack) { - var result = fn(node, parent, stack); + this._interfaceish(node); +} - return result == null ? func(node, parent, stack) : result; - } : func; +function DeclareFunction(node, parent) { + if (!t.isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); } - for (var _iterator = (0, _keys2.default)(obj), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + this.word("function"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation.typeAnnotation, node); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (node.predicate) { + this.space(); + this.print(node.predicate, node); + } - var type = _ref; + this.semicolon(); +} +function InferredPredicate() { + this.token("%"); + this.word("checks"); +} - var aliases = t.FLIPPED_ALIAS_KEYS[type]; - if (aliases) { - for (var _iterator2 = aliases, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; +function DeclaredPredicate(node) { + this.token("%"); + this.word("checks"); + this.token("("); + this.print(node.value, node); + this.token(")"); +} - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +function DeclareInterface(node) { + this.word("declare"); + this.space(); + this.InterfaceDeclaration(node); +} - var alias = _ref2; +function DeclareModule(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.space(); + this.print(node.id, node); + this.space(); + this.print(node.body, node); +} - add(alias, obj[type]); - } - } else { - add(type, obj[type]); - } - } +function DeclareModuleExports(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.token("."); + this.word("exports"); + this.print(node.typeAnnotation, node); +} - return newObj; +function DeclareTypeAlias(node) { + this.word("declare"); + this.space(); + this.TypeAlias(node); } -var expandedParens = expandAliases(parens); -var expandedWhitespaceNodes = expandAliases(_whitespace2.default.nodes); -var expandedWhitespaceList = expandAliases(_whitespace2.default.list); +function DeclareOpaqueType(node, parent) { + if (!t.isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } -function find(obj, node, parent, printStack) { - var fn = obj[node.type]; - return fn ? fn(node, parent, printStack) : null; + this.OpaqueType(node); } -function isOrHasCallExpression(node) { - if (t.isCallExpression(node)) { - return true; +function DeclareVariable(node, parent) { + if (!t.isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); } - if (t.isMemberExpression(node)) { - return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property); - } else { - return false; - } + this.word("var"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation, node); + this.semicolon(); } -function needsWhitespace(node, parent, type) { - if (!node) return 0; +function DeclareExportDeclaration(node) { + this.word("declare"); + this.space(); + this.word("export"); + this.space(); - if (t.isExpressionStatement(node)) { - node = node.expression; + if (node.default) { + this.word("default"); + this.space(); } - var linesInfo = find(expandedWhitespaceNodes, node, parent); + FlowExportDeclaration.apply(this, arguments); +} - if (!linesInfo) { - var items = find(expandedWhitespaceList, node, parent); - if (items) { - for (var i = 0; i < items.length; i++) { - linesInfo = needsWhitespace(items[i], node, type); - if (linesInfo) break; - } - } - } +function DeclareExportAllDeclaration() { + this.word("declare"); + this.space(); - return linesInfo && linesInfo[type] || 0; + _modules.ExportAllDeclaration.apply(this, arguments); } -function needsWhitespaceBefore(node, parent) { - return needsWhitespace(node, parent, "before"); +function EnumDeclaration(node) { + var id = node.id, + body = node.body; + this.word("enum"); + this.space(); + this.print(id, node); + this.print(body, node); } -function needsWhitespaceAfter(node, parent) { - return needsWhitespace(node, parent, "after"); +function enumExplicitType(context, name, hasExplicitType) { + if (hasExplicitType) { + context.space(); + context.word("of"); + context.space(); + context.word(name); + } + + context.space(); } -function needsParens(node, parent, printStack) { - if (!parent) return false; +function enumBody(context, node) { + var members = node.members; + context.token("{"); + context.indent(); + context.newline(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (t.isNewExpression(parent) && parent.callee === node) { - if (isOrHasCallExpression(node)) return true; + try { + for (var _iterator = members[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var member = _step.value; + context.print(member, node); + context.newline(); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } } - return find(expandedParens, node, parent, printStack); + context.dedent(); + context.token("}"); } -},{"./parentheses":46,"./whitespace":47,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/keys":102,"babel-types":151}],46:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.AwaitExpression = exports.FunctionTypeAnnotation = undefined; -exports.NullableTypeAnnotation = NullableTypeAnnotation; -exports.UpdateExpression = UpdateExpression; -exports.ObjectExpression = ObjectExpression; -exports.DoExpression = DoExpression; -exports.Binary = Binary; -exports.BinaryExpression = BinaryExpression; -exports.SequenceExpression = SequenceExpression; -exports.YieldExpression = YieldExpression; -exports.ClassExpression = ClassExpression; -exports.UnaryLike = UnaryLike; -exports.FunctionExpression = FunctionExpression; -exports.ArrowFunctionExpression = ArrowFunctionExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.AssignmentExpression = AssignmentExpression; +function EnumBooleanBody(node) { + var explicitType = node.explicitType; + enumExplicitType(this, "boolean", explicitType); + enumBody(this, node); +} -var _babelTypes = require("babel-types"); +function EnumNumberBody(node) { + var explicitType = node.explicitType; + enumExplicitType(this, "number", explicitType); + enumBody(this, node); +} -var t = _interopRequireWildcard(_babelTypes); +function EnumStringBody(node) { + var explicitType = node.explicitType; + enumExplicitType(this, "string", explicitType); + enumBody(this, node); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function EnumSymbolBody(node) { + enumExplicitType(this, "symbol", true); + enumBody(this, node); +} -var PRECEDENCE = { - "||": 0, - "&&": 1, - "|": 2, - "^": 3, - "&": 4, - "==": 5, - "===": 5, - "!=": 5, - "!==": 5, - "<": 6, - ">": 6, - "<=": 6, - ">=": 6, - in: 6, - instanceof: 6, - ">>": 7, - "<<": 7, - ">>>": 7, - "+": 8, - "-": 8, - "*": 9, - "/": 9, - "%": 9, - "**": 10 -}; +function EnumDefaultedMember(node) { + var id = node.id; + this.print(id, node); + this.token(","); +} -function NullableTypeAnnotation(node, parent) { - return t.isArrayTypeAnnotation(parent); +function enumInitializedMember(context, node) { + var id = node.id, + init = node.init; + context.print(id, node); + context.space(); + context.token("="); + context.space(); + context.print(init, node); + context.token(","); } -exports.FunctionTypeAnnotation = NullableTypeAnnotation; -function UpdateExpression(node, parent) { - return t.isMemberExpression(parent) && parent.object === node; +function EnumBooleanMember(node) { + enumInitializedMember(this, node); } -function ObjectExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerArrow: true }); +function EnumNumberMember(node) { + enumInitializedMember(this, node); } -function DoExpression(node, parent, printStack) { - return isFirstInStatement(printStack); +function EnumStringMember(node) { + enumInitializedMember(this, node); } -function Binary(node, parent) { - if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node || t.isUnaryLike(parent) || t.isMemberExpression(parent) && parent.object === node || t.isAwaitExpression(parent)) { - return true; - } +function FlowExportDeclaration(node) { + if (node.declaration) { + var declar = node.declaration; + this.print(declar, node); + if (!t.isStatement(declar)) this.semicolon(); + } else { + this.token("{"); - if (t.isBinary(parent)) { - var parentOp = parent.operator; - var parentPos = PRECEDENCE[parentOp]; + if (node.specifiers.length) { + this.space(); + this.printList(node.specifiers, node); + this.space(); + } - var nodeOp = node.operator; - var nodePos = PRECEDENCE[nodeOp]; + this.token("}"); - if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent) || parentPos > nodePos) { - return true; + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); } - } - return false; + this.semicolon(); + } } -function BinaryExpression(node, parent) { - return node.operator === "in" && (t.isVariableDeclarator(parent) || t.isFor(parent)); +function ExistsTypeAnnotation() { + this.token("*"); } -function SequenceExpression(node, parent) { +function FunctionTypeAnnotation(node, parent) { + this.print(node.typeParameters, node); + this.token("("); + this.printList(node.params, node); - if (t.isForStatement(parent) || t.isThrowStatement(parent) || t.isReturnStatement(parent) || t.isIfStatement(parent) && parent.test === node || t.isWhileStatement(parent) && parent.test === node || t.isForInStatement(parent) && parent.right === node || t.isSwitchStatement(parent) && parent.discriminant === node || t.isExpressionStatement(parent) && parent.expression === node) { - return false; + if (node.rest) { + if (node.params.length) { + this.token(","); + this.space(); + } + + this.token("..."); + this.print(node.rest, node); } - return true; -} + this.token(")"); -function YieldExpression(node, parent) { - return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent) || t.isConditionalExpression(parent) && node === parent.test; -} + if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction" || parent.type === "ObjectTypeProperty" && parent.method) { + this.token(":"); + } else { + this.space(); + this.token("=>"); + } -exports.AwaitExpression = YieldExpression; -function ClassExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerDefaultExports: true }); + this.space(); + this.print(node.returnType, node); } -function UnaryLike(node, parent) { - return t.isMemberExpression(parent, { object: node }) || t.isCallExpression(parent, { callee: node }) || t.isNewExpression(parent, { callee: node }); +function FunctionTypeParam(node) { + this.print(node.name, node); + if (node.optional) this.token("?"); + + if (node.name) { + this.token(":"); + this.space(); + } + + this.print(node.typeAnnotation, node); } -function FunctionExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerDefaultExports: true }); +function InterfaceExtends(node) { + this.print(node.id, node); + this.print(node.typeParameters, node); } -function ArrowFunctionExpression(node, parent) { - if (t.isExportDeclaration(parent) || t.isBinaryExpression(parent) || t.isLogicalExpression(parent) || t.isUnaryExpression(parent) || t.isTaggedTemplateExpression(parent)) { - return true; +function _interfaceish(node) { + this.print(node.id, node); + this.print(node.typeParameters, node); + + if (node.extends.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends, node); } - return UnaryLike(node, parent); -} + if (node.mixins && node.mixins.length) { + this.space(); + this.word("mixins"); + this.space(); + this.printList(node.mixins, node); + } -function ConditionalExpression(node, parent) { - if (t.isUnaryLike(parent) || t.isBinary(parent) || t.isConditionalExpression(parent, { test: node }) || t.isAwaitExpression(parent)) { - return true; + if (node.implements && node.implements.length) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); } - return UnaryLike(node, parent); + this.space(); + this.print(node.body, node); } -function AssignmentExpression(node) { - if (t.isObjectPattern(node.left)) { - return true; - } else { - return ConditionalExpression.apply(undefined, arguments); +function _variance(node) { + if (node.variance) { + if (node.variance.kind === "plus") { + this.token("+"); + } else if (node.variance.kind === "minus") { + this.token("-"); + } } } -function isFirstInStatement(printStack) { - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$considerArrow = _ref.considerArrow, - considerArrow = _ref$considerArrow === undefined ? false : _ref$considerArrow, - _ref$considerDefaultE = _ref.considerDefaultExports, - considerDefaultExports = _ref$considerDefaultE === undefined ? false : _ref$considerDefaultE; +function InterfaceDeclaration(node) { + this.word("interface"); + this.space(); - var i = printStack.length - 1; - var node = printStack[i]; - i--; - var parent = printStack[i]; - while (i > 0) { - if (t.isExpressionStatement(parent, { expression: node }) || t.isTaggedTemplateExpression(parent) || considerDefaultExports && t.isExportDefaultDeclaration(parent, { declaration: node }) || considerArrow && t.isArrowFunctionExpression(parent, { body: node })) { - return true; - } + this._interfaceish(node); +} - if (t.isCallExpression(parent, { callee: node }) || t.isSequenceExpression(parent) && parent.expressions[0] === node || t.isMemberExpression(parent, { object: node }) || t.isConditional(parent, { test: node }) || t.isBinary(parent, { left: node }) || t.isAssignmentExpression(parent, { left: node })) { - node = parent; - i--; - parent = printStack[i]; - } else { - return false; - } +function andSeparator() { + this.space(); + this.token("&"); + this.space(); +} + +function InterfaceTypeAnnotation(node) { + this.word("interface"); + + if (node.extends && node.extends.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends, node); } - return false; + this.space(); + this.print(node.body, node); } -},{"babel-types":151}],47:[function(require,module,exports){ -"use strict"; -var _map = require("lodash/map"); - -var _map2 = _interopRequireDefault(_map); +function IntersectionTypeAnnotation(node) { + this.printJoin(node.types, node, { + separator: andSeparator + }); +} -var _babelTypes = require("babel-types"); +function MixedTypeAnnotation() { + this.word("mixed"); +} -var t = _interopRequireWildcard(_babelTypes); +function EmptyTypeAnnotation() { + this.word("empty"); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function NullableTypeAnnotation(node) { + this.token("?"); + this.print(node.typeAnnotation, node); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function NumberTypeAnnotation() { + this.word("number"); +} -function crawl(node) { - var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +function StringTypeAnnotation() { + this.word("string"); +} - if (t.isMemberExpression(node)) { - crawl(node.object, state); - if (node.computed) crawl(node.property, state); - } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { - crawl(node.left, state); - crawl(node.right, state); - } else if (t.isCallExpression(node)) { - state.hasCall = true; - crawl(node.callee, state); - } else if (t.isFunction(node)) { - state.hasFunction = true; - } else if (t.isIdentifier(node)) { - state.hasHelper = state.hasHelper || isHelper(node.callee); - } +function ThisTypeAnnotation() { + this.word("this"); +} - return state; +function TupleTypeAnnotation(node) { + this.token("["); + this.printList(node.types, node); + this.token("]"); } -function isHelper(node) { - if (t.isMemberExpression(node)) { - return isHelper(node.object) || isHelper(node.property); - } else if (t.isIdentifier(node)) { - return node.name === "require" || node.name[0] === "_"; - } else if (t.isCallExpression(node)) { - return isHelper(node.callee); - } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { - return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); - } else { - return false; - } +function TypeofTypeAnnotation(node) { + this.word("typeof"); + this.space(); + this.print(node.argument, node); } -function isType(node) { - return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node); +function TypeAlias(node) { + this.word("type"); + this.space(); + this.print(node.id, node); + this.print(node.typeParameters, node); + this.space(); + this.token("="); + this.space(); + this.print(node.right, node); + this.semicolon(); } -exports.nodes = { - AssignmentExpression: function AssignmentExpression(node) { - var state = crawl(node.right); - if (state.hasCall && state.hasHelper || state.hasFunction) { - return { - before: state.hasFunction, - after: true - }; - } - }, - SwitchCase: function SwitchCase(node, parent) { - return { - before: node.consequent.length || parent.cases[0] === node - }; - }, - LogicalExpression: function LogicalExpression(node) { - if (t.isFunction(node.left) || t.isFunction(node.right)) { - return { - after: true - }; - } - }, - Literal: function Literal(node) { - if (node.value === "use strict") { - return { - after: true - }; - } - }, - CallExpression: function CallExpression(node) { - if (t.isFunction(node.callee) || isHelper(node)) { - return { - before: true, - after: true - }; - } - }, - VariableDeclaration: function VariableDeclaration(node) { - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; +function TypeAnnotation(node) { + this.token(":"); + this.space(); + if (node.optional) this.token("?"); + this.print(node.typeAnnotation, node); +} - var enabled = isHelper(declar.id) && !isType(declar.init); - if (!enabled) { - var state = crawl(declar.init); - enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; - } +function TypeParameterInstantiation(node) { + this.token("<"); + this.printList(node.params, node, {}); + this.token(">"); +} - if (enabled) { - return { - before: true, - after: true - }; - } - } - }, - IfStatement: function IfStatement(node) { - if (t.isBlockStatement(node.consequent)) { - return { - before: true, - after: true - }; - } - } -}; +function TypeParameter(node) { + this._variance(node); -exports.nodes.ObjectProperty = exports.nodes.ObjectTypeProperty = exports.nodes.ObjectMethod = exports.nodes.SpreadProperty = function (node, parent) { - if (parent.properties[0] === node) { - return { - before: true - }; + this.word(node.name); + + if (node.bound) { + this.print(node.bound, node); } -}; -exports.list = { - VariableDeclaration: function VariableDeclaration(node) { - return (0, _map2.default)(node.declarations, "init"); - }, - ArrayExpression: function ArrayExpression(node) { - return node.elements; - }, - ObjectExpression: function ObjectExpression(node) { - return node.properties; + if (node.default) { + this.space(); + this.token("="); + this.space(); + this.print(node.default, node); } -}; +} -[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function (_ref) { - var type = _ref[0], - amounts = _ref[1]; +function OpaqueType(node) { + this.word("opaque"); + this.space(); + this.word("type"); + this.space(); + this.print(node.id, node); + this.print(node.typeParameters, node); - if (typeof amounts === "boolean") { - amounts = { after: amounts, before: amounts }; + if (node.supertype) { + this.token(":"); + this.space(); + this.print(node.supertype, node); } - [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { - exports.nodes[type] = function () { - return amounts; - }; - }); -}); -},{"babel-types":151,"lodash/map":500}],48:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; + if (node.impltype) { + this.space(); + this.token("="); + this.space(); + this.print(node.impltype, node); + } + + this.semicolon(); +} + +function ObjectTypeAnnotation(node) { + var _this = this; -var _assign = require("babel-runtime/core-js/object/assign"); + if (node.exact) { + this.token("{|"); + } else { + this.token("{"); + } -var _assign2 = _interopRequireDefault(_assign); + var props = node.properties.concat(node.callProperties || [], node.indexers || [], node.internalSlots || []); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (props.length) { + this.space(); + this.printJoin(props, node, { + addNewlines: function addNewlines(leading) { + if (leading && !props[0]) return 1; + }, + indent: true, + statement: true, + iterator: function iterator() { + if (props.length !== 1 || node.inexact) { + _this.token(","); -var _getIterator3 = _interopRequireDefault(_getIterator2); + _this.space(); + } + } + }); + this.space(); + } -var _stringify = require("babel-runtime/core-js/json/stringify"); + if (node.inexact) { + this.indent(); + this.token("..."); -var _stringify2 = _interopRequireDefault(_stringify); + if (props.length) { + this.newline(); + } -var _weakSet = require("babel-runtime/core-js/weak-set"); + this.dedent(); + } -var _weakSet2 = _interopRequireDefault(_weakSet); + if (node.exact) { + this.token("|}"); + } else { + this.token("}"); + } +} -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +function ObjectTypeInternalSlot(node) { + if (node.static) { + this.word("static"); + this.space(); + } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + this.token("["); + this.token("["); + this.print(node.id, node); + this.token("]"); + this.token("]"); + if (node.optional) this.token("?"); -var _find = require("lodash/find"); + if (!node.method) { + this.token(":"); + this.space(); + } -var _find2 = _interopRequireDefault(_find); + this.print(node.value, node); +} -var _findLast = require("lodash/findLast"); +function ObjectTypeCallProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } -var _findLast2 = _interopRequireDefault(_findLast); + this.print(node.value, node); +} -var _isInteger = require("lodash/isInteger"); +function ObjectTypeIndexer(node) { + if (node.static) { + this.word("static"); + this.space(); + } -var _isInteger2 = _interopRequireDefault(_isInteger); + this._variance(node); -var _repeat = require("lodash/repeat"); + this.token("["); -var _repeat2 = _interopRequireDefault(_repeat); + if (node.id) { + this.print(node.id, node); + this.token(":"); + this.space(); + } -var _buffer = require("./buffer"); + this.print(node.key, node); + this.token("]"); + this.token(":"); + this.space(); + this.print(node.value, node); +} -var _buffer2 = _interopRequireDefault(_buffer); +function ObjectTypeProperty(node) { + if (node.proto) { + this.word("proto"); + this.space(); + } -var _node = require("./node"); + if (node.static) { + this.word("static"); + this.space(); + } -var n = _interopRequireWildcard(_node); + this._variance(node); -var _whitespace = require("./whitespace"); + this.print(node.key, node); + if (node.optional) this.token("?"); -var _whitespace2 = _interopRequireDefault(_whitespace); + if (!node.method) { + this.token(":"); + this.space(); + } -var _babelTypes = require("babel-types"); + this.print(node.value, node); +} -var t = _interopRequireWildcard(_babelTypes); +function ObjectTypeSpreadProperty(node) { + this.token("..."); + this.print(node.argument, node); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function QualifiedTypeIdentifier(node) { + this.print(node.qualification, node); + this.token("."); + this.print(node.id, node); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function orSeparator() { + this.space(); + this.token("|"); + this.space(); +} -var SCIENTIFIC_NOTATION = /e/i; -var ZERO_DECIMAL_INTEGER = /\.0+$/; -var NON_DECIMAL_LITERAL = /^0[box]/; +function UnionTypeAnnotation(node) { + this.printJoin(node.types, node, { + separator: orSeparator + }); +} -var Printer = function () { - function Printer(format, map, tokens) { - (0, _classCallCheck3.default)(this, Printer); - this.inForStatementInitCounter = 0; - this._printStack = []; - this._indent = 0; - this._insideAux = false; - this._printedCommentStarts = {}; - this._parenPushNewlineState = null; - this._printAuxAfterOnNextUserNode = false; - this._printedComments = new _weakSet2.default(); - this._endsWithInteger = false; - this._endsWithWord = false; +function TypeCastExpression(node) { + this.token("("); + this.print(node.expression, node); + this.print(node.typeAnnotation, node); + this.token(")"); +} - this.format = format || {}; - this._buf = new _buffer2.default(map); - this._whitespace = tokens.length > 0 ? new _whitespace2.default(tokens) : null; +function Variance(node) { + if (node.kind === "plus") { + this.token("+"); + } else { + this.token("-"); } +} - Printer.prototype.generate = function generate(ast) { - this.print(ast); - this._maybeAddAuxComment(); +function VoidTypeAnnotation() { + this.word("void"); +} - return this._buf.get(); - }; +},{"./modules":46,"./types":49,"@babel/types":242}],43:[function(require,module,exports){ +"use strict"; - Printer.prototype.indent = function indent() { - if (this.format.compact || this.format.concise) return; +Object.defineProperty(exports, "__esModule", { + value: true +}); - this._indent++; - }; +var _templateLiterals = require("./template-literals"); - Printer.prototype.dedent = function dedent() { - if (this.format.compact || this.format.concise) return; +Object.keys(_templateLiterals).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _templateLiterals[key]; + } + }); +}); - this._indent--; - }; +var _expressions = require("./expressions"); - Printer.prototype.semicolon = function semicolon() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; +Object.keys(_expressions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _expressions[key]; + } + }); +}); - this._maybeAddAuxComment(); - this._append(";", !force); - }; +var _statements = require("./statements"); - Printer.prototype.rightBrace = function rightBrace() { - if (this.format.minified) { - this._buf.removeLastSemicolon(); +Object.keys(_statements).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _statements[key]; } - this.token("}"); - }; - - Printer.prototype.space = function space() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + }); +}); - if (this.format.compact) return; +var _classes = require("./classes"); - if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) { - this._space(); +Object.keys(_classes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _classes[key]; } - }; + }); +}); - Printer.prototype.word = function word(str) { - if (this._endsWithWord) this._space(); +var _methods = require("./methods"); - this._maybeAddAuxComment(); - this._append(str); +Object.keys(_methods).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _methods[key]; + } + }); +}); - this._endsWithWord = true; - }; +var _modules = require("./modules"); - Printer.prototype.number = function number(str) { - this.word(str); +Object.keys(_modules).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _modules[key]; + } + }); +}); - this._endsWithInteger = (0, _isInteger2.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; - }; +var _types = require("./types"); - Printer.prototype.token = function token(str) { - if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) { - this._space(); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _types[key]; } + }); +}); - this._maybeAddAuxComment(); - this._append(str); - }; - - Printer.prototype.newline = function newline(i) { - if (this.format.retainLines || this.format.compact) return; +var _flow = require("./flow"); - if (this.format.concise) { - this.space(); - return; +Object.keys(_flow).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _flow[key]; } + }); +}); - if (this.endsWith("\n\n")) return; +var _base = require("./base"); - if (typeof i !== "number") i = 1; +Object.keys(_base).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _base[key]; + } + }); +}); - i = Math.min(2, i); - if (this.endsWith("{\n") || this.endsWith(":\n")) i--; - if (i <= 0) return; +var _jsx = require("./jsx"); - for (var j = 0; j < i; j++) { - this._newline(); +Object.keys(_jsx).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _jsx[key]; } - }; + }); +}); - Printer.prototype.endsWith = function endsWith(str) { - return this._buf.endsWith(str); - }; +var _typescript = require("./typescript"); - Printer.prototype.removeTrailingNewline = function removeTrailingNewline() { - this._buf.removeTrailingNewline(); - }; +Object.keys(_typescript).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _typescript[key]; + } + }); +}); - Printer.prototype.source = function source(prop, loc) { - this._catchUp(prop, loc); +},{"./base":39,"./classes":40,"./expressions":41,"./flow":42,"./jsx":44,"./methods":45,"./modules":46,"./statements":47,"./template-literals":48,"./types":49,"./typescript":50}],44:[function(require,module,exports){ +"use strict"; - this._buf.source(prop, loc); - }; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.JSXAttribute = JSXAttribute; +exports.JSXIdentifier = JSXIdentifier; +exports.JSXNamespacedName = JSXNamespacedName; +exports.JSXMemberExpression = JSXMemberExpression; +exports.JSXSpreadAttribute = JSXSpreadAttribute; +exports.JSXExpressionContainer = JSXExpressionContainer; +exports.JSXSpreadChild = JSXSpreadChild; +exports.JSXText = JSXText; +exports.JSXElement = JSXElement; +exports.JSXOpeningElement = JSXOpeningElement; +exports.JSXClosingElement = JSXClosingElement; +exports.JSXEmptyExpression = JSXEmptyExpression; +exports.JSXFragment = JSXFragment; +exports.JSXOpeningFragment = JSXOpeningFragment; +exports.JSXClosingFragment = JSXClosingFragment; - Printer.prototype.withSource = function withSource(prop, loc, cb) { - this._catchUp(prop, loc); +function JSXAttribute(node) { + this.print(node.name, node); - this._buf.withSource(prop, loc, cb); - }; + if (node.value) { + this.token("="); + this.print(node.value, node); + } +} - Printer.prototype._space = function _space() { - this._append(" ", true); - }; +function JSXIdentifier(node) { + this.word(node.name); +} - Printer.prototype._newline = function _newline() { - this._append("\n", true); - }; +function JSXNamespacedName(node) { + this.print(node.namespace, node); + this.token(":"); + this.print(node.name, node); +} - Printer.prototype._append = function _append(str) { - var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; +function JSXMemberExpression(node) { + this.print(node.object, node); + this.token("."); + this.print(node.property, node); +} - this._maybeAddParen(str); - this._maybeIndent(str); +function JSXSpreadAttribute(node) { + this.token("{"); + this.token("..."); + this.print(node.argument, node); + this.token("}"); +} - if (queue) this._buf.queue(str);else this._buf.append(str); +function JSXExpressionContainer(node) { + this.token("{"); + this.print(node.expression, node); + this.token("}"); +} - this._endsWithWord = false; - this._endsWithInteger = false; - }; +function JSXSpreadChild(node) { + this.token("{"); + this.token("..."); + this.print(node.expression, node); + this.token("}"); +} - Printer.prototype._maybeIndent = function _maybeIndent(str) { - if (this._indent && this.endsWith("\n") && str[0] !== "\n") { - this._buf.queue(this._getIndent()); - } - }; +function JSXText(node) { + var raw = this.getPossibleRaw(node); - Printer.prototype._maybeAddParen = function _maybeAddParen(str) { - var parenPushNewlineState = this._parenPushNewlineState; - if (!parenPushNewlineState) return; - this._parenPushNewlineState = null; + if (raw != null) { + this.token(raw); + } else { + this.token(node.value); + } +} - var i = void 0; - for (i = 0; i < str.length && str[i] === " "; i++) { - continue; - }if (i === str.length) return; +function JSXElement(node) { + var open = node.openingElement; + this.print(open, node); + if (open.selfClosing) return; + this.indent(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - var cha = str[i]; - if (cha === "\n" || cha === "/") { - this.token("("); - this.indent(); - parenPushNewlineState.printed = true; + try { + for (var _iterator = node.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var child = _step.value; + this.print(child, node); } - }; + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } - Printer.prototype._catchUp = function _catchUp(prop, loc) { - if (!this.format.retainLines) return; + this.dedent(); + this.print(node.closingElement, node); +} - var pos = loc ? loc[prop] : null; - if (pos && pos.line !== null) { - var count = pos.line - this._buf.getCurrentLine(); +function spaceSeparator() { + this.space(); +} - for (var i = 0; i < count; i++) { - this._newline(); - } - } - }; +function JSXOpeningElement(node) { + this.token("<"); + this.print(node.name, node); + this.print(node.typeParameters, node); - Printer.prototype._getIndent = function _getIndent() { - return (0, _repeat2.default)(this.format.indent.style, this._indent); - }; + if (node.attributes.length > 0) { + this.space(); + this.printJoin(node.attributes, node, { + separator: spaceSeparator + }); + } - Printer.prototype.startTerminatorless = function startTerminatorless() { - return this._parenPushNewlineState = { - printed: false - }; - }; + if (node.selfClosing) { + this.space(); + this.token("/>"); + } else { + this.token(">"); + } +} - Printer.prototype.endTerminatorless = function endTerminatorless(state) { - if (state.printed) { - this.dedent(); - this.newline(); - this.token(")"); - } - }; +function JSXClosingElement(node) { + this.token(""); +} - Printer.prototype.print = function print(node, parent) { - var _this = this; +function JSXEmptyExpression(node) { + this.printInnerComments(node); +} - if (!node) return; +function JSXFragment(node) { + this.print(node.openingFragment, node); + this.indent(); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - var oldConcise = this.format.concise; - if (node._compact) { - this.format.concise = true; + try { + for (var _iterator2 = node.children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var child = _step2.value; + this.print(child, node); } - - var printMethod = this[node.type]; - if (!printMethod) { - throw new ReferenceError("unknown node of type " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name)); + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } } + } - this._printStack.push(node); - - var oldInAux = this._insideAux; - this._insideAux = !node.loc; - this._maybeAddAuxComment(this._insideAux && !oldInAux); + this.dedent(); + this.print(node.closingFragment, node); +} - var needsParens = n.needsParens(node, parent, this._printStack); - if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) { - needsParens = true; - } - if (needsParens) this.token("("); +function JSXOpeningFragment() { + this.token("<"); + this.token(">"); +} - this._printLeadingComments(node, parent); +function JSXClosingFragment() { + this.token(""); +} - var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; - this.withSource("start", loc, function () { - _this[node.type](node, parent); - }); +},{}],45:[function(require,module,exports){ +"use strict"; - this._printTrailingComments(node, parent); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports._params = _params; +exports._parameters = _parameters; +exports._param = _param; +exports._methodHead = _methodHead; +exports._predicate = _predicate; +exports._functionHead = _functionHead; +exports.FunctionDeclaration = exports.FunctionExpression = FunctionExpression; +exports.ArrowFunctionExpression = ArrowFunctionExpression; - if (needsParens) this.token(")"); +var t = _interopRequireWildcard(require("@babel/types")); - this._printStack.pop(); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - this.format.concise = oldConcise; - this._insideAux = oldInAux; + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; - Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) { - if (enteredPositionlessNode) this._printAuxBeforeComment(); - if (!this._insideAux) this._printAuxAfterComment(); - }; - - Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() { - if (this._printAuxAfterOnNextUserNode) return; - this._printAuxAfterOnNextUserNode = true; - - var comment = this.format.auxiliaryCommentBefore; - if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment - }); - } - }; - - Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() { - if (!this._printAuxAfterOnNextUserNode) return; - this._printAuxAfterOnNextUserNode = false; - - var comment = this.format.auxiliaryCommentAfter; - if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment - }); - } - }; - - Printer.prototype.getPossibleRaw = function getPossibleRaw(node) { - var extra = node.extra; - if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { - return extra.raw; - } - }; - - Printer.prototype.printJoin = function printJoin(nodes, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - if (!nodes || !nodes.length) return; + return cache; +} - if (opts.indent) this.indent(); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - var newlineOpts = { - addNewlines: opts.addNewlines - }; + var cache = _getRequireWildcardCache(); - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (!node) continue; + if (cache && cache.has(obj)) { + return cache.get(obj); + } - if (opts.statement) this._printNewline(true, node, parent, newlineOpts); + var newObj = {}; - this.print(node, parent); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (opts.iterator) { - opts.iterator(node, i); - } + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (opts.separator && i < nodes.length - 1) { - opts.separator.call(this); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } - - if (opts.statement) this._printNewline(false, node, parent, newlineOpts); - } - - if (opts.indent) this.dedent(); - }; - - Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) { - var indent = !!node.leadingComments; - if (indent) this.indent(); - this.print(node, parent); - if (indent) this.dedent(); - }; - - Printer.prototype.printBlock = function printBlock(parent) { - var node = parent.body; - - if (!t.isEmptyStatement(node)) { - this.space(); } + } - this.print(node, parent); - }; - - Printer.prototype._printTrailingComments = function _printTrailingComments(node, parent) { - this._printComments(this._getComments(false, node, parent)); - }; - - Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) { - this._printComments(this._getComments(true, node, parent)); - }; - - Printer.prototype.printInnerComments = function printInnerComments(node) { - var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - if (!node.innerComments) return; - if (indent) this.indent(); - this._printComments(node.innerComments); - if (indent) this.dedent(); - }; - - Printer.prototype.printSequence = function printSequence(nodes, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + newObj.default = obj; - opts.statement = true; - return this.printJoin(nodes, parent, opts); - }; + if (cache) { + cache.set(obj, newObj); + } - Printer.prototype.printList = function printList(items, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + return newObj; +} - if (opts.separator == null) { - opts.separator = commaSeparator; - } +function _params(node) { + this.print(node.typeParameters, node); + this.token("("); - return this.printJoin(items, parent, opts); - }; + this._parameters(node.params, node); - Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) { - var _this2 = this; + this.token(")"); + this.print(node.returnType, node); +} - if (this.format.retainLines || this.format.compact) return; +function _parameters(parameters, parent) { + for (var i = 0; i < parameters.length; i++) { + this._param(parameters[i], parent); - if (this.format.concise) { + if (i < parameters.length - 1) { + this.token(","); this.space(); - return; } + } +} - var lines = 0; - - if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) { - if (leading) { - var _comments = node.leadingComments; - var _comment = _comments && (0, _find2.default)(_comments, function (comment) { - return !!comment.loc && _this2.format.shouldPrintComment(comment.value); - }); +function _param(parameter, parent) { + this.printJoin(parameter.decorators, parameter); + this.print(parameter, parent); + if (parameter.optional) this.token("?"); + this.print(parameter.typeAnnotation, parameter); +} - lines = this._whitespace.getNewlinesBefore(_comment || node); - } else { - var _comments2 = node.trailingComments; - var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) { - return !!comment.loc && _this2.format.shouldPrintComment(comment.value); - }); +function _methodHead(node) { + var kind = node.kind; + var key = node.key; - lines = this._whitespace.getNewlinesAfter(_comment2 || node); - } - } else { - if (!leading) lines++; - if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; + if (kind === "get" || kind === "set") { + this.word(kind); + this.space(); + } - var needs = n.needsWhitespaceAfter; - if (leading) needs = n.needsWhitespaceBefore; - if (needs(node, parent)) lines++; + if (node.async) { + this.word("async"); + this.space(); + } - if (!this._buf.hasContent()) lines = 0; + if (kind === "method" || kind === "init") { + if (node.generator) { + this.token("*"); } + } - this.newline(lines); - }; + if (node.computed) { + this.token("["); + this.print(key, node); + this.token("]"); + } else { + this.print(key, node); + } - Printer.prototype._getComments = function _getComments(leading, node) { - return node && (leading ? node.leadingComments : node.trailingComments) || []; - }; + if (node.optional) { + this.token("?"); + } - Printer.prototype._printComment = function _printComment(comment) { - var _this3 = this; + this._params(node); +} - if (!this.format.shouldPrintComment(comment.value)) return; +function _predicate(node) { + if (node.predicate) { + if (!node.returnType) { + this.token(":"); + } - if (comment.ignore) return; + this.space(); + this.print(node.predicate, node); + } +} - if (this._printedComments.has(comment)) return; - this._printedComments.add(comment); +function _functionHead(node) { + if (node.async) { + this.word("async"); + this.space(); + } - if (comment.start != null) { - if (this._printedCommentStarts[comment.start]) return; - this._printedCommentStarts[comment.start] = true; - } + this.word("function"); + if (node.generator) this.token("*"); + this.space(); - this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0); + if (node.id) { + this.print(node.id, node); + } - if (!this.endsWith("[") && !this.endsWith("{")) this.space(); + this._params(node); - var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/"; + this._predicate(node); +} - if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) { - var offset = comment.loc && comment.loc.start.column; - if (offset) { - var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); - val = val.replace(newlineRegex, "\n"); - } +function FunctionExpression(node) { + this._functionHead(node); - var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); - val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize)); - } + this.space(); + this.print(node.body, node); +} - this.withSource("start", comment.loc, function () { - _this3._append(val); - }); +function ArrowFunctionExpression(node) { + if (node.async) { + this.word("async"); + this.space(); + } - this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0)); - }; + var firstParam = node.params[0]; - Printer.prototype._printComments = function _printComments(comments) { - if (!comments || !comments.length) return; + if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) { + if (this.format.retainLines && node.loc && node.body.loc && node.loc.start.line < node.body.loc.start.line) { + this.token("("); - for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (firstParam.loc && firstParam.loc.start.line > node.loc.start.line) { + this.indent(); + this.print(firstParam, node); + this.dedent(); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; + this._catchUp("start", node.body.loc); } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + this.print(firstParam, node); } - var _comment3 = _ref; - - this._printComment(_comment3); + this.token(")"); + } else { + this.print(firstParam, node); } - }; - - return Printer; -}(); - -exports.default = Printer; + } else { + this._params(node); + } + this._predicate(node); -function commaSeparator() { - this.token(","); this.space(); + this.token("=>"); + this.space(); + this.print(node.body, node); } -var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")]; -for (var _i2 = 0; _i2 < _arr.length; _i2++) { - var generator = _arr[_i2]; - (0, _assign2.default)(Printer.prototype, generator); +function hasTypes(node, param) { + return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; } -module.exports = exports["default"]; -},{"./buffer":33,"./generators/base":34,"./generators/classes":35,"./generators/expressions":36,"./generators/flow":37,"./generators/jsx":38,"./generators/methods":39,"./generators/modules":40,"./generators/statements":41,"./generators/template-literals":42,"./generators/types":43,"./node":45,"./whitespace":50,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/core-js/object/assign":99,"babel-runtime/core-js/weak-set":108,"babel-runtime/helpers/classCallCheck":109,"babel-types":151,"lodash/find":474,"lodash/findLast":476,"lodash/isInteger":489,"lodash/repeat":507}],49:[function(require,module,exports){ + +},{"@babel/types":242}],46:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ImportSpecifier = ImportSpecifier; +exports.ImportDefaultSpecifier = ImportDefaultSpecifier; +exports.ExportDefaultSpecifier = ExportDefaultSpecifier; +exports.ExportSpecifier = ExportSpecifier; +exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; +exports.ExportAllDeclaration = ExportAllDeclaration; +exports.ExportNamedDeclaration = ExportNamedDeclaration; +exports.ExportDefaultDeclaration = ExportDefaultDeclaration; +exports.ImportDeclaration = ImportDeclaration; +exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; -var _keys = require("babel-runtime/core-js/object/keys"); +var t = _interopRequireWildcard(require("@babel/types")); -var _keys2 = _interopRequireDefault(_keys); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -var _typeof2 = require("babel-runtime/helpers/typeof"); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; -var _typeof3 = _interopRequireDefault(_typeof2); + return cache; +} -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + var cache = _getRequireWildcardCache(); -var _sourceMap = require("source-map"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var _sourceMap2 = _interopRequireDefault(_sourceMap); + var newObj = {}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -var SourceMap = function () { - function SourceMap(opts, code) { - (0, _classCallCheck3.default)(this, SourceMap); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - this._cachedMap = null; - this._code = code; - this._opts = opts; - this._rawMappings = []; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } } - SourceMap.prototype.get = function get() { - if (!this._cachedMap) { - var map = this._cachedMap = new _sourceMap2.default.SourceMapGenerator({ - file: this._opts.sourceMapTarget, - sourceRoot: this._opts.sourceRoot - }); + newObj.default = obj; - var code = this._code; - if (typeof code === "string") { - map.setSourceContent(this._opts.sourceFileName, code); - } else if ((typeof code === "undefined" ? "undefined" : (0, _typeof3.default)(code)) === "object") { - (0, _keys2.default)(code).forEach(function (sourceFileName) { - map.setSourceContent(sourceFileName, code[sourceFileName]); - }); - } + if (cache) { + cache.set(obj, newObj); + } - this._rawMappings.forEach(map.addMapping, map); - } + return newObj; +} - return this._cachedMap.toJSON(); - }; +function ImportSpecifier(node) { + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } - SourceMap.prototype.getRawMappings = function getRawMappings() { - return this._rawMappings.slice(); - }; + this.print(node.imported, node); - SourceMap.prototype.mark = function mark(generatedLine, generatedColumn, line, column, identifierName, filename) { - if (this._lastGenLine !== generatedLine && line === null) return; + if (node.local && node.local.name !== node.imported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); + } +} - if (this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { - return; - } +function ImportDefaultSpecifier(node) { + this.print(node.local, node); +} - this._cachedMap = null; - this._lastGenLine = generatedLine; - this._lastSourceLine = line; - this._lastSourceColumn = column; +function ExportDefaultSpecifier(node) { + this.print(node.exported, node); +} - this._rawMappings.push({ - name: identifierName || undefined, - generated: { - line: generatedLine, - column: generatedColumn - }, - source: line == null ? undefined : filename || this._opts.sourceFileName, - original: line == null ? undefined : { - line: line, - column: column - } - }); - }; +function ExportSpecifier(node) { + this.print(node.local, node); - return SourceMap; -}(); + if (node.exported && node.local.name !== node.exported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); + } +} -exports.default = SourceMap; -module.exports = exports["default"]; -},{"babel-runtime/core-js/object/keys":102,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/typeof":113,"source-map":552}],50:[function(require,module,exports){ -"use strict"; +function ExportNamespaceSpecifier(node) { + this.token("*"); + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); +} -exports.__esModule = true; +function ExportAllDeclaration(node) { + this.word("export"); + this.space(); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + this.token("*"); + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.semicolon(); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function ExportNamedDeclaration(node) { + if (this.format.decoratorsBeforeExport && t.isClassDeclaration(node.declaration)) { + this.printJoin(node.declaration.decorators, node); + } -var Whitespace = function () { - function Whitespace(tokens) { - (0, _classCallCheck3.default)(this, Whitespace); + this.word("export"); + this.space(); + ExportDeclaration.apply(this, arguments); +} - this.tokens = tokens; - this.used = {}; +function ExportDefaultDeclaration(node) { + if (this.format.decoratorsBeforeExport && t.isClassDeclaration(node.declaration)) { + this.printJoin(node.declaration.decorators, node); } - Whitespace.prototype.getNewlinesBefore = function getNewlinesBefore(node) { - var startToken = void 0; - var endToken = void 0; - var tokens = this.tokens; + this.word("export"); + this.space(); + this.word("default"); + this.space(); + ExportDeclaration.apply(this, arguments); +} - var index = this._findToken(function (token) { - return token.start - node.start; - }, 0, tokens.length); - if (index >= 0) { - while (index && node.start === tokens[index - 1].start) { - --index; - }startToken = tokens[index - 1]; - endToken = tokens[index]; +function ExportDeclaration(node) { + if (node.declaration) { + var declar = node.declaration; + this.print(declar, node); + if (!t.isStatement(declar)) this.semicolon(); + } else { + if (node.exportKind === "type") { + this.word("type"); + this.space(); } - return this._getNewlinesBetween(startToken, endToken); - }; + var specifiers = node.specifiers.slice(0); + var hasSpecial = false; - Whitespace.prototype.getNewlinesAfter = function getNewlinesAfter(node) { - var startToken = void 0; - var endToken = void 0; - var tokens = this.tokens; + while (true) { + var first = specifiers[0]; - var index = this._findToken(function (token) { - return token.end - node.end; - }, 0, tokens.length); - if (index >= 0) { - while (index && node.end === tokens[index - 1].end) { - --index; - }startToken = tokens[index]; - endToken = tokens[index + 1]; - if (endToken.type.label === ",") endToken = tokens[index + 2]; - } + if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) { + hasSpecial = true; + this.print(specifiers.shift(), node); - if (endToken && endToken.type.label === "eof") { - return 1; - } else { - return this._getNewlinesBetween(startToken, endToken); + if (specifiers.length) { + this.token(","); + this.space(); + } + } else { + break; + } } - }; - Whitespace.prototype._getNewlinesBetween = function _getNewlinesBetween(startToken, endToken) { - if (!endToken || !endToken.loc) return 0; - - var start = startToken ? startToken.loc.end.line : 1; - var end = endToken.loc.start.line; - var lines = 0; + if (specifiers.length || !specifiers.length && !hasSpecial) { + this.token("{"); - for (var line = start; line < end; line++) { - if (typeof this.used[line] === "undefined") { - this.used[line] = true; - lines++; + if (specifiers.length) { + this.space(); + this.printList(specifiers, node); + this.space(); } - } - return lines; - }; - - Whitespace.prototype._findToken = function _findToken(test, start, end) { - if (start >= end) return -1; - var middle = start + end >>> 1; - var match = test(this.tokens[middle]); - if (match < 0) { - return this._findToken(test, middle + 1, end); - } else if (match > 0) { - return this._findToken(test, start, middle); - } else if (match === 0) { - return middle; + this.token("}"); } - return -1; - }; - - return Whitespace; -}(); - -exports.default = Whitespace; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109}],51:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = function (path) { - var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : path.scope; - var node = path.node; + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + } - var container = t.functionExpression(null, [], node.body, node.generator, node.async); + this.semicolon(); + } +} - var callee = container; - var args = []; +function ImportDeclaration(node) { + this.word("import"); + this.space(); - (0, _babelHelperHoistVariables2.default)(path, function (id) { - return scope.push({ id: id }); - }); + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } - var state = { - foundThis: false, - foundArguments: false - }; + var specifiers = node.specifiers.slice(0); - path.traverse(visitor, state); + if (specifiers && specifiers.length) { + while (true) { + var first = specifiers[0]; - if (state.foundArguments) { - callee = t.memberExpression(container, t.identifier("apply")); - args = []; + if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) { + this.print(specifiers.shift(), node); - if (state.foundThis) { - args.push(t.thisExpression()); + if (specifiers.length) { + this.token(","); + this.space(); + } + } else { + break; + } } - if (state.foundArguments) { - if (!state.foundThis) args.push(t.nullLiteral()); - args.push(t.identifier("arguments")); + if (specifiers.length) { + this.token("{"); + this.space(); + this.printList(specifiers, node); + this.space(); + this.token("}"); } - } - var call = t.callExpression(callee, args); - if (node.generator) call = t.yieldExpression(call, true); + this.space(); + this.word("from"); + this.space(); + } - return t.returnStatement(call); -}; + this.print(node.source, node); + this.semicolon(); +} -var _babelHelperHoistVariables = require("babel-helper-hoist-variables"); +function ImportNamespaceSpecifier(node) { + this.token("*"); + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); +} -var _babelHelperHoistVariables2 = _interopRequireDefault(_babelHelperHoistVariables); +},{"@babel/types":242}],47:[function(require,module,exports){ +"use strict"; -var _babelTypes = require("babel-types"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.WithStatement = WithStatement; +exports.IfStatement = IfStatement; +exports.ForStatement = ForStatement; +exports.WhileStatement = WhileStatement; +exports.DoWhileStatement = DoWhileStatement; +exports.LabeledStatement = LabeledStatement; +exports.TryStatement = TryStatement; +exports.CatchClause = CatchClause; +exports.SwitchStatement = SwitchStatement; +exports.SwitchCase = SwitchCase; +exports.DebuggerStatement = DebuggerStatement; +exports.VariableDeclaration = VariableDeclaration; +exports.VariableDeclarator = VariableDeclarator; +exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForOfStatement = exports.ForInStatement = void 0; -var t = _interopRequireWildcard(_babelTypes); +var t = _interopRequireWildcard(require("@babel/types")); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; -var visitor = { - enter: function enter(path, state) { - if (path.isThisExpression()) { - state.foundThis = true; - } + return cache; +} - if (path.isReferencedIdentifier({ name: "arguments" })) { - state.foundArguments = true; - } - }, - Function: function Function(path) { - path.skip(); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; } -}; - -module.exports = exports["default"]; -},{"babel-helper-hoist-variables":55,"babel-types":151}],52:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -exports.push = push; -exports.hasComputed = hasComputed; -exports.toComputedObjectFromClass = toComputedObjectFromClass; -exports.toClassObject = toClassObject; -exports.toDefineObject = toDefineObject; - -var _babelHelperFunctionName = require("babel-helper-function-name"); -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + var cache = _getRequireWildcardCache(); -var _has = require("lodash/has"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var _has2 = _interopRequireDefault(_has); + var newObj = {}; -var _babelTypes = require("babel-types"); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -var t = _interopRequireWildcard(_babelTypes); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + newObj.default = obj; -function toKind(node) { - if (t.isClassMethod(node) || t.isObjectMethod(node)) { - if (node.kind === "get" || node.kind === "set") { - return node.kind; - } + if (cache) { + cache.set(obj, newObj); } - return "value"; + return newObj; } -function push(mutatorMap, node, kind, file, scope) { - var alias = t.toKeyAlias(node); +function WithStatement(node) { + this.word("with"); + this.space(); + this.token("("); + this.print(node.object, node); + this.token(")"); + this.printBlock(node); +} - var map = {}; - if ((0, _has2.default)(mutatorMap, alias)) map = mutatorMap[alias]; - mutatorMap[alias] = map; +function IfStatement(node) { + this.word("if"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.space(); + var needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); - map._inherits = map._inherits || []; - map._inherits.push(node); + if (needsBlock) { + this.token("{"); + this.newline(); + this.indent(); + } - map._key = node.key; + this.printAndIndentOnComments(node.consequent, node); - if (node.computed) { - map._computed = true; + if (needsBlock) { + this.dedent(); + this.newline(); + this.token("}"); } - if (node.decorators) { - var decorators = map.decorators = map.decorators || t.arrayExpression([]); - decorators.elements = decorators.elements.concat(node.decorators.map(function (dec) { - return dec.expression; - }).reverse()); + if (node.alternate) { + if (this.endsWith("}")) this.space(); + this.word("else"); + this.space(); + this.printAndIndentOnComments(node.alternate, node); } +} - if (map.value || map.initializer) { - throw file.buildCodeFrameError(node, "Key conflict with sibling node"); - } +function getLastStatement(statement) { + if (!t.isStatement(statement.body)) return statement; + return getLastStatement(statement.body); +} - var key = void 0, - value = void 0; +function ForStatement(node) { + this.word("for"); + this.space(); + this.token("("); + this.inForStatementInitCounter++; + this.print(node.init, node); + this.inForStatementInitCounter--; + this.token(";"); - if (t.isObjectProperty(node) || t.isObjectMethod(node) || t.isClassMethod(node)) { - key = t.toComputedKey(node, node.key); + if (node.test) { + this.space(); + this.print(node.test, node); } - if (t.isObjectProperty(node) || t.isClassProperty(node)) { - value = node.value; - } else if (t.isObjectMethod(node) || t.isClassMethod(node)) { - value = t.functionExpression(null, node.params, node.body, node.generator, node.async); - value.returnType = node.returnType; - } + this.token(";"); - var inheritedKind = toKind(node); - if (!kind || inheritedKind !== "value") { - kind = inheritedKind; + if (node.update) { + this.space(); + this.print(node.update, node); } - if (scope && t.isStringLiteral(key) && (kind === "value" || kind === "initializer") && t.isFunctionExpression(value)) { - value = (0, _babelHelperFunctionName2.default)({ id: key, node: value, scope: scope }); - } - - if (value) { - t.inheritsComments(value, node); - map[kind] = value; - } + this.token(")"); + this.printBlock(node); +} - return map; +function WhileStatement(node) { + this.word("while"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.printBlock(node); } -function hasComputed(mutatorMap) { - for (var key in mutatorMap) { - if (mutatorMap[key]._computed) { - return true; +var buildForXStatement = function buildForXStatement(op) { + return function (node) { + this.word("for"); + this.space(); + + if (op === "of" && node.await) { + this.word("await"); + this.space(); } - } - return false; + + this.token("("); + this.print(node.left, node); + this.space(); + this.word(op); + this.space(); + this.print(node.right, node); + this.token(")"); + this.printBlock(node); + }; +}; + +var ForInStatement = buildForXStatement("in"); +exports.ForInStatement = ForInStatement; +var ForOfStatement = buildForXStatement("of"); +exports.ForOfStatement = ForOfStatement; + +function DoWhileStatement(node) { + this.word("do"); + this.space(); + this.print(node.body, node); + this.space(); + this.word("while"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.semicolon(); } -function toComputedObjectFromClass(obj) { - var objExpr = t.arrayExpression([]); +function buildLabelStatement(prefix) { + var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "label"; + return function (node) { + this.word(prefix); + var label = node[key]; - for (var i = 0; i < obj.properties.length; i++) { - var prop = obj.properties[i]; - var val = prop.value; - val.properties.unshift(t.objectProperty(t.identifier("key"), t.toComputedKey(prop))); - objExpr.elements.push(val); - } + if (label) { + this.space(); + var isLabel = key == "label"; + var terminatorState = this.startTerminatorless(isLabel); + this.print(label, node); + this.endTerminatorless(terminatorState); + } - return objExpr; + this.semicolon(); + }; } -function toClassObject(mutatorMap) { - var objExpr = t.objectExpression([]); +var ContinueStatement = buildLabelStatement("continue"); +exports.ContinueStatement = ContinueStatement; +var ReturnStatement = buildLabelStatement("return", "argument"); +exports.ReturnStatement = ReturnStatement; +var BreakStatement = buildLabelStatement("break"); +exports.BreakStatement = BreakStatement; +var ThrowStatement = buildLabelStatement("throw", "argument"); +exports.ThrowStatement = ThrowStatement; - (0, _keys2.default)(mutatorMap).forEach(function (mutatorMapKey) { - var map = mutatorMap[mutatorMapKey]; - var mapNode = t.objectExpression([]); +function LabeledStatement(node) { + this.print(node.label, node); + this.token(":"); + this.space(); + this.print(node.body, node); +} - var propNode = t.objectProperty(map._key, mapNode, map._computed); +function TryStatement(node) { + this.word("try"); + this.space(); + this.print(node.block, node); + this.space(); - (0, _keys2.default)(map).forEach(function (key) { - var node = map[key]; - if (key[0] === "_") return; + if (node.handlers) { + this.print(node.handlers[0], node); + } else { + this.print(node.handler, node); + } + + if (node.finalizer) { + this.space(); + this.word("finally"); + this.space(); + this.print(node.finalizer, node); + } +} - var inheritNode = node; - if (t.isClassMethod(node) || t.isClassProperty(node)) node = node.value; +function CatchClause(node) { + this.word("catch"); + this.space(); - var prop = t.objectProperty(t.identifier(key), node); - t.inheritsComments(prop, inheritNode); - t.removeComments(inheritNode); + if (node.param) { + this.token("("); + this.print(node.param, node); + this.token(")"); + this.space(); + } - mapNode.properties.push(prop); - }); + this.print(node.body, node); +} - objExpr.properties.push(propNode); +function SwitchStatement(node) { + this.word("switch"); + this.space(); + this.token("("); + this.print(node.discriminant, node); + this.token(")"); + this.space(); + this.token("{"); + this.printSequence(node.cases, node, { + indent: true, + addNewlines: function addNewlines(leading, cas) { + if (!leading && node.cases[node.cases.length - 1] === cas) return -1; + } }); + this.token("}"); +} - return objExpr; +function SwitchCase(node) { + if (node.test) { + this.word("case"); + this.space(); + this.print(node.test, node); + this.token(":"); + } else { + this.word("default"); + this.token(":"); + } + + if (node.consequent.length) { + this.newline(); + this.printSequence(node.consequent, node, { + indent: true + }); + } } -function toDefineObject(mutatorMap) { - (0, _keys2.default)(mutatorMap).forEach(function (key) { - var map = mutatorMap[key]; - if (map.value) map.writable = t.booleanLiteral(true); - map.configurable = t.booleanLiteral(true); - map.enumerable = t.booleanLiteral(true); - }); +function DebuggerStatement() { + this.word("debugger"); + this.semicolon(); +} - return toClassObject(mutatorMap); +function variableDeclarationIndent() { + this.token(","); + this.newline(); + if (this.endsWith("\n")) for (var i = 0; i < 4; i++) { + this.space(true); + } } -},{"babel-helper-function-name":53,"babel-runtime/core-js/object/keys":102,"babel-types":151,"lodash/has":479}],53:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; +function constDeclarationIndent() { + this.token(","); + this.newline(); + if (this.endsWith("\n")) for (var i = 0; i < 6; i++) { + this.space(true); + } +} -exports.default = function (_ref) { - var node = _ref.node, - parent = _ref.parent, - scope = _ref.scope, - id = _ref.id; +function VariableDeclaration(node, parent) { + if (node.declare) { + this.word("declare"); + this.space(); + } - if (node.id) return; + this.word(node.kind); + this.space(); + var hasInits = false; - if ((t.isObjectProperty(parent) || t.isObjectMethod(parent, { kind: "method" })) && (!parent.computed || t.isLiteral(parent.key))) { - id = parent.key; - } else if (t.isVariableDeclarator(parent)) { - id = parent.id; + if (!t.isFor(parent)) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (t.isIdentifier(id)) { - var binding = scope.parent.getBinding(id.name); - if (binding && binding.constant && scope.getBinding(id.name) === binding) { - node.id = id; - node.id[t.NOT_LOCAL_BINDING] = true; - return; + try { + for (var _iterator = node.declarations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var declar = _step.value; + + if (declar.init) { + hasInits = true; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } } - } else if (t.isAssignmentExpression(parent)) { - id = parent.left; - } else if (!id) { - return; } - var name = void 0; - if (id && t.isLiteral(id)) { - name = id.value; - } else if (id && t.isIdentifier(id)) { - name = id.name; - } else { - return; - } + var separator; - name = t.toBindingIdentifierName(name); - id = t.identifier(name); + if (hasInits) { + separator = node.kind === "const" ? constDeclarationIndent : variableDeclarationIndent; + } - id[t.NOT_LOCAL_BINDING] = true; + this.printList(node.declarations, node, { + separator: separator + }); - var state = visit(node, name, scope); - return wrap(state, node, id, scope) || node; -}; + if (t.isFor(parent)) { + if (parent.left === node || parent.init === node) return; + } -var _babelHelperGetFunctionArity = require("babel-helper-get-function-arity"); + this.semicolon(); +} -var _babelHelperGetFunctionArity2 = _interopRequireDefault(_babelHelperGetFunctionArity); +function VariableDeclarator(node) { + this.print(node.id, node); + if (node.definite) this.token("!"); + this.print(node.id.typeAnnotation, node); -var _babelTemplate = require("babel-template"); + if (node.init) { + this.space(); + this.token("="); + this.space(); + this.print(node.init, node); + } +} -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); +},{"@babel/types":242}],48:[function(require,module,exports){ +"use strict"; -var _babelTypes = require("babel-types"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TaggedTemplateExpression = TaggedTemplateExpression; +exports.TemplateElement = TemplateElement; +exports.TemplateLiteral = TemplateLiteral; -var t = _interopRequireWildcard(_babelTypes); +function TaggedTemplateExpression(node) { + this.print(node.tag, node); + this.print(node.typeParameters, node); + this.print(node.quasi, node); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function TemplateElement(node, parent) { + var isFirst = parent.quasis[0] === node; + var isLast = parent.quasis[parent.quasis.length - 1] === node; + var value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); + this.token(value); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function TemplateLiteral(node) { + var quasis = node.quasis; -var buildPropertyMethodAssignmentWrapper = (0, _babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); + for (var i = 0; i < quasis.length; i++) { + this.print(quasis[i], node); -var buildGeneratorPropertyMethodAssignmentWrapper = (0, _babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); + if (i + 1 < quasis.length) { + this.print(node.expressions[i], node); + } + } +} -var visitor = { - "ReferencedIdentifier|BindingIdentifier": function ReferencedIdentifierBindingIdentifier(path, state) { - if (path.node.name !== state.name) return; +},{}],49:[function(require,module,exports){ +"use strict"; - var localDeclar = path.scope.getBindingIdentifier(state.name); - if (localDeclar !== state.outerDeclar) return; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Identifier = Identifier; +exports.ArgumentPlaceholder = ArgumentPlaceholder; +exports.SpreadElement = exports.RestElement = RestElement; +exports.ObjectPattern = exports.ObjectExpression = ObjectExpression; +exports.ObjectMethod = ObjectMethod; +exports.ObjectProperty = ObjectProperty; +exports.ArrayPattern = exports.ArrayExpression = ArrayExpression; +exports.RegExpLiteral = RegExpLiteral; +exports.BooleanLiteral = BooleanLiteral; +exports.NullLiteral = NullLiteral; +exports.NumericLiteral = NumericLiteral; +exports.StringLiteral = StringLiteral; +exports.BigIntLiteral = BigIntLiteral; +exports.PipelineTopicExpression = PipelineTopicExpression; +exports.PipelineBareFunction = PipelineBareFunction; +exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference; - state.selfReference = true; - path.stop(); - } -}; +var t = _interopRequireWildcard(require("@babel/types")); -function wrap(state, method, id, scope) { - if (state.selfReference) { - if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) { - scope.rename(id.name); - } else { - if (!t.isFunction(method)) return; +var _jsesc = _interopRequireDefault(require("jsesc")); - var build = buildPropertyMethodAssignmentWrapper; - if (method.generator) build = buildGeneratorPropertyMethodAssignmentWrapper; - var _template = build({ - FUNCTION: method, - FUNCTION_ID: id, - FUNCTION_KEY: scope.generateUidIdentifier(id.name) - }).expression; - _template.callee._skipModulesRemap = true; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - var params = _template.callee.body.body[0].params; - for (var i = 0, len = (0, _babelHelperGetFunctionArity2.default)(method); i < len; i++) { - params.push(scope.generateUidIdentifier("x")); - } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - return _template; - } - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - method.id = id; - scope.getProgramParent().references[id.name] = true; + return cache; } -function visit(node, name, scope) { - var state = { - selfAssignment: false, - selfReference: false, - outerDeclar: scope.getBindingIdentifier(name), - references: [], - name: name - }; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - var binding = scope.getOwnBinding(name); + var cache = _getRequireWildcardCache(); - if (binding) { - if (binding.kind === "param") { - state.selfReference = true; - } else {} - } else if (state.outerDeclar || scope.hasGlobal(name)) { - scope.traverse(node, visitor, state); + if (cache && cache.has(obj)) { + return cache.get(obj); } - return state; -} + var newObj = {}; -module.exports = exports["default"]; -},{"babel-helper-get-function-arity":54,"babel-template":114,"babel-types":151}],54:[function(require,module,exports){ -"use strict"; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -exports.__esModule = true; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -exports.default = function (node) { - var params = node.params; - for (var i = 0; i < params.length; i++) { - var param = params[i]; - if (t.isAssignmentPattern(param) || t.isRestElement(param)) { - return i; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } } } - return params.length; -}; - -var _babelTypes = require("babel-types"); -var t = _interopRequireWildcard(_babelTypes); + newObj.default = obj; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -module.exports = exports["default"]; -},{"babel-types":151}],55:[function(require,module,exports){ -"use strict"; + if (cache) { + cache.set(obj, newObj); + } -exports.__esModule = true; + return newObj; +} -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function Identifier(node) { + var _this = this; -var _getIterator3 = _interopRequireDefault(_getIterator2); + this.exactSource(node.loc, function () { + _this.word(node.name); + }); +} -exports.default = function (path, emit) { - var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "var"; +function ArgumentPlaceholder() { + this.token("?"); +} - path.traverse(visitor, { kind: kind, emit: emit }); -}; +function RestElement(node) { + this.token("..."); + this.print(node.argument, node); +} -var _babelTypes = require("babel-types"); +function ObjectExpression(node) { + var props = node.properties; + this.token("{"); + this.printInnerComments(node); -var t = _interopRequireWildcard(_babelTypes); + if (props.length) { + this.space(); + this.printList(props, node, { + indent: true, + statement: true + }); + this.space(); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + this.token("}"); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function ObjectMethod(node) { + this.printJoin(node.decorators, node); -var visitor = { - Scope: function Scope(path, state) { - if (state.kind === "let") path.skip(); - }, - Function: function Function(path) { - path.skip(); - }, - VariableDeclaration: function VariableDeclaration(path, state) { - if (state.kind && path.node.kind !== state.kind) return; + this._methodHead(node); - var nodes = []; + this.space(); + this.print(node.body, node); +} - var declarations = path.get("declarations"); - var firstId = void 0; +function ObjectProperty(node) { + this.printJoin(node.decorators, node); - for (var _iterator = declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (node.computed) { + this.token("["); + this.print(node.key, node); + this.token("]"); + } else { + if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) { + this.print(node.value, node); + return; + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + this.print(node.key, node); - var declar = _ref; + if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { + return; + } + } - firstId = declar.node.id; + this.token(":"); + this.space(); + this.print(node.value, node); +} - if (declar.node.init) { - nodes.push(t.expressionStatement(t.assignmentExpression("=", declar.node.id, declar.node.init))); - } +function ArrayExpression(node) { + var elems = node.elements; + var len = elems.length; + this.token("["); + this.printInnerComments(node); - for (var name in declar.getBindingIdentifiers()) { - state.emit(t.identifier(name), name); - } - } + for (var i = 0; i < elems.length; i++) { + var elem = elems[i]; - if (path.parentPath.isFor({ left: path.node })) { - path.replaceWith(firstId); + if (elem) { + if (i > 0) this.space(); + this.print(elem, node); + if (i < len - 1) this.token(","); } else { - path.replaceWithMultiple(nodes); + this.token(","); } } -}; -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],56:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; + this.token("]"); +} -exports.default = function (callee, thisNode, args) { - if (args.length === 1 && t.isSpreadElement(args[0]) && t.isIdentifier(args[0].argument, { name: "arguments" })) { - return t.callExpression(t.memberExpression(callee, t.identifier("apply")), [thisNode, args[0].argument]); - } else { - return t.callExpression(t.memberExpression(callee, t.identifier("call")), [thisNode].concat(args)); - } -}; +function RegExpLiteral(node) { + this.word("/".concat(node.pattern, "/").concat(node.flags)); +} -var _babelTypes = require("babel-types"); +function BooleanLiteral(node) { + this.word(node.value ? "true" : "false"); +} -var t = _interopRequireWildcard(_babelTypes); +function NullLiteral() { + this.word("null"); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function NumericLiteral(node) { + var raw = this.getPossibleRaw(node); + var value = node.value + ""; -module.exports = exports["default"]; -},{"babel-types":151}],57:[function(require,module,exports){ -"use strict"; + if (raw == null) { + this.number(value); + } else if (this.format.minified) { + this.number(raw.length < value.length ? raw : value); + } else { + this.number(raw); + } +} -exports.__esModule = true; -exports.is = is; -exports.pullFlag = pullFlag; +function StringLiteral(node) { + var raw = this.getPossibleRaw(node); -var _pull = require("lodash/pull"); + if (!this.format.minified && raw != null) { + this.token(raw); + return; + } -var _pull2 = _interopRequireDefault(_pull); + var opts = this.format.jsescOption; -var _babelTypes = require("babel-types"); + if (this.format.jsonCompatibleStrings) { + opts.json = true; + } -var t = _interopRequireWildcard(_babelTypes); + var val = (0, _jsesc.default)(node.value, opts); + return this.token(val); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function BigIntLiteral(node) { + var raw = this.getPossibleRaw(node); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!this.format.minified && raw != null) { + this.token(raw); + return; + } -function is(node, flag) { - return t.isRegExpLiteral(node) && node.flags.indexOf(flag) >= 0; + this.token(node.value); } -function pullFlag(node, flag) { - var flags = node.flags.split(""); - if (node.flags.indexOf(flag) < 0) return; - (0, _pull2.default)(flags, flag); - node.flags = flags.join(""); +function PipelineTopicExpression(node) { + this.print(node.expression, node); } -},{"babel-types":151,"lodash/pull":505}],58:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; +function PipelineBareFunction(node) { + this.print(node.callee, node); +} -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +function PipelinePrimaryTopicReference() { + this.token("#"); +} -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +},{"@babel/types":242,"jsesc":844}],50:[function(require,module,exports){ +"use strict"; -var _symbol = require("babel-runtime/core-js/symbol"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TSTypeAnnotation = TSTypeAnnotation; +exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation; +exports.TSTypeParameter = TSTypeParameter; +exports.TSParameterProperty = TSParameterProperty; +exports.TSDeclareFunction = TSDeclareFunction; +exports.TSDeclareMethod = TSDeclareMethod; +exports.TSQualifiedName = TSQualifiedName; +exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; +exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; +exports.TSPropertySignature = TSPropertySignature; +exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName; +exports.TSMethodSignature = TSMethodSignature; +exports.TSIndexSignature = TSIndexSignature; +exports.TSAnyKeyword = TSAnyKeyword; +exports.TSBigIntKeyword = TSBigIntKeyword; +exports.TSUnknownKeyword = TSUnknownKeyword; +exports.TSNumberKeyword = TSNumberKeyword; +exports.TSObjectKeyword = TSObjectKeyword; +exports.TSBooleanKeyword = TSBooleanKeyword; +exports.TSStringKeyword = TSStringKeyword; +exports.TSSymbolKeyword = TSSymbolKeyword; +exports.TSVoidKeyword = TSVoidKeyword; +exports.TSUndefinedKeyword = TSUndefinedKeyword; +exports.TSNullKeyword = TSNullKeyword; +exports.TSNeverKeyword = TSNeverKeyword; +exports.TSThisType = TSThisType; +exports.TSFunctionType = TSFunctionType; +exports.TSConstructorType = TSConstructorType; +exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType; +exports.TSTypeReference = TSTypeReference; +exports.TSTypePredicate = TSTypePredicate; +exports.TSTypeQuery = TSTypeQuery; +exports.TSTypeLiteral = TSTypeLiteral; +exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody; +exports.tsPrintBraced = tsPrintBraced; +exports.TSArrayType = TSArrayType; +exports.TSTupleType = TSTupleType; +exports.TSOptionalType = TSOptionalType; +exports.TSRestType = TSRestType; +exports.TSUnionType = TSUnionType; +exports.TSIntersectionType = TSIntersectionType; +exports.tsPrintUnionOrIntersectionType = tsPrintUnionOrIntersectionType; +exports.TSConditionalType = TSConditionalType; +exports.TSInferType = TSInferType; +exports.TSParenthesizedType = TSParenthesizedType; +exports.TSTypeOperator = TSTypeOperator; +exports.TSIndexedAccessType = TSIndexedAccessType; +exports.TSMappedType = TSMappedType; +exports.TSLiteralType = TSLiteralType; +exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments; +exports.TSInterfaceDeclaration = TSInterfaceDeclaration; +exports.TSInterfaceBody = TSInterfaceBody; +exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration; +exports.TSAsExpression = TSAsExpression; +exports.TSTypeAssertion = TSTypeAssertion; +exports.TSEnumDeclaration = TSEnumDeclaration; +exports.TSEnumMember = TSEnumMember; +exports.TSModuleDeclaration = TSModuleDeclaration; +exports.TSModuleBlock = TSModuleBlock; +exports.TSImportType = TSImportType; +exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; +exports.TSExternalModuleReference = TSExternalModuleReference; +exports.TSNonNullExpression = TSNonNullExpression; +exports.TSExportAssignment = TSExportAssignment; +exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration; +exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase; +exports.tsPrintClassMemberModifiers = tsPrintClassMemberModifiers; + +function TSTypeAnnotation(node) { + this.token(":"); + this.space(); + if (node.optional) this.token("?"); + this.print(node.typeAnnotation, node); +} -var _symbol2 = _interopRequireDefault(_symbol); +function TSTypeParameterInstantiation(node) { + this.token("<"); + this.printList(node.params, node, {}); + this.token(">"); +} -var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); +function TSTypeParameter(node) { + this.word(node.name); -var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); + if (node.constraint) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.constraint, node); + } -var _babelMessages = require("babel-messages"); + if (node.default) { + this.space(); + this.token("="); + this.space(); + this.print(node.default, node); + } +} -var messages = _interopRequireWildcard(_babelMessages); +function TSParameterProperty(node) { + if (node.accessibility) { + this.word(node.accessibility); + this.space(); + } -var _babelTypes = require("babel-types"); + if (node.readonly) { + this.word("readonly"); + this.space(); + } -var t = _interopRequireWildcard(_babelTypes); + this._param(node.parameter); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function TSDeclareFunction(node) { + if (node.declare) { + this.word("declare"); + this.space(); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this._functionHead(node); -var HARDCORE_THIS_REF = (0, _symbol2.default)(); - -function isIllegalBareSuper(node, parent) { - if (!t.isSuper(node)) return false; - if (t.isMemberExpression(parent, { computed: false })) return false; - if (t.isCallExpression(parent, { callee: node })) return false; - return true; + this.token(";"); } -function isMemberExpressionSuper(node) { - return t.isMemberExpression(node) && t.isSuper(node.object); +function TSDeclareMethod(node) { + this._classMethodHead(node); + + this.token(";"); } -function getPrototypeOfExpression(objectRef, isStatic) { - var targetRef = isStatic ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); +function TSQualifiedName(node) { + this.print(node.left, node); + this.token("."); + this.print(node.right, node); +} - return t.logicalExpression("||", t.memberExpression(targetRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [targetRef])); +function TSCallSignatureDeclaration(node) { + this.tsPrintSignatureDeclarationBase(node); + this.token(";"); } -var visitor = { - Function: function Function(path) { - if (!path.inShadow("this")) { - path.skip(); - } - }, - ReturnStatement: function ReturnStatement(path, state) { - if (!path.inShadow("this")) { - state.returns.push(path); - } - }, - ThisExpression: function ThisExpression(path, state) { - if (!path.node[HARDCORE_THIS_REF]) { - state.thises.push(path); - } - }, - enter: function enter(path, state) { - var callback = state.specHandle; - if (state.isLoose) callback = state.looseHandle; +function TSConstructSignatureDeclaration(node) { + this.word("new"); + this.space(); + this.tsPrintSignatureDeclarationBase(node); + this.token(";"); +} - var isBareSuper = path.isCallExpression() && path.get("callee").isSuper(); +function TSPropertySignature(node) { + var readonly = node.readonly, + initializer = node.initializer; - var result = callback.call(state, path); + if (readonly) { + this.word("readonly"); + this.space(); + } - if (result) { - state.hasSuper = true; - } + this.tsPrintPropertyOrMethodName(node); + this.print(node.typeAnnotation, node); - if (isBareSuper) { - state.bareSupers.push(path); - } + if (initializer) { + this.space(); + this.token("="); + this.space(); + this.print(initializer, node); + } - if (result === true) { - path.requeue(); - } + this.token(";"); +} - if (result !== true && result) { - if (Array.isArray(result)) { - path.replaceWithMultiple(result); - } else { - path.replaceWith(result); - } - } +function tsPrintPropertyOrMethodName(node) { + if (node.computed) { + this.token("["); } -}; -var ReplaceSupers = function () { - function ReplaceSupers(opts) { - var inClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - (0, _classCallCheck3.default)(this, ReplaceSupers); - - this.forceSuperMemoisation = opts.forceSuperMemoisation; - this.methodPath = opts.methodPath; - this.methodNode = opts.methodNode; - this.superRef = opts.superRef; - this.isStatic = opts.isStatic; - this.hasSuper = false; - this.inClass = inClass; - this.isLoose = opts.isLoose; - this.scope = this.methodPath.scope; - this.file = opts.file; - this.opts = opts; + this.print(node.key, node); - this.bareSupers = []; - this.returns = []; - this.thises = []; + if (node.computed) { + this.token("]"); } - ReplaceSupers.prototype.getObjectRef = function getObjectRef() { - return this.opts.objectRef || this.opts.getObjectRef(); - }; + if (node.optional) { + this.token("?"); + } +} - ReplaceSupers.prototype.setSuperProperty = function setSuperProperty(property, value, isComputed) { - return t.callExpression(this.file.addHelper("set"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), value, t.thisExpression()]); - }; +function TSMethodSignature(node) { + this.tsPrintPropertyOrMethodName(node); + this.tsPrintSignatureDeclarationBase(node); + this.token(";"); +} - ReplaceSupers.prototype.getSuperProperty = function getSuperProperty(property, isComputed) { - return t.callExpression(this.file.addHelper("get"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), t.thisExpression()]); - }; +function TSIndexSignature(node) { + var readonly = node.readonly; - ReplaceSupers.prototype.replace = function replace() { - this.methodPath.traverse(visitor, this); - }; + if (readonly) { + this.word("readonly"); + this.space(); + } - ReplaceSupers.prototype.getLooseSuperProperty = function getLooseSuperProperty(id, parent) { - var methodNode = this.methodNode; - var superRef = this.superRef || t.identifier("Function"); + this.token("["); - if (parent.property === id) { - return; - } else if (t.isCallExpression(parent, { callee: id })) { - return; - } else if (t.isMemberExpression(parent) && !methodNode.static) { - return t.memberExpression(superRef, t.identifier("prototype")); - } else { - return superRef; - } - }; + this._parameters(node.parameters, node); - ReplaceSupers.prototype.looseHandle = function looseHandle(path) { - var node = path.node; - if (path.isSuper()) { - return this.getLooseSuperProperty(node, path.parent); - } else if (path.isCallExpression()) { - var callee = node.callee; - if (!t.isMemberExpression(callee)) return; - if (!t.isSuper(callee.object)) return; + this.token("]"); + this.print(node.typeAnnotation, node); + this.token(";"); +} - t.appendToMemberExpression(callee, t.identifier("call")); - node.arguments.unshift(t.thisExpression()); - return true; - } - }; +function TSAnyKeyword() { + this.word("any"); +} - ReplaceSupers.prototype.specHandleAssignmentExpression = function specHandleAssignmentExpression(ref, path, node) { - if (node.operator === "=") { - return this.setSuperProperty(node.left.property, node.right, node.left.computed); - } else { - ref = ref || path.scope.generateUidIdentifier("ref"); - return [t.variableDeclaration("var", [t.variableDeclarator(ref, node.left)]), t.expressionStatement(t.assignmentExpression("=", node.left, t.binaryExpression(node.operator[0], ref, node.right)))]; - } - }; +function TSBigIntKeyword() { + this.word("bigint"); +} - ReplaceSupers.prototype.specHandle = function specHandle(path) { - var property = void 0; - var computed = void 0; - var args = void 0; +function TSUnknownKeyword() { + this.word("unknown"); +} - var parent = path.parent; - var node = path.node; +function TSNumberKeyword() { + this.word("number"); +} - if (isIllegalBareSuper(node, parent)) { - throw path.buildCodeFrameError(messages.get("classesIllegalBareSuper")); - } +function TSObjectKeyword() { + this.word("object"); +} - if (t.isCallExpression(node)) { - var callee = node.callee; - if (t.isSuper(callee)) { - return; - } else if (isMemberExpressionSuper(callee)) { - property = callee.property; - computed = callee.computed; - args = node.arguments; - } - } else if (t.isMemberExpression(node) && t.isSuper(node.object)) { - property = node.property; - computed = node.computed; - } else if (t.isUpdateExpression(node) && isMemberExpressionSuper(node.argument)) { - var binary = t.binaryExpression(node.operator[0], node.argument, t.numericLiteral(1)); - if (node.prefix) { - return this.specHandleAssignmentExpression(null, path, binary); - } else { - var ref = path.scope.generateUidIdentifier("ref"); - return this.specHandleAssignmentExpression(ref, path, binary).concat(t.expressionStatement(ref)); - } - } else if (t.isAssignmentExpression(node) && isMemberExpressionSuper(node.left)) { - return this.specHandleAssignmentExpression(null, path, node); - } +function TSBooleanKeyword() { + this.word("boolean"); +} - if (!property) return; +function TSStringKeyword() { + this.word("string"); +} - var superProperty = this.getSuperProperty(property, computed); +function TSSymbolKeyword() { + this.word("symbol"); +} - if (args) { - return this.optimiseCall(superProperty, args); - } else { - return superProperty; - } - }; +function TSVoidKeyword() { + this.word("void"); +} - ReplaceSupers.prototype.optimiseCall = function optimiseCall(callee, args) { - var thisNode = t.thisExpression(); - thisNode[HARDCORE_THIS_REF] = true; - return (0, _babelHelperOptimiseCallExpression2.default)(callee, thisNode, args); - }; +function TSUndefinedKeyword() { + this.word("undefined"); +} - return ReplaceSupers; -}(); +function TSNullKeyword() { + this.word("null"); +} -exports.default = ReplaceSupers; -module.exports = exports["default"]; -},{"babel-helper-optimise-call-expression":56,"babel-messages":61,"babel-runtime/core-js/symbol":104,"babel-runtime/helpers/classCallCheck":109,"babel-types":151}],59:[function(require,module,exports){ -"use strict"; +function TSNeverKeyword() { + this.word("never"); +} -exports.__esModule = true; +function TSThisType() { + this.word("this"); +} -var _babelTemplate = require("babel-template"); +function TSFunctionType(node) { + this.tsPrintFunctionOrConstructorType(node); +} -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); +function TSConstructorType(node) { + this.word("new"); + this.space(); + this.tsPrintFunctionOrConstructorType(node); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function tsPrintFunctionOrConstructorType(node) { + var typeParameters = node.typeParameters, + parameters = node.parameters; + this.print(typeParameters, node); + this.token("("); -var helpers = {}; -exports.default = helpers; + this._parameters(parameters, node); + this.token(")"); + this.space(); + this.token("=>"); + this.space(); + this.print(node.typeAnnotation.typeAnnotation, node); +} -helpers.typeof = (0, _babelTemplate2.default)("\n (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? \"symbol\"\n : typeof obj;\n };\n"); +function TSTypeReference(node) { + this.print(node.typeName, node); + this.print(node.typeParameters, node); +} -helpers.jsx = (0, _babelTemplate2.default)("\n (function () {\n var REACT_ELEMENT_TYPE = (typeof Symbol === \"function\" && Symbol.for && Symbol.for(\"react.element\")) || 0xeac7;\n\n return function createRawReactElement (type, props, key, children) {\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we're going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {};\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n };\n\n })()\n"); +function TSTypePredicate(node) { + if (node.asserts) { + this.word("asserts"); + this.space(); + } -helpers.asyncIterator = (0, _babelTemplate2.default)("\n (function (iterable) {\n if (typeof Symbol === \"function\") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError(\"Object is not async iterable\");\n })\n"); + this.print(node.parameterName); -helpers.asyncGenerator = (0, _babelTemplate2.default)("\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume(\"next\", arg); },\n function (arg) { resume(\"throw\", arg); });\n } else {\n settle(result.done ? \"return\" : \"normal\", result.value);\n }\n } catch (err) {\n settle(\"throw\", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case \"return\":\n front.resolve({ value: value, done: true });\n break;\n case \"throw\":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide \"return\" method if generator return is not supported\n if (typeof gen.return !== \"function\") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === \"function\" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke(\"next\", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke(\"throw\", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke(\"return\", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n"); + if (node.typeAnnotation) { + this.space(); + this.word("is"); + this.space(); + this.print(node.typeAnnotation.typeAnnotation); + } +} -helpers.asyncGeneratorDelegate = (0, _babelTemplate2.default)("\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === \"function\" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump(\"next\", value);\n };\n\n if (typeof inner.throw === \"function\") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump(\"throw\", value);\n };\n }\n\n if (typeof inner.return === \"function\") {\n iter.return = function (value) {\n return pump(\"return\", value);\n };\n }\n\n return iter;\n })\n"); +function TSTypeQuery(node) { + this.word("typeof"); + this.space(); + this.print(node.exprName); +} -helpers.asyncToGenerator = (0, _babelTemplate2.default)("\n (function (fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n return Promise.resolve(value).then(function (value) {\n step(\"next\", value);\n }, function (err) {\n step(\"throw\", err);\n });\n }\n }\n\n return step(\"next\");\n });\n };\n })\n"); +function TSTypeLiteral(node) { + this.tsPrintTypeLiteralOrInterfaceBody(node.members, node); +} -helpers.classCallCheck = (0, _babelTemplate2.default)("\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n });\n"); +function tsPrintTypeLiteralOrInterfaceBody(members, node) { + this.tsPrintBraced(members, node); +} -helpers.createClass = (0, _babelTemplate2.default)("\n (function() {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n })()\n"); +function tsPrintBraced(members, node) { + this.token("{"); -helpers.defineEnumerableProperties = (0, _babelTemplate2.default)("\n (function (obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if (\"value\" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n return obj;\n })\n"); + if (members.length) { + this.indent(); + this.newline(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; -helpers.defaults = (0, _babelTemplate2.default)("\n (function (obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n })\n"); + try { + for (var _iterator = members[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var member = _step.value; + this.print(member, node); + this.newline(); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } -helpers.defineProperty = (0, _babelTemplate2.default)("\n (function (obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n });\n"); + this.dedent(); + this.rightBrace(); + } else { + this.token("}"); + } +} -helpers.extends = (0, _babelTemplate2.default)("\n Object.assign || (function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n })\n"); +function TSArrayType(node) { + this.print(node.elementType, node); + this.token("[]"); +} -helpers.get = (0, _babelTemplate2.default)("\n (function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n });\n"); +function TSTupleType(node) { + this.token("["); + this.printList(node.elementTypes, node); + this.token("]"); +} -helpers.inherits = (0, _babelTemplate2.default)("\n (function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n })\n"); +function TSOptionalType(node) { + this.print(node.typeAnnotation, node); + this.token("?"); +} -helpers.instanceof = (0, _babelTemplate2.default)("\n (function (left, right) {\n if (right != null && typeof Symbol !== \"undefined\" && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n });\n"); +function TSRestType(node) { + this.token("..."); + this.print(node.typeAnnotation, node); +} -helpers.interopRequireDefault = (0, _babelTemplate2.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"); +function TSUnionType(node) { + this.tsPrintUnionOrIntersectionType(node, "|"); +} -helpers.interopRequireWildcard = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];\n }\n }\n newObj.default = obj;\n return newObj;\n }\n })\n"); +function TSIntersectionType(node) { + this.tsPrintUnionOrIntersectionType(node, "&"); +} -helpers.newArrowCheck = (0, _babelTemplate2.default)("\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError(\"Cannot instantiate an arrow function\");\n }\n });\n"); +function tsPrintUnionOrIntersectionType(node, sep) { + this.printJoin(node.types, node, { + separator: function separator() { + this.space(); + this.token(sep); + this.space(); + } + }); +} -helpers.objectDestructuringEmpty = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj == null) throw new TypeError(\"Cannot destructure undefined\");\n });\n"); +function TSConditionalType(node) { + this.print(node.checkType); + this.space(); + this.word("extends"); + this.space(); + this.print(node.extendsType); + this.space(); + this.token("?"); + this.space(); + this.print(node.trueType); + this.space(); + this.token(":"); + this.space(); + this.print(node.falseType); +} -helpers.objectWithoutProperties = (0, _babelTemplate2.default)("\n (function (obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n })\n"); +function TSInferType(node) { + this.token("infer"); + this.space(); + this.print(node.typeParameter); +} -helpers.possibleConstructorReturn = (0, _babelTemplate2.default)("\n (function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n });\n"); +function TSParenthesizedType(node) { + this.token("("); + this.print(node.typeAnnotation, node); + this.token(")"); +} -helpers.selfGlobal = (0, _babelTemplate2.default)("\n typeof global === \"undefined\" ? self : global\n"); +function TSTypeOperator(node) { + this.token(node.operator); + this.space(); + this.print(node.typeAnnotation, node); +} -helpers.set = (0, _babelTemplate2.default)("\n (function set(object, property, value, receiver) {\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent !== null) {\n set(parent, property, value, receiver);\n }\n } else if (\"value\" in desc && desc.writable) {\n desc.value = value;\n } else {\n var setter = desc.set;\n\n if (setter !== undefined) {\n setter.call(receiver, value);\n }\n }\n\n return value;\n });\n"); +function TSIndexedAccessType(node) { + this.print(node.objectType, node); + this.token("["); + this.print(node.indexType, node); + this.token("]"); +} -helpers.slicedToArray = (0, _babelTemplate2.default)("\n (function () {\n // Broken out into a separate function to avoid deoptimizations due to the try/catch for the\n // array iterator case.\n function sliceIterator(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliancy is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"]) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n };\n })();\n"); +function TSMappedType(node) { + var readonly = node.readonly, + typeParameter = node.typeParameter, + optional = node.optional; + this.token("{"); + this.space(); -helpers.slicedToArrayLoose = (0, _babelTemplate2.default)("\n (function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n });\n"); + if (readonly) { + tokenIfPlusMinus(this, readonly); + this.word("readonly"); + this.space(); + } -helpers.taggedTemplateLiteral = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"); + this.token("["); + this.word(typeParameter.name); + this.space(); + this.word("in"); + this.space(); + this.print(typeParameter.constraint, typeParameter); + this.token("]"); -helpers.taggedTemplateLiteralLoose = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"); + if (optional) { + tokenIfPlusMinus(this, optional); + this.token("?"); + } -helpers.temporalRef = (0, _babelTemplate2.default)("\n (function (val, name, undef) {\n if (val === undef) {\n throw new ReferenceError(name + \" is not defined - temporal dead zone\");\n } else {\n return val;\n }\n })\n"); + this.token(":"); + this.space(); + this.print(node.typeAnnotation, node); + this.space(); + this.token("}"); +} -helpers.temporalUndefined = (0, _babelTemplate2.default)("\n ({})\n"); +function tokenIfPlusMinus(self, tok) { + if (tok !== true) { + self.token(tok); + } +} -helpers.toArray = (0, _babelTemplate2.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"); +function TSLiteralType(node) { + this.print(node.literal, node); +} -helpers.toConsumableArray = (0, _babelTemplate2.default)("\n (function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n } else {\n return Array.from(arr);\n }\n });\n"); -module.exports = exports["default"]; -},{"babel-template":114}],60:[function(require,module,exports){ -"use strict"; +function TSExpressionWithTypeArguments(node) { + this.print(node.expression, node); + this.print(node.typeParameters, node); +} -exports.__esModule = true; -exports.list = undefined; +function TSInterfaceDeclaration(node) { + var declare = node.declare, + id = node.id, + typeParameters = node.typeParameters, + extendz = node.extends, + body = node.body; -var _keys = require("babel-runtime/core-js/object/keys"); + if (declare) { + this.word("declare"); + this.space(); + } -var _keys2 = _interopRequireDefault(_keys); + this.word("interface"); + this.space(); + this.print(id, node); + this.print(typeParameters, node); -exports.get = get; + if (extendz) { + this.space(); + this.word("extends"); + this.space(); + this.printList(extendz, node); + } -var _helpers = require("./helpers"); + this.space(); + this.print(body, node); +} -var _helpers2 = _interopRequireDefault(_helpers); +function TSInterfaceBody(node) { + this.tsPrintTypeLiteralOrInterfaceBody(node.body, node); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function TSTypeAliasDeclaration(node) { + var declare = node.declare, + id = node.id, + typeParameters = node.typeParameters, + typeAnnotation = node.typeAnnotation; -function get(name) { - var fn = _helpers2.default[name]; - if (!fn) throw new ReferenceError("Unknown helper " + name); + if (declare) { + this.word("declare"); + this.space(); + } - return fn().expression; + this.word("type"); + this.space(); + this.print(id, node); + this.print(typeParameters, node); + this.space(); + this.token("="); + this.space(); + this.print(typeAnnotation, node); + this.token(";"); } -var list = exports.list = (0, _keys2.default)(_helpers2.default).map(function (name) { - return name.replace(/^_/, ""); -}).filter(function (name) { - return name !== "__esModule"; -}); +function TSAsExpression(node) { + var expression = node.expression, + typeAnnotation = node.typeAnnotation; + this.print(expression, node); + this.space(); + this.word("as"); + this.space(); + this.print(typeAnnotation, node); +} -exports.default = get; -},{"./helpers":59,"babel-runtime/core-js/object/keys":102}],61:[function(require,module,exports){ -"use strict"; +function TSTypeAssertion(node) { + var typeAnnotation = node.typeAnnotation, + expression = node.expression; + this.token("<"); + this.print(typeAnnotation, node); + this.token(">"); + this.space(); + this.print(expression, node); +} -exports.__esModule = true; -exports.MESSAGES = undefined; +function TSEnumDeclaration(node) { + var declare = node.declare, + isConst = node.const, + id = node.id, + members = node.members; -var _stringify = require("babel-runtime/core-js/json/stringify"); + if (declare) { + this.word("declare"); + this.space(); + } -var _stringify2 = _interopRequireDefault(_stringify); + if (isConst) { + this.word("const"); + this.space(); + } -exports.get = get; -exports.parseArgs = parseArgs; + this.word("enum"); + this.space(); + this.print(id, node); + this.space(); + this.tsPrintBraced(members, node); +} -var _util = require("util"); +function TSEnumMember(node) { + var id = node.id, + initializer = node.initializer; + this.print(id, node); -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var MESSAGES = exports.MESSAGES = { - tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence", - classesIllegalBareSuper: "Illegal use of bare super", - classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead", - scopeDuplicateDeclaration: "Duplicate declaration $1", - settersNoRest: "Setters aren't allowed to have a rest", - noAssignmentsInForHead: "No assignments allowed in for-in/of head", - expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier", - invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue", - readOnly: "$1 is read-only", - unknownForHead: "Unknown node type $1 in ForStatement", - didYouMean: "Did you mean $1?", - codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.", - missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues", - unsupportedOutputType: "Unsupported output type $1", - illegalMethodName: "Illegal method name $1", - lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated", - - modulesIllegalExportName: "Illegal export $1", - modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes", - - undeclaredVariable: "Reference to undeclared variable $1", - undeclaredVariableType: "Referencing a type alias outside of a type annotation", - undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?", - - traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.", - traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?", - traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2", - traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type", - - pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3", - pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3", - pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4", - pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3" -}; - -function get(key) { - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; + if (initializer) { + this.space(); + this.token("="); + this.space(); + this.print(initializer, node); } - var msg = MESSAGES[key]; - if (!msg) throw new ReferenceError("Unknown message " + (0, _stringify2.default)(key)); + this.token(","); +} - args = parseArgs(args); +function TSModuleDeclaration(node) { + var declare = node.declare, + id = node.id; - return msg.replace(/\$(\d+)/g, function (str, i) { - return args[i - 1]; - }); -} + if (declare) { + this.word("declare"); + this.space(); + } -function parseArgs(args) { - return args.map(function (val) { - if (val != null && val.inspect) { - return val.inspect(); - } else { - try { - return (0, _stringify2.default)(val) || val + ""; - } catch (e) { - return util.inspect(val); - } - } - }); -} -},{"babel-runtime/core-js/json/stringify":96,"util":560}],62:[function(require,module,exports){ -"use strict"; + if (!node.global) { + this.word(id.type === "Identifier" ? "namespace" : "module"); + this.space(); + } -exports.__esModule = true; + this.print(id, node); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (!node.body) { + this.token(";"); + return; + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + var body = node.body; -exports.default = function (_ref) { - var messages = _ref.messages; + while (body.type === "TSModuleDeclaration") { + this.token("."); + this.print(body.id, body); + body = body.body; + } - return { - visitor: { - Scope: function Scope(_ref2) { - var scope = _ref2.scope; + this.space(); + this.print(body, node); +} - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - if (binding.kind !== "const" && binding.kind !== "module") continue; +function TSModuleBlock(node) { + this.tsPrintBraced(node.body, node); +} - for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref3; +function TSImportType(node) { + var argument = node.argument, + qualifier = node.qualifier, + typeParameters = node.typeParameters; + this.word("import"); + this.token("("); + this.print(argument, node); + this.token(")"); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref3 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref3 = _i.value; - } + if (qualifier) { + this.token("."); + this.print(qualifier, node); + } - var violation = _ref3; + if (typeParameters) { + this.print(typeParameters, node); + } +} - throw violation.buildCodeFrameError(messages.get("readOnly", name)); - } - } - } - } - }; -}; +function TSImportEqualsDeclaration(node) { + var isExport = node.isExport, + id = node.id, + moduleReference = node.moduleReference; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (isExport) { + this.word("export"); + this.space(); + } -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],63:[function(require,module,exports){ -"use strict"; + this.word("import"); + this.space(); + this.print(id, node); + this.space(); + this.token("="); + this.space(); + this.print(moduleReference, node); + this.token(";"); +} -exports.__esModule = true; +function TSExternalModuleReference(node) { + this.token("require("); + this.print(node.expression, node); + this.token(")"); +} -exports.default = function () { - return { - manipulateOptions: function manipulateOptions(opts, parserOpts) { - parserOpts.plugins.push("dynamicImport"); - } - }; -}; +function TSNonNullExpression(node) { + this.print(node.expression, node); + this.token("!"); +} -module.exports = exports["default"]; -},{}],64:[function(require,module,exports){ -"use strict"; +function TSExportAssignment(node) { + this.word("export"); + this.space(); + this.token("="); + this.space(); + this.print(node.expression, node); + this.token(";"); +} -exports.__esModule = true; +function TSNamespaceExportDeclaration(node) { + this.word("export"); + this.space(); + this.word("as"); + this.space(); + this.word("namespace"); + this.space(); + this.print(node.id, node); +} -exports.default = function (_ref) { - var t = _ref.types; +function tsPrintSignatureDeclarationBase(node) { + var typeParameters = node.typeParameters, + parameters = node.parameters; + this.print(typeParameters, node); + this.token("("); - return { - visitor: { - ArrowFunctionExpression: function ArrowFunctionExpression(path, state) { - if (state.opts.spec) { - var node = path.node; + this._parameters(parameters, node); - if (node.shadow) return; + this.token(")"); + this.print(node.typeAnnotation, node); +} - node.shadow = { this: false }; - node.type = "FunctionExpression"; +function tsPrintClassMemberModifiers(node, isField) { + if (isField && node.declare) { + this.word("declare"); + this.space(); + } - var boundThis = t.thisExpression(); - boundThis._forceShadow = path; + if (node.accessibility) { + this.word(node.accessibility); + this.space(); + } - path.ensureBlock(); - path.get("body").unshiftContainer("body", t.expressionStatement(t.callExpression(state.addHelper("newArrowCheck"), [t.thisExpression(), boundThis]))); + if (node.static) { + this.word("static"); + this.space(); + } - path.replaceWith(t.callExpression(t.memberExpression(node, t.identifier("bind")), [t.thisExpression()])); - } else { - path.arrowFunctionToShadowed(); - } - } - } - }; -}; + if (node.abstract) { + this.word("abstract"); + this.space(); + } -module.exports = exports["default"]; -},{}],65:[function(require,module,exports){ -"use strict"; + if (isField && node.readonly) { + this.word("readonly"); + this.space(); + } +} -exports.__esModule = true; +},{}],51:[function(require,module,exports){ +"use strict"; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -var _getIterator3 = _interopRequireDefault(_getIterator2); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -exports.default = function (_ref) { - var t = _ref.types; +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function statementList(key, path) { - var paths = path.get(key); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - var _path = _ref2; +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } - var func = _path.node; - if (!_path.isFunctionDeclaration()) continue; +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } - var declar = t.variableDeclaration("let", [t.variableDeclarator(func.id, t.toExpression(func))]); +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - declar._blockHoist = 2; +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - func.id = null; +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - _path.replaceWith(declar); - } - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +exports.CodeGenerator = void 0; - return { - visitor: { - BlockStatement: function BlockStatement(path) { - var node = path.node, - parent = path.parent; +var _sourceMap = _interopRequireDefault(require("./source-map")); - if (t.isFunction(parent, { body: node }) || t.isExportDeclaration(parent)) { - return; - } +var _printer = _interopRequireDefault(require("./printer")); - statementList("body", path); - }, - SwitchCase: function SwitchCase(path) { - statementList("consequent", path); - } - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +} -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],66:[function(require,module,exports){ -"use strict"; +var Generator = +/*#__PURE__*/ +function (_printer$default) { + _inherits(Generator, _printer$default); -exports.__esModule = true; + function Generator(ast) { + var _this; -var _symbol = require("babel-runtime/core-js/symbol"); + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var code = arguments.length > 2 ? arguments[2] : undefined; -var _symbol2 = _interopRequireDefault(_symbol); + _classCallCheck(this, Generator); -var _create = require("babel-runtime/core-js/object/create"); + var format = normalizeOptions(code, opts); + var map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null; + _this = _possibleConstructorReturn(this, _getPrototypeOf(Generator).call(this, format, map)); + _this.ast = ast; + return _this; + } -var _create2 = _interopRequireDefault(_create); + _createClass(Generator, [{ + key: "generate", + value: function generate() { + return _get(_getPrototypeOf(Generator.prototype), "generate", this).call(this, this.ast); + } + }]); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + return Generator; +}(_printer.default); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +function normalizeOptions(code, opts) { + var format = { + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + shouldPrintComment: opts.shouldPrintComment, + retainLines: opts.retainLines, + retainFunctionParens: opts.retainFunctionParens, + comments: opts.comments == null || opts.comments, + compact: opts.compact, + minified: opts.minified, + concise: opts.concise, + jsonCompatibleStrings: opts.jsonCompatibleStrings, + indent: { + adjustMultilineComment: true, + style: " ", + base: 0 + }, + decoratorsBeforeExport: !!opts.decoratorsBeforeExport, + jsescOption: Object.assign({ + quotes: "double", + wrap: true + }, opts.jsescOption) + }; -exports.default = function () { - return { - visitor: { - VariableDeclaration: function VariableDeclaration(path, file) { - var node = path.node, - parent = path.parent, - scope = path.scope; + if (format.minified) { + format.compact = true; - if (!isBlockScoped(node)) return; - convertBlockScopedToVar(path, null, parent, scope, true); + format.shouldPrintComment = format.shouldPrintComment || function () { + return format.comments; + }; + } else { + format.shouldPrintComment = format.shouldPrintComment || function (value) { + return format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0; + }; + } - if (node._tdzThis) { - var nodes = [node]; + if (format.compact === "auto") { + format.compact = code.length > 500000; - for (var i = 0; i < node.declarations.length; i++) { - var decl = node.declarations[i]; - if (decl.init) { - var assign = t.assignmentExpression("=", decl.id, decl.init); - assign._ignoreBlockScopingTDZ = true; - nodes.push(t.expressionStatement(assign)); - } - decl.init = file.addHelper("temporalUndefined"); - } + if (format.compact) { + console.error("[BABEL] Note: The code generator has deoptimised the styling of " + "".concat(opts.filename, " as it exceeds the max of ", "500KB", ".")); + } + } - node._blockHoist = 2; + if (format.compact) { + format.indent.adjustMultilineComment = false; + } - if (path.isCompletionRecord()) { - nodes.push(t.expressionStatement(scope.buildUndefinedNode())); - } + return format; +} - path.replaceWithMultiple(nodes); - } - }, - Loop: function Loop(path, file) { - var node = path.node, - parent = path.parent, - scope = path.scope; +var CodeGenerator = +/*#__PURE__*/ +function () { + function CodeGenerator(ast, opts, code) { + _classCallCheck(this, CodeGenerator); - t.ensureBlock(node); - var blockScoping = new BlockScoping(path, path.get("body"), parent, scope, file); - var replace = blockScoping.run(); - if (replace) path.replaceWith(replace); - }, - CatchClause: function CatchClause(path, file) { - var parent = path.parent, - scope = path.scope; + this._generator = new Generator(ast, opts, code); + } - var blockScoping = new BlockScoping(null, path.get("body"), parent, scope, file); - blockScoping.run(); - }, - "BlockStatement|SwitchStatement|Program": function BlockStatementSwitchStatementProgram(path, file) { - if (!ignoreBlock(path)) { - var blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); - blockScoping.run(); - } - } + _createClass(CodeGenerator, [{ + key: "generate", + value: function generate() { + return this._generator.generate(); } - }; -}; + }]); -var _babelTraverse = require("babel-traverse"); + return CodeGenerator; +}(); -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); +exports.CodeGenerator = CodeGenerator; -var _tdz = require("./tdz"); +function _default(ast, opts, code) { + var gen = new Generator(ast, opts, code); + return gen.generate(); +} -var _babelTypes = require("babel-types"); +},{"./printer":55,"./source-map":56}],52:[function(require,module,exports){ +"use strict"; -var t = _interopRequireWildcard(_babelTypes); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -var _values = require("lodash/values"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.needsWhitespace = needsWhitespace; +exports.needsWhitespaceBefore = needsWhitespaceBefore; +exports.needsWhitespaceAfter = needsWhitespaceAfter; +exports.needsParens = needsParens; -var _values2 = _interopRequireDefault(_values); +var whitespace = _interopRequireWildcard(require("./whitespace")); -var _extend = require("lodash/extend"); +var parens = _interopRequireWildcard(require("./parentheses")); -var _extend2 = _interopRequireDefault(_extend); +var t = _interopRequireWildcard(require("@babel/types")); -var _babelTemplate = require("babel-template"); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return cache; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -function ignoreBlock(path) { - return t.isLoop(path.parent) || t.isCatchClause(path.parent); -} + var cache = _getRequireWildcardCache(); -var buildRetCheck = (0, _babelTemplate2.default)("\n if (typeof RETURN === \"object\") return RETURN.v;\n"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } -function isBlockScoped(node) { - if (!t.isVariableDeclaration(node)) return false; - if (node[t.BLOCK_SCOPED_SYMBOL]) return true; - if (node.kind !== "let" && node.kind !== "const") return false; - return true; -} + var newObj = {}; -function convertBlockScopedToVar(path, node, parent, scope) { - var moveBindingsToParent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (!node) { - node = path.node; - } + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (!t.isFor(parent)) { - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - declar.init = declar.init || scope.buildUndefinedNode(); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } } } - node[t.BLOCK_SCOPED_SYMBOL] = true; - node.kind = "var"; + newObj.default = obj; - if (moveBindingsToParent) { - var parentScope = scope.getFunctionParent(); - var ids = path.getBindingIdentifiers(); - for (var name in ids) { - var binding = scope.getOwnBinding(name); - if (binding) binding.kind = "var"; - scope.moveBindingTo(name, parentScope); - } + if (cache) { + cache.set(obj, newObj); } -} -function isVar(node) { - return t.isVariableDeclaration(node, { kind: "var" }) && !isBlockScoped(node); + return newObj; } -var letReferenceBlockVisitor = _babelTraverse2.default.visitors.merge([{ - Loop: { - enter: function enter(path, state) { - state.loopDepth++; - }, - exit: function exit(path, state) { - state.loopDepth--; - } - }, - Function: function Function(path, state) { - if (state.loopDepth > 0) { - path.traverse(letReferenceFunctionVisitor, state); - } - return path.skip(); - } -}, _tdz.visitor]); - -var letReferenceFunctionVisitor = _babelTraverse2.default.visitors.merge([{ - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - var ref = state.letReferences[path.node.name]; - - if (!ref) return; - - var localBinding = path.scope.getBindingIdentifier(path.node.name); - if (localBinding && localBinding !== ref) return; +function expandAliases(obj) { + var newObj = {}; - state.closurify = true; + function add(type, func) { + var fn = newObj[type]; + newObj[type] = fn ? function (node, parent, stack) { + var result = fn(node, parent, stack); + return result == null ? func(node, parent, stack) : result; + } : func; } -}, _tdz.visitor]); -var hoistVarDeclarationsVisitor = { - enter: function enter(path, self) { - var node = path.node, - parent = path.parent; + for (var _i = 0, _Object$keys = Object.keys(obj); _i < _Object$keys.length; _i++) { + var type = _Object$keys[_i]; + var aliases = t.FLIPPED_ALIAS_KEYS[type]; + if (aliases) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (path.isForStatement()) { - if (isVar(node.init, node)) { - var nodes = self.pushDeclar(node.init); - if (nodes.length === 1) { - node.init = nodes[0]; - } else { - node.init = t.sequenceExpression(nodes); + try { + for (var _iterator = aliases[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var alias = _step.value; + add(alias, obj[type]); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } } - } else if (path.isFor()) { - if (isVar(node.left, node)) { - self.pushDeclar(node.left); - node.left = node.left.declarations[0].id; - } - } else if (isVar(node, parent)) { - path.replaceWithMultiple(self.pushDeclar(node).map(function (expr) { - return t.expressionStatement(expr); - })); - } else if (path.isFunction()) { - return path.skip(); + } else { + add(type, obj[type]); } } -}; -var loopLabelVisitor = { - LabeledStatement: function LabeledStatement(_ref, state) { - var node = _ref.node; + return newObj; +} - state.innerLabels.push(node.label.name); - } -}; +var expandedParens = expandAliases(parens); +var expandedWhitespaceNodes = expandAliases(whitespace.nodes); +var expandedWhitespaceList = expandAliases(whitespace.list); -var continuationVisitor = { - enter: function enter(path, state) { - if (path.isAssignmentExpression() || path.isUpdateExpression()) { - var bindings = path.getBindingIdentifiers(); - for (var name in bindings) { - if (state.outsideReferences[name] !== path.scope.getBindingIdentifier(name)) continue; - state.reassignments[name] = true; - } - } +function find(obj, node, parent, printStack) { + var fn = obj[node.type]; + return fn ? fn(node, parent, printStack) : null; +} + +function isOrHasCallExpression(node) { + if (t.isCallExpression(node)) { + return true; } -}; -function loopNodeTo(node) { - if (t.isBreakStatement(node)) { - return "break"; - } else if (t.isContinueStatement(node)) { - return "continue"; + if (t.isMemberExpression(node)) { + return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property); + } else { + return false; } } -var loopVisitor = { - Loop: function Loop(path, state) { - var oldIgnoreLabeless = state.ignoreLabeless; - state.ignoreLabeless = true; - path.traverse(loopVisitor, state); - state.ignoreLabeless = oldIgnoreLabeless; - path.skip(); - }, - Function: function Function(path) { - path.skip(); - }, - SwitchCase: function SwitchCase(path, state) { - var oldInSwitchCase = state.inSwitchCase; - state.inSwitchCase = true; - path.traverse(loopVisitor, state); - state.inSwitchCase = oldInSwitchCase; - path.skip(); - }, - "BreakStatement|ContinueStatement|ReturnStatement": function BreakStatementContinueStatementReturnStatement(path, state) { - var node = path.node, - parent = path.parent, - scope = path.scope; - - if (node[this.LOOP_IGNORE]) return; - - var replace = void 0; - var loopText = loopNodeTo(node); +function needsWhitespace(node, parent, type) { + if (!node) return 0; - if (loopText) { - if (node.label) { - if (state.innerLabels.indexOf(node.label.name) >= 0) { - return; - } + if (t.isExpressionStatement(node)) { + node = node.expression; + } - loopText = loopText + "|" + node.label.name; - } else { - if (state.ignoreLabeless) return; + var linesInfo = find(expandedWhitespaceNodes, node, parent); - if (state.inSwitchCase) return; + if (!linesInfo) { + var items = find(expandedWhitespaceList, node, parent); - if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return; + if (items) { + for (var i = 0; i < items.length; i++) { + linesInfo = needsWhitespace(items[i], node, type); + if (linesInfo) break; } - - state.hasBreakContinue = true; - state.map[loopText] = node; - replace = t.stringLiteral(loopText); - } - - if (path.isReturnStatement()) { - state.hasReturn = true; - replace = t.objectExpression([t.objectProperty(t.identifier("v"), node.argument || scope.buildUndefinedNode())]); } + } - if (replace) { - replace = t.returnStatement(replace); - replace[this.LOOP_IGNORE] = true; - path.skip(); - path.replaceWith(t.inherits(replace, node)); - } + if (_typeof(linesInfo) === "object" && linesInfo !== null) { + return linesInfo[type] || 0; } -}; -var BlockScoping = function () { - function BlockScoping(loopPath, blockPath, parent, scope, file) { - (0, _classCallCheck3.default)(this, BlockScoping); + return 0; +} - this.parent = parent; - this.scope = scope; - this.file = file; +function needsWhitespaceBefore(node, parent) { + return needsWhitespace(node, parent, "before"); +} - this.blockPath = blockPath; - this.block = blockPath.node; +function needsWhitespaceAfter(node, parent) { + return needsWhitespace(node, parent, "after"); +} - this.outsideLetReferences = (0, _create2.default)(null); - this.hasLetReferences = false; - this.letReferences = (0, _create2.default)(null); - this.body = []; +function needsParens(node, parent, printStack) { + if (!parent) return false; - if (loopPath) { - this.loopParent = loopPath.parent; - this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label; - this.loopPath = loopPath; - this.loop = loopPath.node; - } + if (t.isNewExpression(parent) && parent.callee === node) { + if (isOrHasCallExpression(node)) return true; } - BlockScoping.prototype.run = function run() { - var block = this.block; - if (block._letDone) return; - block._letDone = true; - - var needsClosure = this.getLetReferences(); + if (t.isLogicalExpression(node) && parent.operator === "??") return true; + return find(expandedParens, node, parent, printStack); +} - if (t.isFunction(this.parent) || t.isProgram(this.block)) { - this.updateScopeInfo(); - return; - } +},{"./parentheses":53,"./whitespace":54,"@babel/types":242}],53:[function(require,module,exports){ +"use strict"; - if (!this.hasLetReferences) return; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NullableTypeAnnotation = NullableTypeAnnotation; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.UpdateExpression = UpdateExpression; +exports.ObjectExpression = ObjectExpression; +exports.DoExpression = DoExpression; +exports.Binary = Binary; +exports.IntersectionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.TSAsExpression = TSAsExpression; +exports.TSTypeAssertion = TSTypeAssertion; +exports.TSIntersectionType = exports.TSUnionType = TSUnionType; +exports.BinaryExpression = BinaryExpression; +exports.SequenceExpression = SequenceExpression; +exports.AwaitExpression = exports.YieldExpression = YieldExpression; +exports.ClassExpression = ClassExpression; +exports.UnaryLike = UnaryLike; +exports.FunctionExpression = FunctionExpression; +exports.ArrowFunctionExpression = ArrowFunctionExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.OptionalMemberExpression = OptionalMemberExpression; +exports.AssignmentExpression = AssignmentExpression; +exports.NewExpression = NewExpression; - if (needsClosure) { - this.wrapClosure(); - } else { - this.remap(); - } +var t = _interopRequireWildcard(require("@babel/types")); - this.updateScopeInfo(needsClosure); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) { - return t.labeledStatement(this.loopLabel, this.loop); - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; - BlockScoping.prototype.updateScopeInfo = function updateScopeInfo(wrappedInClosure) { - var scope = this.scope; - var parentScope = scope.getFunctionParent(); - var letRefs = this.letReferences; + return cache; +} - for (var key in letRefs) { - var ref = letRefs[key]; - var binding = scope.getBinding(ref.name); - if (!binding) continue; - if (binding.kind === "let" || binding.kind === "const") { - binding.kind = "var"; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - if (wrappedInClosure) { - scope.removeBinding(ref.name); - } else { - scope.moveBindingTo(ref.name, parentScope); - } - } - } - }; + var cache = _getRequireWildcardCache(); - BlockScoping.prototype.remap = function remap() { - var letRefs = this.letReferences; - var scope = this.scope; + if (cache && cache.has(obj)) { + return cache.get(obj); + } - for (var key in letRefs) { - var ref = letRefs[key]; + var newObj = {}; - if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { - if (scope.hasOwnBinding(key)) scope.rename(ref.name); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (this.blockPath.scope.hasOwnBinding(key)) this.blockPath.scope.rename(ref.name); - } - } - }; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - BlockScoping.prototype.wrapClosure = function wrapClosure() { - if (this.file.opts.throwIfClosureRequired) { - throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure " + "(throwIfClosureRequired)."); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } } - var block = this.block; - - var outsideRefs = this.outsideLetReferences; + } - if (this.loop) { - for (var name in outsideRefs) { - var id = outsideRefs[name]; + newObj.default = obj; - if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) { - delete outsideRefs[id.name]; - delete this.letReferences[id.name]; + if (cache) { + cache.set(obj, newObj); + } - this.scope.rename(id.name); + return newObj; +} - this.letReferences[id.name] = id; - outsideRefs[id.name] = id; - } - } - } +var PRECEDENCE = { + "||": 0, + "&&": 1, + "|": 2, + "^": 3, + "&": 4, + "==": 5, + "===": 5, + "!=": 5, + "!==": 5, + "<": 6, + ">": 6, + "<=": 6, + ">=": 6, + in: 6, + instanceof: 6, + ">>": 7, + "<<": 7, + ">>>": 7, + "+": 8, + "-": 8, + "*": 9, + "/": 9, + "%": 9, + "**": 10 +}; - this.has = this.checkLoop(); +var isClassExtendsClause = function isClassExtendsClause(node, parent) { + return (t.isClassDeclaration(parent) || t.isClassExpression(parent)) && parent.superClass === node; +}; - this.hoistVarDeclarations(); +function NullableTypeAnnotation(node, parent) { + return t.isArrayTypeAnnotation(parent); +} - var params = (0, _values2.default)(outsideRefs); - var args = (0, _values2.default)(outsideRefs); +function FunctionTypeAnnotation(node, parent, printStack) { + return t.isUnionTypeAnnotation(parent) || t.isIntersectionTypeAnnotation(parent) || t.isArrayTypeAnnotation(parent) || t.isTypeAnnotation(parent) && t.isArrowFunctionExpression(printStack[printStack.length - 3]); +} - var isSwitch = this.blockPath.isSwitchStatement(); +function UpdateExpression(node, parent) { + return t.isMemberExpression(parent, { + object: node + }) || t.isCallExpression(parent, { + callee: node + }) || t.isNewExpression(parent, { + callee: node + }) || isClassExtendsClause(node, parent); +} - var fn = t.functionExpression(null, params, t.blockStatement(isSwitch ? [block] : block.body)); - fn.shadow = true; +function ObjectExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { + considerArrow: true + }); +} - this.addContinuations(fn); +function DoExpression(node, parent, printStack) { + return isFirstInStatement(printStack); +} - var ref = fn; +function Binary(node, parent) { + if (node.operator === "**" && t.isBinaryExpression(parent, { + operator: "**" + })) { + return parent.left === node; + } - if (this.loop) { - ref = this.scope.generateUidIdentifier("loop"); - this.loopPath.insertBefore(t.variableDeclaration("var", [t.variableDeclarator(ref, fn)])); - } + if (isClassExtendsClause(node, parent)) { + return true; + } - var call = t.callExpression(ref, args); - var ret = this.scope.generateUidIdentifier("ret"); + if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node || t.isUnaryLike(parent) || t.isMemberExpression(parent) && parent.object === node || t.isAwaitExpression(parent)) { + return true; + } - var hasYield = _babelTraverse2.default.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); - if (hasYield) { - fn.generator = true; - call = t.yieldExpression(call, true); - } + if (t.isBinary(parent)) { + var parentOp = parent.operator; + var parentPos = PRECEDENCE[parentOp]; + var nodeOp = node.operator; + var nodePos = PRECEDENCE[nodeOp]; - var hasAsync = _babelTraverse2.default.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); - if (hasAsync) { - fn.async = true; - call = t.awaitExpression(call); + if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent) || parentPos > nodePos) { + return true; } + } - this.buildClosure(ret, call); - - if (isSwitch) this.blockPath.replaceWithMultiple(this.body);else block.body = this.body; - }; + return false; +} - BlockScoping.prototype.buildClosure = function buildClosure(ret, call) { - var has = this.has; - if (has.hasReturn || has.hasBreakContinue) { - this.buildHas(ret, call); - } else { - this.body.push(t.expressionStatement(call)); - } - }; +function UnionTypeAnnotation(node, parent) { + return t.isArrayTypeAnnotation(parent) || t.isNullableTypeAnnotation(parent) || t.isIntersectionTypeAnnotation(parent) || t.isUnionTypeAnnotation(parent); +} - BlockScoping.prototype.addContinuations = function addContinuations(fn) { - var state = { - reassignments: {}, - outsideReferences: this.outsideLetReferences - }; +function TSAsExpression() { + return true; +} - this.scope.traverse(fn, continuationVisitor, state); +function TSTypeAssertion() { + return true; +} - for (var i = 0; i < fn.params.length; i++) { - var param = fn.params[i]; - if (!state.reassignments[param.name]) continue; +function TSUnionType(node, parent) { + return t.isTSArrayType(parent) || t.isTSOptionalType(parent) || t.isTSIntersectionType(parent) || t.isTSUnionType(parent) || t.isTSRestType(parent); +} - var newParam = this.scope.generateUidIdentifier(param.name); - fn.params[i] = newParam; +function BinaryExpression(node, parent) { + return node.operator === "in" && (t.isVariableDeclarator(parent) || t.isFor(parent)); +} - this.scope.rename(param.name, newParam.name, fn); +function SequenceExpression(node, parent) { + if (t.isForStatement(parent) || t.isThrowStatement(parent) || t.isReturnStatement(parent) || t.isIfStatement(parent) && parent.test === node || t.isWhileStatement(parent) && parent.test === node || t.isForInStatement(parent) && parent.right === node || t.isSwitchStatement(parent) && parent.discriminant === node || t.isExpressionStatement(parent) && parent.expression === node) { + return false; + } - fn.body.body.push(t.expressionStatement(t.assignmentExpression("=", param, newParam))); - } - }; + return true; +} - BlockScoping.prototype.getLetReferences = function getLetReferences() { - var _this = this; +function YieldExpression(node, parent) { + return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent) || t.isAwaitExpression(parent) && t.isYieldExpression(node) || t.isConditionalExpression(parent) && node === parent.test || isClassExtendsClause(node, parent); +} - var block = this.block; +function ClassExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { + considerDefaultExports: true + }); +} - var declarators = []; +function UnaryLike(node, parent) { + return t.isMemberExpression(parent, { + object: node + }) || t.isCallExpression(parent, { + callee: node + }) || t.isNewExpression(parent, { + callee: node + }) || t.isBinaryExpression(parent, { + operator: "**", + left: node + }) || isClassExtendsClause(node, parent); +} - if (this.loop) { - var init = this.loop.left || this.loop.init; - if (isBlockScoped(init)) { - declarators.push(init); - (0, _extend2.default)(this.outsideLetReferences, t.getBindingIdentifiers(init)); - } - } +function FunctionExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { + considerDefaultExports: true + }); +} - var addDeclarationsFromChild = function addDeclarationsFromChild(path, node) { - node = node || path.node; - if (t.isClassDeclaration(node) || t.isFunctionDeclaration(node) || isBlockScoped(node)) { - if (isBlockScoped(node)) { - convertBlockScopedToVar(path, node, block, _this.scope); - } - declarators = declarators.concat(node.declarations || node); - } - if (t.isLabeledStatement(node)) { - addDeclarationsFromChild(path.get("body"), node.body); - } - }; +function ArrowFunctionExpression(node, parent) { + return t.isExportDeclaration(parent) || ConditionalExpression(node, parent); +} - if (block.body) { - for (var i = 0; i < block.body.length; i++) { - var declarPath = this.blockPath.get("body")[i]; - addDeclarationsFromChild(declarPath); - } - } +function ConditionalExpression(node, parent) { + if (t.isUnaryLike(parent) || t.isBinary(parent) || t.isConditionalExpression(parent, { + test: node + }) || t.isAwaitExpression(parent) || t.isOptionalMemberExpression(parent) || t.isTaggedTemplateExpression(parent) || t.isTSTypeAssertion(parent) || t.isTSAsExpression(parent)) { + return true; + } - if (block.cases) { - for (var _i = 0; _i < block.cases.length; _i++) { - var consequents = block.cases[_i].consequent; + return UnaryLike(node, parent); +} - for (var j = 0; j < consequents.length; j++) { - var _declarPath = this.blockPath.get("cases")[_i]; - var declar = consequents[j]; - addDeclarationsFromChild(_declarPath, declar); - } - } - } +function OptionalMemberExpression(node, parent) { + return t.isCallExpression(parent) || t.isMemberExpression(parent); +} - for (var _i2 = 0; _i2 < declarators.length; _i2++) { - var _declar = declarators[_i2]; +function AssignmentExpression(node) { + if (t.isObjectPattern(node.left)) { + return true; + } else { + return ConditionalExpression.apply(void 0, arguments); + } +} - var keys = t.getBindingIdentifiers(_declar, false, true); - (0, _extend2.default)(this.letReferences, keys); - this.hasLetReferences = true; - } +function NewExpression(node, parent) { + return isClassExtendsClause(node, parent); +} - if (!this.hasLetReferences) return; +function isFirstInStatement(printStack) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$considerArrow = _ref.considerArrow, + considerArrow = _ref$considerArrow === void 0 ? false : _ref$considerArrow, + _ref$considerDefaultE = _ref.considerDefaultExports, + considerDefaultExports = _ref$considerDefaultE === void 0 ? false : _ref$considerDefaultE; - var state = { - letReferences: this.letReferences, - closurify: false, - file: this.file, - loopDepth: 0 - }; + var i = printStack.length - 1; + var node = printStack[i]; + i--; + var parent = printStack[i]; - var loopOrFunctionParent = this.blockPath.find(function (path) { - return path.isLoop() || path.isFunction(); - }); - if (loopOrFunctionParent && loopOrFunctionParent.isLoop()) { - state.loopDepth++; + while (i > 0) { + if (t.isExpressionStatement(parent, { + expression: node + }) || t.isTaggedTemplateExpression(parent) || considerDefaultExports && t.isExportDefaultDeclaration(parent, { + declaration: node + }) || considerArrow && t.isArrowFunctionExpression(parent, { + body: node + })) { + return true; } - this.blockPath.traverse(letReferenceBlockVisitor, state); - - return state.closurify; - }; + if (t.isCallExpression(parent, { + callee: node + }) || t.isSequenceExpression(parent) && parent.expressions[0] === node || t.isMemberExpression(parent, { + object: node + }) || t.isConditional(parent, { + test: node + }) || t.isBinary(parent, { + left: node + }) || t.isAssignmentExpression(parent, { + left: node + })) { + node = parent; + i--; + parent = printStack[i]; + } else { + return false; + } + } - BlockScoping.prototype.checkLoop = function checkLoop() { - var state = { - hasBreakContinue: false, - ignoreLabeless: false, - inSwitchCase: false, - innerLabels: [], - hasReturn: false, - isLoop: !!this.loop, - map: {}, - LOOP_IGNORE: (0, _symbol2.default)() - }; + return false; +} - this.blockPath.traverse(loopLabelVisitor, state); - this.blockPath.traverse(loopVisitor, state); +},{"@babel/types":242}],54:[function(require,module,exports){ +"use strict"; - return state; - }; +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - BlockScoping.prototype.hoistVarDeclarations = function hoistVarDeclarations() { - this.blockPath.traverse(hoistVarDeclarationsVisitor, this); - }; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - BlockScoping.prototype.pushDeclar = function pushDeclar(node) { - var declars = []; - var names = t.getBindingIdentifiers(node); - for (var name in names) { - declars.push(t.variableDeclarator(names[name])); - } +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - this.body.push(t.variableDeclaration(node.kind, declars)); +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - var replace = []; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.list = exports.nodes = void 0; - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - if (!declar.init) continue; +var t = _interopRequireWildcard(require("@babel/types")); - var expr = t.assignmentExpression("=", declar.id, declar.init); - replace.push(t.inherits(expr, declar)); - } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - return replace; + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; - BlockScoping.prototype.buildHas = function buildHas(ret, call) { - var body = this.body; + return cache; +} - body.push(t.variableDeclaration("var", [t.variableDeclarator(ret, call)])); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - var retCheck = void 0; - var has = this.has; - var cases = []; + var cache = _getRequireWildcardCache(); - if (has.hasReturn) { - retCheck = buildRetCheck({ - RETURN: ret - }); - } + if (cache && cache.has(obj)) { + return cache.get(obj); + } - if (has.hasBreakContinue) { - for (var key in has.map) { - cases.push(t.switchCase(t.stringLiteral(key), [has.map[key]])); - } + var newObj = {}; - if (has.hasReturn) { - cases.push(t.switchCase(null, [retCheck])); - } + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (cases.length === 1) { - var single = cases[0]; - body.push(t.ifStatement(t.binaryExpression("===", ret, single.test), single.consequent[0])); - } else { - if (this.loop) { - for (var i = 0; i < cases.length; i++) { - var caseConsequent = cases[i].consequent[0]; - if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) { - caseConsequent.label = this.loopLabel = this.loopLabel || this.scope.generateUidIdentifier("loop"); - } - } - } + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - body.push(t.switchStatement(ret, cases)); - } - } else { - if (has.hasReturn) { - body.push(retCheck); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } } - }; - - return BlockScoping; -}(); + } -module.exports = exports["default"]; -},{"./tdz":67,"babel-runtime/core-js/object/create":100,"babel-runtime/core-js/symbol":104,"babel-runtime/helpers/classCallCheck":109,"babel-template":114,"babel-traverse":118,"babel-types":151,"lodash/extend":473,"lodash/values":518}],67:[function(require,module,exports){ -"use strict"; + newObj.default = obj; -exports.__esModule = true; -exports.visitor = undefined; + if (cache) { + cache.set(obj, newObj); + } -var _babelTypes = require("babel-types"); + return newObj; +} -var t = _interopRequireWildcard(_babelTypes); +function crawl(node) { + var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (t.isMemberExpression(node)) { + crawl(node.object, state); + if (node.computed) crawl(node.property, state); + } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { + crawl(node.left, state); + crawl(node.right, state); + } else if (t.isCallExpression(node)) { + state.hasCall = true; + crawl(node.callee, state); + } else if (t.isFunction(node)) { + state.hasFunction = true; + } else if (t.isIdentifier(node)) { + state.hasHelper = state.hasHelper || isHelper(node.callee); + } -function getTDZStatus(refPath, bindingPath) { - var executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); + return state; +} - if (executionStatus === "before") { - return "inside"; - } else if (executionStatus === "after") { - return "outside"; +function isHelper(node) { + if (t.isMemberExpression(node)) { + return isHelper(node.object) || isHelper(node.property); + } else if (t.isIdentifier(node)) { + return node.name === "require" || node.name[0] === "_"; + } else if (t.isCallExpression(node)) { + return isHelper(node.callee); + } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { + return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); } else { - return "maybe"; + return false; } } -function buildTDZAssert(node, file) { - return t.callExpression(file.addHelper("temporalRef"), [node, t.stringLiteral(node.name), file.addHelper("temporalUndefined")]); -} - -function isReference(node, scope, state) { - var declared = state.letReferences[node.name]; - if (!declared) return false; - - return scope.getBindingIdentifier(node.name) === declared; +function isType(node) { + return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node); } -var visitor = exports.visitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (!this.file.opts.tdz) return; - - var node = path.node, - parent = path.parent, - scope = path.scope; - - - if (path.parentPath.isFor({ left: node })) return; - if (!isReference(node, scope, state)) return; - - var bindingPath = scope.getBinding(node.name).path; - - var status = getTDZStatus(path, bindingPath); - if (status === "inside") return; - - if (status === "maybe") { - var assert = buildTDZAssert(node, state.file); - - bindingPath.parent._tdzThis = true; - - path.skip(); +var nodes = { + AssignmentExpression: function AssignmentExpression(node) { + var state = crawl(node.right); - if (path.parentPath.isUpdateExpression()) { - if (parent._ignoreBlockScopingTDZ) return; - path.parentPath.replaceWith(t.sequenceExpression([assert, parent])); - } else { - path.replaceWith(assert); - } - } else if (status === "outside") { - path.replaceWith(t.throwStatement(t.inherits(t.newExpression(t.identifier("ReferenceError"), [t.stringLiteral(node.name + " is not defined - temporal dead zone")]), node))); + if (state.hasCall && state.hasHelper || state.hasFunction) { + return { + before: state.hasFunction, + after: true + }; } }, + SwitchCase: function SwitchCase(node, parent) { + return { + before: node.consequent.length || parent.cases[0] === node, + after: !node.consequent.length && parent.cases[parent.cases.length - 1] === node + }; + }, + LogicalExpression: function LogicalExpression(node) { + if (t.isFunction(node.left) || t.isFunction(node.right)) { + return { + after: true + }; + } + }, + Literal: function Literal(node) { + if (node.value === "use strict") { + return { + after: true + }; + } + }, + CallExpression: function CallExpression(node) { + if (t.isFunction(node.callee) || isHelper(node)) { + return { + before: true, + after: true + }; + } + }, + VariableDeclaration: function VariableDeclaration(node) { + for (var i = 0; i < node.declarations.length; i++) { + var declar = node.declarations[i]; + var enabled = isHelper(declar.id) && !isType(declar.init); - - AssignmentExpression: { - exit: function exit(path, state) { - if (!this.file.opts.tdz) return; - - var node = path.node; - - if (node._ignoreBlockScopingTDZ) return; - - var nodes = []; - var ids = path.getBindingIdentifiers(); - - for (var name in ids) { - var id = ids[name]; - - if (isReference(id, path.scope, state)) { - nodes.push(buildTDZAssert(id, state.file)); - } + if (!enabled) { + var state = crawl(declar.init); + enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; } - if (nodes.length) { - node._ignoreBlockScopingTDZ = true; - nodes.push(node); - path.replaceWithMultiple(nodes.map(t.expressionStatement)); + if (enabled) { + return { + before: true, + after: true + }; } } + }, + IfStatement: function IfStatement(node) { + if (t.isBlockStatement(node.consequent)) { + return { + before: true, + after: true + }; + } } }; -},{"babel-types":151}],68:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (_ref) { - var t = _ref.types; - - var VISITED = (0, _symbol2.default)(); - - return { - visitor: { - ExportDefaultDeclaration: function ExportDefaultDeclaration(path) { - if (!path.get("declaration").isClassDeclaration()) return; - - var node = path.node; - - var ref = node.declaration.id || path.scope.generateUidIdentifier("class"); - node.declaration.id = ref; - - path.replaceWith(node.declaration); - path.insertAfter(t.exportDefaultDeclaration(ref)); - }, - ClassDeclaration: function ClassDeclaration(path) { - var node = path.node; +exports.nodes = nodes; +nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (node, parent) { + if (parent.properties[0] === node) { + return { + before: true + }; + } +}; - var ref = node.id || path.scope.generateUidIdentifier("class"); +nodes.ObjectTypeCallProperty = function (node, parent) { + if (parent.callProperties[0] === node && (!parent.properties || !parent.properties.length)) { + return { + before: true + }; + } +}; - path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(ref, t.toExpression(node))])); - }, - ClassExpression: function ClassExpression(path, state) { - var node = path.node; +nodes.ObjectTypeIndexer = function (node, parent) { + if (parent.indexers[0] === node && (!parent.properties || !parent.properties.length) && (!parent.callProperties || !parent.callProperties.length)) { + return { + before: true + }; + } +}; - if (node[VISITED]) return; +nodes.ObjectTypeInternalSlot = function (node, parent) { + if (parent.internalSlots[0] === node && (!parent.properties || !parent.properties.length) && (!parent.callProperties || !parent.callProperties.length) && (!parent.indexers || !parent.indexers.length)) { + return { + before: true + }; + } +}; - var inferred = (0, _babelHelperFunctionName2.default)(path); - if (inferred && inferred !== node) return path.replaceWith(inferred); +var list = { + VariableDeclaration: function VariableDeclaration(node) { + return node.declarations.map(function (decl) { + return decl.init; + }); + }, + ArrayExpression: function ArrayExpression(node) { + return node.elements; + }, + ObjectExpression: function ObjectExpression(node) { + return node.properties; + } +}; +exports.list = list; +[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + type = _ref2[0], + amounts = _ref2[1]; - node[VISITED] = true; + if (typeof amounts === "boolean") { + amounts = { + after: amounts, + before: amounts + }; + } - var Constructor = _vanilla2.default; - if (state.opts.loose) Constructor = _loose2.default; + [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { + nodes[type] = function () { + return amounts; + }; + }); +}); - path.replaceWith(new Constructor(path, state.file).run()); - } - } - }; -}; +},{"@babel/types":242}],55:[function(require,module,exports){ +"use strict"; -var _loose = require("./loose"); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var _loose2 = _interopRequireDefault(_loose); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -var _vanilla = require("./vanilla"); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -var _vanilla2 = _interopRequireDefault(_vanilla); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; -var _babelHelperFunctionName = require("babel-helper-function-name"); +var _isInteger = _interopRequireDefault(require("lodash/isInteger")); -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); +var _repeat = _interopRequireDefault(require("lodash/repeat")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _buffer = _interopRequireDefault(require("./buffer")); -module.exports = exports["default"]; -},{"./loose":69,"./vanilla":70,"babel-helper-function-name":53,"babel-runtime/core-js/symbol":104}],69:[function(require,module,exports){ -"use strict"; +var n = _interopRequireWildcard(require("./node")); -exports.__esModule = true; +var t = _interopRequireWildcard(require("@babel/types")); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +var generatorFunctions = _interopRequireWildcard(require("./generators")); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + return cache; +} -var _inherits2 = require("babel-runtime/helpers/inherits"); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -var _inherits3 = _interopRequireDefault(_inherits2); + var cache = _getRequireWildcardCache(); -var _babelHelperFunctionName = require("babel-helper-function-name"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + var newObj = {}; -var _vanilla = require("./vanilla"); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -var _vanilla2 = _interopRequireDefault(_vanilla); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -var _babelTypes = require("babel-types"); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } -var t = _interopRequireWildcard(_babelTypes); + newObj.default = obj; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (cache) { + cache.set(obj, newObj); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return newObj; +} -var LooseClassTransformer = function (_VanillaTransformer) { - (0, _inherits3.default)(LooseClassTransformer, _VanillaTransformer); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - function LooseClassTransformer() { - (0, _classCallCheck3.default)(this, LooseClassTransformer); +var SCIENTIFIC_NOTATION = /e/i; +var ZERO_DECIMAL_INTEGER = /\.0+$/; +var NON_DECIMAL_LITERAL = /^0[box]/; - var _this = (0, _possibleConstructorReturn3.default)(this, _VanillaTransformer.apply(this, arguments)); +var Printer = +/*#__PURE__*/ +function () { + function Printer(format, map) { + _classCallCheck(this, Printer); - _this.isLoose = true; - return _this; + this.inForStatementInitCounter = 0; + this._printStack = []; + this._indent = 0; + this._insideAux = false; + this._printedCommentStarts = {}; + this._parenPushNewlineState = null; + this._noLineTerminator = false; + this._printAuxAfterOnNextUserNode = false; + this._printedComments = new WeakSet(); + this._endsWithInteger = false; + this._endsWithWord = false; + this.format = format || {}; + this._buf = new _buffer.default(map); } - LooseClassTransformer.prototype._processMethod = function _processMethod(node, scope) { - if (!node.decorators) { + _createClass(Printer, [{ + key: "generate", + value: function generate(ast) { + this.print(ast); - var classRef = this.classRef; - if (!node.static) classRef = t.memberExpression(classRef, t.identifier("prototype")); - var methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key)); + this._maybeAddAuxComment(); - var func = t.functionExpression(null, node.params, node.body, node.generator, node.async); - func.returnType = node.returnType; - var key = t.toComputedKey(node, node.key); - if (t.isStringLiteral(key)) { - func = (0, _babelHelperFunctionName2.default)({ - node: func, - id: key, - scope: scope - }); - } - - var expr = t.expressionStatement(t.assignmentExpression("=", methodName, func)); - t.inheritsComments(expr, node); - this.body.push(expr); - return true; + return this._buf.get(); } - }; - - return LooseClassTransformer; -}(_vanilla2.default); + }, { + key: "indent", + value: function indent() { + if (this.format.compact || this.format.concise) return; + this._indent++; + } + }, { + key: "dedent", + value: function dedent() { + if (this.format.compact || this.format.concise) return; + this._indent--; + } + }, { + key: "semicolon", + value: function semicolon() { + var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; -exports.default = LooseClassTransformer; -module.exports = exports["default"]; -},{"./vanilla":70,"babel-helper-function-name":53,"babel-runtime/helpers/classCallCheck":109,"babel-runtime/helpers/inherits":110,"babel-runtime/helpers/possibleConstructorReturn":112,"babel-types":151}],70:[function(require,module,exports){ -"use strict"; + this._maybeAddAuxComment(); -exports.__esModule = true; + this._append(";", !force); + } + }, { + key: "rightBrace", + value: function rightBrace() { + if (this.format.minified) { + this._buf.removeLastSemicolon(); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + this.token("}"); + } + }, { + key: "space", + value: function space() { + var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + if (this.format.compact) return; -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) { + this._space(); + } + } + }, { + key: "word", + value: function word(str) { + if (this._endsWithWord || this.endsWith("/") && str.indexOf("/") === 0) { + this._space(); + } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + this._maybeAddAuxComment(); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + this._append(str); -var _babelTraverse = require("babel-traverse"); + this._endsWithWord = true; + } + }, { + key: "number", + value: function number(str) { + this.word(str); + this._endsWithInteger = (0, _isInteger.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; + } + }, { + key: "token", + value: function token(str) { + if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) { + this._space(); + } -var _babelHelperReplaceSupers = require("babel-helper-replace-supers"); + this._maybeAddAuxComment(); -var _babelHelperReplaceSupers2 = _interopRequireDefault(_babelHelperReplaceSupers); + this._append(str); + } + }, { + key: "newline", + value: function newline(i) { + if (this.format.retainLines || this.format.compact) return; -var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); + if (this.format.concise) { + this.space(); + return; + } -var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); + if (this.endsWith("\n\n")) return; + if (typeof i !== "number") i = 1; + i = Math.min(2, i); + if (this.endsWith("{\n") || this.endsWith(":\n")) i--; + if (i <= 0) return; -var _babelHelperDefineMap = require("babel-helper-define-map"); + for (var j = 0; j < i; j++) { + this._newline(); + } + } + }, { + key: "endsWith", + value: function endsWith(str) { + return this._buf.endsWith(str); + } + }, { + key: "removeTrailingNewline", + value: function removeTrailingNewline() { + this._buf.removeTrailingNewline(); + } + }, { + key: "exactSource", + value: function exactSource(loc, cb) { + this._catchUp("start", loc); -var defineMap = _interopRequireWildcard(_babelHelperDefineMap); + this._buf.exactSource(loc, cb); + } + }, { + key: "source", + value: function source(prop, loc) { + this._catchUp(prop, loc); -var _babelTemplate = require("babel-template"); + this._buf.source(prop, loc); + } + }, { + key: "withSource", + value: function withSource(prop, loc, cb) { + this._catchUp(prop, loc); -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + this._buf.withSource(prop, loc, cb); + } + }, { + key: "_space", + value: function _space() { + this._append(" ", true); + } + }, { + key: "_newline", + value: function _newline() { + this._append("\n", true); + } + }, { + key: "_append", + value: function _append(str) { + var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; -var _babelTypes = require("babel-types"); + this._maybeAddParen(str); -var t = _interopRequireWildcard(_babelTypes); + this._maybeIndent(str); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (queue) this._buf.queue(str);else this._buf.append(str); + this._endsWithWord = false; + this._endsWithInteger = false; + } + }, { + key: "_maybeIndent", + value: function _maybeIndent(str) { + if (this._indent && this.endsWith("\n") && str[0] !== "\n") { + this._buf.queue(this._getIndent()); + } + } + }, { + key: "_maybeAddParen", + value: function _maybeAddParen(str) { + var parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + this._parenPushNewlineState = null; + var i; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (i = 0; i < str.length && str[i] === " "; i++) { + continue; + } -var buildDerivedConstructor = (0, _babelTemplate2.default)("\n (function () {\n super(...arguments);\n })\n"); + if (i === str.length) return; + var cha = str[i]; -var noMethodVisitor = { - "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { - if (!path.is("shadow")) { - path.skip(); - } - }, - Method: function Method(path) { - path.skip(); - } -}; + if (cha !== "\n") { + if (cha !== "/") return; + if (i + 1 === str.length) return; + var chaPost = str[i + 1]; + if (chaPost !== "/" && chaPost !== "*") return; + } -var verifyConstructorVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { - Super: function Super(path) { - if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) { - throw path.buildCodeFrameError("'super.*' is not allowed before super()"); + this.token("("); + this.indent(); + parenPushNewlineState.printed = true; } - }, - + }, { + key: "_catchUp", + value: function _catchUp(prop, loc) { + if (!this.format.retainLines) return; + var pos = loc ? loc[prop] : null; - CallExpression: { - exit: function exit(path) { - if (path.get("callee").isSuper()) { - this.hasBareSuper = true; + if (pos && pos.line !== null) { + var count = pos.line - this._buf.getCurrentLine(); - if (!this.isDerived) { - throw path.buildCodeFrameError("super() is only allowed in a derived constructor"); + for (var i = 0; i < count; i++) { + this._newline(); } } } - }, + }, { + key: "_getIndent", + value: function _getIndent() { + return (0, _repeat.default)(this.format.indent.style, this._indent); + } + }, { + key: "startTerminatorless", + value: function startTerminatorless() { + var isLabel = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - ThisExpression: function ThisExpression(path) { - if (this.isDerived && !this.hasBareSuper) { - if (!path.inShadow("this")) { - throw path.buildCodeFrameError("'this' is not allowed before super()"); + if (isLabel) { + this._noLineTerminator = true; + return null; + } else { + return this._parenPushNewlineState = { + printed: false + }; } } - } -}]); - -var findThisesVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { - ThisExpression: function ThisExpression(path) { - this.superThises.push(path); - } -}]); + }, { + key: "endTerminatorless", + value: function endTerminatorless(state) { + this._noLineTerminator = false; -var ClassTransformer = function () { - function ClassTransformer(path, file) { - (0, _classCallCheck3.default)(this, ClassTransformer); + if (state && state.printed) { + this.dedent(); + this.newline(); + this.token(")"); + } + } + }, { + key: "print", + value: function print(node, parent) { + var _this = this; - this.parent = path.parent; - this.scope = path.scope; - this.node = path.node; - this.path = path; - this.file = file; + if (!node) return; + var oldConcise = this.format.concise; - this.clearDescriptors(); + if (node._compact) { + this.format.concise = true; + } - this.instancePropBody = []; - this.instancePropRefs = {}; - this.staticPropBody = []; - this.body = []; + var printMethod = this[node.type]; - this.bareSuperAfter = []; - this.bareSupers = []; + if (!printMethod) { + throw new ReferenceError("unknown node of type ".concat(JSON.stringify(node.type), " with constructor ").concat(JSON.stringify(node && node.constructor.name))); + } - this.pushedConstructor = false; - this.pushedInherits = false; - this.isLoose = false; + this._printStack.push(node); - this.superThises = []; + var oldInAux = this._insideAux; + this._insideAux = !node.loc; - this.classId = this.node.id; + this._maybeAddAuxComment(this._insideAux && !oldInAux); - this.classRef = this.node.id ? t.identifier(this.node.id.name) : this.scope.generateUidIdentifier("class"); + var needsParens = n.needsParens(node, parent, this._printStack); - this.superName = this.node.superClass || t.identifier("Function"); - this.isDerived = !!this.node.superClass; - } + if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) { + needsParens = true; + } - ClassTransformer.prototype.run = function run() { - var _this = this; + if (needsParens) this.token("("); - var superName = this.superName; - var file = this.file; - var body = this.body; + this._printLeadingComments(node); - var constructorBody = this.constructorBody = t.blockStatement([]); - this.constructor = this.buildConstructor(); + var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; + this.withSource("start", loc, function () { + printMethod.call(_this, node, parent); + }); - var closureParams = []; - var closureArgs = []; + this._printTrailingComments(node); - if (this.isDerived) { - closureArgs.push(superName); + if (needsParens) this.token(")"); - superName = this.scope.generateUidIdentifierBasedOnNode(superName); - closureParams.push(superName); + this._printStack.pop(); - this.superName = superName; + this.format.concise = oldConcise; + this._insideAux = oldInAux; } + }, { + key: "_maybeAddAuxComment", + value: function _maybeAddAuxComment(enteredPositionlessNode) { + if (enteredPositionlessNode) this._printAuxBeforeComment(); + if (!this._insideAux) this._printAuxAfterComment(); + } + }, { + key: "_printAuxBeforeComment", + value: function _printAuxBeforeComment() { + if (this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = true; + var comment = this.format.auxiliaryCommentBefore; - this.buildBody(); - - constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("classCallCheck"), [t.thisExpression(), this.classRef]))); + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }); + } + } + }, { + key: "_printAuxAfterComment", + value: function _printAuxAfterComment() { + if (!this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = false; + var comment = this.format.auxiliaryCommentAfter; - body = body.concat(this.staticPropBody.map(function (fn) { - return fn(_this.classRef); - })); + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }); + } + } + }, { + key: "getPossibleRaw", + value: function getPossibleRaw(node) { + var extra = node.extra; - if (this.classId) { - if (body.length === 1) return t.toExpression(body[0]); + if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { + return extra.raw; + } } + }, { + key: "printJoin", + value: function printJoin(nodes, parent) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + if (!nodes || !nodes.length) return; + if (opts.indent) this.indent(); + var newlineOpts = { + addNewlines: opts.addNewlines + }; - body.push(t.returnStatement(this.classRef)); + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (!node) continue; + if (opts.statement) this._printNewline(true, node, parent, newlineOpts); + this.print(node, parent); - var container = t.functionExpression(null, closureParams, t.blockStatement(body)); - container.shadow = true; - return t.callExpression(container, closureArgs); - }; + if (opts.iterator) { + opts.iterator(node, i); + } - ClassTransformer.prototype.buildConstructor = function buildConstructor() { - var func = t.functionDeclaration(this.classRef, [], this.constructorBody); - t.inherits(func, this.node); - return func; - }; + if (opts.separator && i < nodes.length - 1) { + opts.separator.call(this); + } - ClassTransformer.prototype.pushToMap = function pushToMap(node, enumerable) { - var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "value"; - var scope = arguments[3]; + if (opts.statement) this._printNewline(false, node, parent, newlineOpts); + } - var mutatorMap = void 0; - if (node.static) { - this.hasStaticDescriptors = true; - mutatorMap = this.staticMutatorMap; - } else { - this.hasInstanceDescriptors = true; - mutatorMap = this.instanceMutatorMap; + if (opts.indent) this.dedent(); } - - var map = defineMap.push(mutatorMap, node, kind, this.file, scope); - - if (enumerable) { - map.enumerable = t.booleanLiteral(true); + }, { + key: "printAndIndentOnComments", + value: function printAndIndentOnComments(node, parent) { + var indent = node.leadingComments && node.leadingComments.length > 0; + if (indent) this.indent(); + this.print(node, parent); + if (indent) this.dedent(); } + }, { + key: "printBlock", + value: function printBlock(parent) { + var node = parent.body; - return map; - }; - - ClassTransformer.prototype.constructorMeMaybe = function constructorMeMaybe() { - var hasConstructor = false; - var paths = this.path.get("body.body"); - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + if (!t.isEmptyStatement(node)) { + this.space(); } - var path = _ref; - - hasConstructor = path.equals("kind", "constructor"); - if (hasConstructor) break; + this.print(node, parent); } - if (hasConstructor) return; + }, { + key: "_printTrailingComments", + value: function _printTrailingComments(node) { + this._printComments(this._getComments(false, node)); + } + }, { + key: "_printLeadingComments", + value: function _printLeadingComments(node) { + this._printComments(this._getComments(true, node)); + } + }, { + key: "printInnerComments", + value: function printInnerComments(node) { + var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + if (!node.innerComments || !node.innerComments.length) return; + if (indent) this.indent(); - var params = void 0, - body = void 0; + this._printComments(node.innerComments); - if (this.isDerived) { - var _constructor = buildDerivedConstructor().expression; - params = _constructor.params; - body = _constructor.body; - } else { - params = []; - body = t.blockStatement([]); + if (indent) this.dedent(); } + }, { + key: "printSequence", + value: function printSequence(nodes, parent) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + opts.statement = true; + return this.printJoin(nodes, parent, opts); + } + }, { + key: "printList", + value: function printList(items, parent) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - this.path.get("body").unshiftContainer("body", t.classMethod("constructor", t.identifier("constructor"), params, body)); - }; - - ClassTransformer.prototype.buildBody = function buildBody() { - this.constructorMeMaybe(); - this.pushBody(); - this.verifyConstructor(); + if (opts.separator == null) { + opts.separator = commaSeparator; + } - if (this.userConstructor) { - var constructorBody = this.constructorBody; - constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body); - t.inherits(this.constructor, this.userConstructor); - t.inherits(constructorBody, this.userConstructor.body); + return this.printJoin(items, parent, opts); } + }, { + key: "_printNewline", + value: function _printNewline(leading, node, parent, opts) { + if (this.format.retainLines || this.format.compact) return; - this.pushDescriptors(); - }; - - ClassTransformer.prototype.pushBody = function pushBody() { - var classBodyPaths = this.path.get("body.body"); + if (this.format.concise) { + this.space(); + return; + } - for (var _iterator2 = classBodyPaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + var lines = 0; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + if (this._buf.hasContent()) { + if (!leading) lines++; + if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; + var needs = leading ? n.needsWhitespaceBefore : n.needsWhitespaceAfter; + if (needs(node, parent)) lines++; } - var path = _ref2; + this.newline(lines); + } + }, { + key: "_getComments", + value: function _getComments(leading, node) { + return node && (leading ? node.leadingComments : node.trailingComments) || []; + } + }, { + key: "_printComment", + value: function _printComment(comment) { + var _this2 = this; - var node = path.node; + if (!this.format.shouldPrintComment(comment.value)) return; + if (comment.ignore) return; + if (this._printedComments.has(comment)) return; - if (path.isClassProperty()) { - throw path.buildCodeFrameError("Missing class properties transform."); - } + this._printedComments.add(comment); - if (node.decorators) { - throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one."); + if (comment.start != null) { + if (this._printedCommentStarts[comment.start]) return; + this._printedCommentStarts[comment.start] = true; } - if (t.isClassMethod(node)) { - var isConstructor = node.kind === "constructor"; + var isBlockComment = comment.type === "CommentBlock"; + this.newline(this._buf.hasContent() && !this._noLineTerminator && isBlockComment ? 1 : 0); + if (!this.endsWith("[") && !this.endsWith("{")) this.space(); + var val = !isBlockComment && !this._noLineTerminator ? "//".concat(comment.value, "\n") : "/*".concat(comment.value, "*/"); - if (isConstructor) { - path.traverse(verifyConstructorVisitor, this); + if (isBlockComment && this.format.indent.adjustMultilineComment) { + var offset = comment.loc && comment.loc.start.column; - if (!this.hasBareSuper && this.isDerived) { - throw path.buildCodeFrameError("missing super() call in constructor"); - } + if (offset) { + var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); + val = val.replace(newlineRegex, "\n"); } - var replaceSupers = new _babelHelperReplaceSupers2.default({ - forceSuperMemoisation: isConstructor, - methodPath: path, - methodNode: node, - objectRef: this.classRef, - superRef: this.superName, - isStatic: node.static, - isLoose: this.isLoose, - scope: this.scope, - file: this.file - }, true); + var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); + val = val.replace(/\n(?!$)/g, "\n".concat((0, _repeat.default)(" ", indentSize))); + } - replaceSupers.replace(); + if (this.endsWith("/")) this._space(); + this.withSource("start", comment.loc, function () { + _this2._append(val); + }); + this.newline(isBlockComment && !this._noLineTerminator ? 1 : 0); + } + }, { + key: "_printComments", + value: function _printComments(comments) { + if (!comments || !comments.length) return; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (isConstructor) { - this.pushConstructor(replaceSupers, node, path); - } else { - this.pushMethod(node, path); + try { + for (var _iterator = comments[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var comment = _step.value; + + this._printComment(comment); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } } } - }; - - ClassTransformer.prototype.clearDescriptors = function clearDescriptors() { - this.hasInstanceDescriptors = false; - this.hasStaticDescriptors = false; - - this.instanceMutatorMap = {}; - this.staticMutatorMap = {}; - }; - - ClassTransformer.prototype.pushDescriptors = function pushDescriptors() { - this.pushInherits(); + }]); - var body = this.body; + return Printer; +}(); - var instanceProps = void 0; - var staticProps = void 0; +exports.default = Printer; +Object.assign(Printer.prototype, generatorFunctions); - if (this.hasInstanceDescriptors) { - instanceProps = defineMap.toClassObject(this.instanceMutatorMap); - } +function commaSeparator() { + this.token(","); + this.space(); +} - if (this.hasStaticDescriptors) { - staticProps = defineMap.toClassObject(this.staticMutatorMap); - } +},{"./buffer":38,"./generators":43,"./node":52,"@babel/types":242,"lodash/isInteger":1021,"lodash/repeat":1039}],56:[function(require,module,exports){ +"use strict"; - if (instanceProps || staticProps) { - if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps); - if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - var nullNode = t.nullLiteral(); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var args = [this.classRef, nullNode, nullNode, nullNode, nullNode]; +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - if (instanceProps) args[1] = instanceProps; - if (staticProps) args[2] = staticProps; +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - if (this.instanceInitializersId) { - args[3] = this.instanceInitializersId; - body.unshift(this.buildObjectAssignment(this.instanceInitializersId)); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - if (this.staticInitializersId) { - args[4] = this.staticInitializersId; - body.unshift(this.buildObjectAssignment(this.staticInitializersId)); - } +var _sourceMap = _interopRequireDefault(require("source-map")); - var lastNonNullIndex = 0; - for (var i = 0; i < args.length; i++) { - if (args[i] !== nullNode) lastNonNullIndex = i; - } - args = args.slice(0, lastNonNullIndex + 1); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - body.push(t.expressionStatement(t.callExpression(this.file.addHelper("createClass"), args))); - } +var SourceMap = +/*#__PURE__*/ +function () { + function SourceMap(opts, code) { + _classCallCheck(this, SourceMap); - this.clearDescriptors(); - }; + this._cachedMap = null; + this._code = code; + this._opts = opts; + this._rawMappings = []; + } - ClassTransformer.prototype.buildObjectAssignment = function buildObjectAssignment(id) { - return t.variableDeclaration("var", [t.variableDeclarator(id, t.objectExpression([]))]); - }; + _createClass(SourceMap, [{ + key: "get", + value: function get() { + if (!this._cachedMap) { + var map = this._cachedMap = new _sourceMap.default.SourceMapGenerator({ + sourceRoot: this._opts.sourceRoot + }); + var code = this._code; - ClassTransformer.prototype.wrapSuperCall = function wrapSuperCall(bareSuper, superRef, thisRef, body) { - var bareSuperNode = bareSuper.node; + if (typeof code === "string") { + map.setSourceContent(this._opts.sourceFileName.replace(/\\/g, "/"), code); + } else if (_typeof(code) === "object") { + Object.keys(code).forEach(function (sourceFileName) { + map.setSourceContent(sourceFileName.replace(/\\/g, "/"), code[sourceFileName]); + }); + } - if (this.isLoose) { - bareSuperNode.arguments.unshift(t.thisExpression()); - if (bareSuperNode.arguments.length === 2 && t.isSpreadElement(bareSuperNode.arguments[1]) && t.isIdentifier(bareSuperNode.arguments[1].argument, { name: "arguments" })) { - bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument; - bareSuperNode.callee = t.memberExpression(superRef, t.identifier("apply")); - } else { - bareSuperNode.callee = t.memberExpression(superRef, t.identifier("call")); + this._rawMappings.forEach(function (mapping) { + return map.addMapping(mapping); + }, map); } - } else { - bareSuperNode = (0, _babelHelperOptimiseCallExpression2.default)(t.logicalExpression("||", t.memberExpression(this.classRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [this.classRef])), t.thisExpression(), bareSuperNode.arguments); + + return this._cachedMap.toJSON(); } + }, { + key: "getRawMappings", + value: function getRawMappings() { + return this._rawMappings.slice(); + } + }, { + key: "mark", + value: function mark(generatedLine, generatedColumn, line, column, identifierName, filename, force) { + if (this._lastGenLine !== generatedLine && line === null) return; - var call = t.callExpression(this.file.addHelper("possibleConstructorReturn"), [t.thisExpression(), bareSuperNode]); + if (!force && this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { + return; + } - var bareSuperAfter = this.bareSuperAfter.map(function (fn) { - return fn(thisRef); - }); + this._cachedMap = null; + this._lastGenLine = generatedLine; + this._lastSourceLine = line; + this._lastSourceColumn = column; - if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) { + this._rawMappings.push({ + name: identifierName || undefined, + generated: { + line: generatedLine, + column: generatedColumn + }, + source: line == null ? undefined : (filename || this._opts.sourceFileName).replace(/\\/g, "/"), + original: line == null ? undefined : { + line: line, + column: column + } + }); + } + }]); - if (this.superThises.length || bareSuperAfter.length) { - bareSuper.scope.push({ id: thisRef }); - call = t.assignmentExpression("=", thisRef, call); - } + return SourceMap; +}(); - if (bareSuperAfter.length) { - call = t.toSequenceExpression([call].concat(bareSuperAfter, [thisRef])); - } +exports.default = SourceMap; - bareSuper.parentPath.replaceWith(t.returnStatement(call)); - } else { - bareSuper.replaceWithMultiple([t.variableDeclaration("var", [t.variableDeclarator(thisRef, call)])].concat(bareSuperAfter, [t.expressionStatement(thisRef)])); - } - }; +},{"source-map":1081}],57:[function(require,module,exports){ +"use strict"; - ClassTransformer.prototype.verifyConstructor = function verifyConstructor() { - var _this2 = this; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = annotateAsPure; - if (!this.isDerived) return; +var t = _interopRequireWildcard(require("@babel/types")); - var path = this.userConstructorPath; - var body = path.get("body"); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - path.traverse(findThisesVisitor, this); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - var guaranteedSuperBeforeFinish = !!this.bareSupers.length; + return cache; +} - var superRef = this.superName || t.identifier("Function"); - var thisRef = path.scope.generateUidIdentifier("this"); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - for (var _iterator3 = this.bareSupers, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + var cache = _getRequireWildcardCache(); - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } + if (cache && cache.has(obj)) { + return cache.get(obj); + } - var bareSuper = _ref3; + var newObj = {}; - this.wrapSuperCall(bareSuper, superRef, thisRef, body); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (guaranteedSuperBeforeFinish) { - bareSuper.find(function (parentPath) { - if (parentPath === path) { - return true; - } + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (parentPath.isLoop() || parentPath.isConditional()) { - guaranteedSuperBeforeFinish = false; - return true; - } - }); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } } + } - for (var _iterator4 = this.superThises, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; + newObj.default = obj; - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } + if (cache) { + cache.set(obj, newObj); + } - var thisPath = _ref4; + return newObj; +} - thisPath.replaceWith(thisRef); - } +var PURE_ANNOTATION = "#__PURE__"; - var wrapReturn = function wrapReturn(returnArg) { - return t.callExpression(_this2.file.addHelper("possibleConstructorReturn"), [thisRef].concat(returnArg || [])); - }; +var isPureAnnotated = function isPureAnnotated(_ref) { + var leadingComments = _ref.leadingComments; + return !!leadingComments && leadingComments.some(function (comment) { + return /[@#]__PURE__/.test(comment.value); + }); +}; - var bodyPaths = body.get("body"); - if (bodyPaths.length && !bodyPaths.pop().isReturnStatement()) { - body.pushContainer("body", t.returnStatement(guaranteedSuperBeforeFinish ? thisRef : wrapReturn())); - } +function annotateAsPure(pathOrNode) { + var node = pathOrNode.node || pathOrNode; - for (var _iterator5 = this.superReturns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; + if (isPureAnnotated(node)) { + return; + } - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } + t.addComment(node, "leading", PURE_ANNOTATION); +} - var returnPath = _ref5; +},{"@babel/types":242}],58:[function(require,module,exports){ +"use strict"; - if (returnPath.node.argument) { - var ref = returnPath.scope.generateDeclaredUidIdentifier("ret"); - returnPath.get("argument").replaceWithMultiple([t.assignmentExpression("=", ref, returnPath.node.argument), wrapReturn(ref)]); - } else { - returnPath.get("argument").replaceWith(wrapReturn()); - } - } - }; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; - ClassTransformer.prototype.pushMethod = function pushMethod(node, path) { - var scope = path ? path.scope : this.scope; +var _helperExplodeAssignableExpression = _interopRequireDefault(require("@babel/helper-explode-assignable-expression")); - if (node.kind === "method") { - if (this._processMethod(node, scope)) return; - } +var t = _interopRequireWildcard(require("@babel/types")); - this.pushToMap(node, false, null, scope); - }; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - ClassTransformer.prototype._processMethod = function _processMethod() { - return false; + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; - ClassTransformer.prototype.pushConstructor = function pushConstructor(replaceSupers, method, path) { - this.bareSupers = replaceSupers.bareSupers; - this.superReturns = replaceSupers.returns; + return cache; +} - if (path.scope.hasOwnBinding(this.classRef.name)) { - path.scope.rename(this.classRef.name); - } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - var construct = this.constructor; + var cache = _getRequireWildcardCache(); - this.userConstructorPath = path; - this.userConstructor = method; - this.hasConstructor = true; + if (cache && cache.has(obj)) { + return cache.get(obj); + } - t.inheritsComments(construct, method); + var newObj = {}; - construct._ignoreUserWhitespace = true; - construct.params = method.params; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - t.inherits(construct.body, method.body); - construct.body.directives = method.body.directives; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - this._pushConstructor(); - }; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } - ClassTransformer.prototype._pushConstructor = function _pushConstructor() { - if (this.pushedConstructor) return; - this.pushedConstructor = true; + newObj.default = obj; - if (this.hasInstanceDescriptors || this.hasStaticDescriptors) { - this.pushDescriptors(); - } + if (cache) { + cache.set(obj, newObj); + } - this.body.push(this.constructor); + return newObj; +} - this.pushInherits(); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - ClassTransformer.prototype.pushInherits = function pushInherits() { - if (!this.isDerived || this.pushedInherits) return; +function _default(opts) { + var build = opts.build, + operator = opts.operator; + return { + AssignmentExpression: function AssignmentExpression(path) { + var node = path.node, + scope = path.scope; + if (node.operator !== operator + "=") return; + var nodes = []; + var exploded = (0, _helperExplodeAssignableExpression.default)(node.left, nodes, this, scope); + nodes.push(t.assignmentExpression("=", exploded.ref, build(exploded.uid, node.right))); + path.replaceWith(t.sequenceExpression(nodes)); + }, + BinaryExpression: function BinaryExpression(path) { + var node = path.node; - this.pushedInherits = true; - this.body.unshift(t.expressionStatement(t.callExpression(this.file.addHelper("inherits"), [this.classRef, this.superName]))); + if (node.operator === operator) { + path.replaceWith(build(node.left, node.right)); + } + } }; +} - return ClassTransformer; -}(); - -exports.default = ClassTransformer; -module.exports = exports["default"]; -},{"babel-helper-define-map":52,"babel-helper-optimise-call-expression":56,"babel-helper-replace-supers":58,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-template":114,"babel-traverse":118,"babel-types":151}],71:[function(require,module,exports){ +},{"@babel/helper-explode-assignable-expression":65,"@babel/types":242}],59:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _helperHoistVariables = _interopRequireDefault(require("@babel/helper-hoist-variables")); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var t = _interopRequireWildcard(require("@babel/types")); -exports.default = function (_ref) { - var t = _ref.types, - template = _ref.template; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - var buildMutatorMapAssign = template("\n MUTATOR_MAP_REF[KEY] = MUTATOR_MAP_REF[KEY] || {};\n MUTATOR_MAP_REF[KEY].KIND = VALUE;\n "); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - function getValue(prop) { - if (t.isObjectProperty(prop)) { - return prop.value; - } else if (t.isObjectMethod(prop)) { - return t.functionExpression(null, prop.params, prop.body, prop.generator, prop.async); - } - } + return cache; +} - function pushAssign(objId, prop, body) { - if (prop.kind === "get" && prop.kind === "set") { - pushMutatorDefine(objId, prop, body); - } else { - body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(objId, prop.key, prop.computed || t.isLiteral(prop.key)), getValue(prop)))); - } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; } - function pushMutatorDefine(_ref2, prop) { - var objId = _ref2.objId, - body = _ref2.body, - getMutatorId = _ref2.getMutatorId, - scope = _ref2.scope; - - var key = !prop.computed && t.isIdentifier(prop.key) ? t.stringLiteral(prop.key.name) : prop.key; - - var maybeMemoise = scope.maybeGenerateMemoised(key); - if (maybeMemoise) { - body.push(t.expressionStatement(t.assignmentExpression("=", maybeMemoise, key))); - key = maybeMemoise; - } + var cache = _getRequireWildcardCache(); - body.push.apply(body, buildMutatorMapAssign({ - MUTATOR_MAP_REF: getMutatorId(), - KEY: key, - VALUE: getValue(prop), - KIND: t.identifier(prop.kind) - })); + if (cache && cache.has(obj)) { + return cache.get(obj); } - function loose(info) { - for (var _iterator = info.computedProps, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref3; + var newObj = {}; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref3 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref3 = _i.value; - } + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - var prop = _ref3; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (prop.kind === "get" || prop.kind === "set") { - pushMutatorDefine(info, prop); - } else { - pushAssign(info.objId, prop, info.body); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } } } - function spec(info) { - var objId = info.objId, - body = info.body, - computedProps = info.computedProps, - state = info.state; - + newObj.default = obj; - for (var _iterator2 = computedProps, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref4; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref4 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref4 = _i2.value; - } + if (cache) { + cache.set(obj, newObj); + } - var prop = _ref4; + return newObj; +} - var key = t.toComputedKey(prop); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - if (prop.kind === "get" || prop.kind === "set") { - pushMutatorDefine(info, prop); - } else if (t.isStringLiteral(key, { value: "__proto__" })) { - pushAssign(objId, prop, body); - } else { - if (computedProps.length === 1) { - return t.callExpression(state.addHelper("defineProperty"), [info.initPropExpression, key, getValue(prop)]); - } else { - body.push(t.expressionStatement(t.callExpression(state.addHelper("defineProperty"), [objId, key, getValue(prop)]))); - } - } +var visitor = { + enter: function enter(path, state) { + if (path.isThisExpression()) { + state.foundThis = true; } - } - - return { - visitor: { - ObjectExpression: { - exit: function exit(path, state) { - var node = path.node, - parent = path.parent, - scope = path.scope; - - var hasComputed = false; - for (var _iterator3 = node.properties, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref5; - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref5 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref5 = _i3.value; - } + if (path.isReferencedIdentifier({ + name: "arguments" + })) { + state.foundArguments = true; + } + }, + Function: function Function(path) { + path.skip(); + } +}; - var prop = _ref5; +function _default(path) { + var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : path.scope; + var node = path.node; + var container = t.functionExpression(null, [], node.body, node.generator, node.async); + var callee = container; + var args = []; + (0, _helperHoistVariables.default)(path, function (id) { + return scope.push({ + id: id + }); + }); + var state = { + foundThis: false, + foundArguments: false + }; + path.traverse(visitor, state); - hasComputed = prop.computed === true; - if (hasComputed) break; - } - if (!hasComputed) return; + if (state.foundArguments || state.foundThis) { + callee = t.memberExpression(container, t.identifier("apply")); + args = []; - var initProps = []; - var computedProps = []; - var foundComputed = false; + if (state.foundThis) { + args.push(t.thisExpression()); + } - for (var _iterator4 = node.properties, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref6; + if (state.foundArguments) { + if (!state.foundThis) args.push(t.nullLiteral()); + args.push(t.identifier("arguments")); + } + } - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref6 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref6 = _i4.value; - } + var call = t.callExpression(callee, args); + if (node.generator) call = t.yieldExpression(call, true); + return t.returnStatement(call); +} - var _prop = _ref6; +},{"@babel/helper-hoist-variables":68,"@babel/types":242}],60:[function(require,module,exports){ +"use strict"; - if (_prop.computed) { - foundComputed = true; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.enableFeature = enableFeature; +exports.hasFeature = hasFeature; +exports.runtimeKey = exports.featuresKey = exports.FEATURES = void 0; +var FEATURES = Object.freeze({ + unicodeFlag: 1 << 0, + dotAllFlag: 1 << 1, + unicodePropertyEscape: 1 << 2, + namedCaptureGroups: 1 << 3 +}); +exports.FEATURES = FEATURES; +var featuresKey = "@babel/plugin-regexp-features/featuresKey"; +exports.featuresKey = featuresKey; +var runtimeKey = "@babel/plugin-regexp-features/runtimeKey"; +exports.runtimeKey = runtimeKey; - if (foundComputed) { - computedProps.push(_prop); - } else { - initProps.push(_prop); - } - } +function enableFeature(features, feature) { + return features | feature; +} - var objId = scope.generateUidIdentifierBasedOnNode(parent); - var initPropExpression = t.objectExpression(initProps); - var body = []; +function hasFeature(features, feature) { + return !!(features & feature); +} - body.push(t.variableDeclaration("var", [t.variableDeclarator(objId, initPropExpression)])); +},{}],61:[function(require,module,exports){ +"use strict"; - var callback = spec; - if (state.opts.loose) callback = loose; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createRegExpFeaturePlugin = createRegExpFeaturePlugin; - var mutatorRef = void 0; +var _regexpuCore = _interopRequireDefault(require("regexpu-core")); - var getMutatorId = function getMutatorId() { - if (!mutatorRef) { - mutatorRef = scope.generateUidIdentifier("mutatorMap"); +var _features = require("./features"); - body.push(t.variableDeclaration("var", [t.variableDeclarator(mutatorRef, t.objectExpression([]))])); - } +var _util = require("./util"); - return mutatorRef; - }; +var _package = _interopRequireDefault(require("../package.json")); - var single = callback({ - scope: scope, - objId: objId, - body: body, - computedProps: computedProps, - initPropExpression: initPropExpression, - getMutatorId: getMutatorId, - state: state - }); +var _core = require("@babel/core"); - if (mutatorRef) { - body.push(t.expressionStatement(t.callExpression(state.addHelper("defineEnumerableProperties"), [objId, mutatorRef]))); - } +var _helperRegex = require("@babel/helper-regex"); - if (single) { - path.replaceWith(single); - } else { - body.push(t.expressionStatement(objId)); - path.replaceWithMultiple(body); - } - } - } - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; -}; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],72:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; +} -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +var version = _package.default.version.split(".").reduce(function (v, x) { + return v * 1e5 + +x; +}, 0); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +var versionKey = "@babel/plugin-regexp-features/version"; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function createRegExpFeaturePlugin(_ref) { + var name = _ref.name, + feature = _ref.feature, + _ref$options = _ref.options, + options = _ref$options === void 0 ? {} : _ref$options; + return { + name: name, + pre: function pre() { + var _file$get; -var _getIterator3 = _interopRequireDefault(_getIterator2); + var file = this.file; + var features = (_file$get = file.get(_features.featuresKey)) !== null && _file$get !== void 0 ? _file$get : 0; + var newFeatures = (0, _features.enableFeature)(features, _features.FEATURES[feature]); + var useUnicodeFlag = options.useUnicodeFlag, + _options$runtime = options.runtime, + runtime = _options$runtime === void 0 ? true : _options$runtime; -exports.default = function (_ref) { - var t = _ref.types; + if (useUnicodeFlag === false) { + newFeatures = (0, _features.enableFeature)(newFeatures, _features.FEATURES.unicodeFlag); + } + if (newFeatures !== features) { + file.set(_features.featuresKey, newFeatures); + } - function variableDeclarationHasPattern(node) { - for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; + if (!runtime) { + file.set(_features.runtimeKey, false); + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; + if (!file.has(versionKey) || file.get(versionKey) < version) { + file.set(versionKey, version); } + }, + visitor: { + RegExpLiteral: function RegExpLiteral(path) { + var _file$get2; - var declar = _ref2; + var node = path.node; + var file = this.file; + var features = file.get(_features.featuresKey); + var runtime = (_file$get2 = file.get(_features.runtimeKey)) !== null && _file$get2 !== void 0 ? _file$get2 : true; + var regexpuOptions = (0, _util.generateRegexpuOptions)(node, features); - if (t.isPattern(declar.id)) { - return true; - } - } - return false; - } + if (regexpuOptions === null) { + return; + } - function hasRest(pattern) { - for (var _iterator2 = pattern.elements, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; + var namedCaptureGroups = {}; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } + if (regexpuOptions.namedGroup) { + regexpuOptions.onNamedGroup = function (name, index) { + namedCaptureGroups[name] = index; + }; + } - var elem = _ref3; + node.pattern = (0, _regexpuCore.default)(node.pattern, node.flags, regexpuOptions); - if (t.isRestElement(elem)) { - return true; - } - } - return false; - } + if (regexpuOptions.namedGroup && Object.keys(namedCaptureGroups).length > 0 && runtime && !isRegExpTest(path)) { + path.replaceWith(_core.types.callExpression(this.addHelper("wrapRegExp"), [node, _core.types.valueToNode(namedCaptureGroups)])); + } + + if ((0, _features.hasFeature)(features, _features.FEATURES.unicodeFlag)) { + (0, _helperRegex.pullFlag)(node, "u"); + } - var arrayUnpackVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (state.bindings[path.node.name]) { - state.deopt = true; - path.stop(); + if ((0, _features.hasFeature)(features, _features.FEATURES.dotAllFlag)) { + (0, _helperRegex.pullFlag)(node, "s"); + } } } }; +} - var DestructuringTransformer = function () { - function DestructuringTransformer(opts) { - (0, _classCallCheck3.default)(this, DestructuringTransformer); - - this.blockHoist = opts.blockHoist; - this.operator = opts.operator; - this.arrays = {}; - this.nodes = opts.nodes || []; - this.scope = opts.scope; - this.file = opts.file; - this.kind = opts.kind; - } - - DestructuringTransformer.prototype.buildVariableAssignment = function buildVariableAssignment(id, init) { - var op = this.operator; - if (t.isMemberExpression(id)) op = "="; - - var node = void 0; +function isRegExpTest(path) { + return path.parentPath.isMemberExpression({ + object: path.node, + computed: false + }) && path.parentPath.get("property").isIdentifier({ + name: "test" + }); +} - if (op) { - node = t.expressionStatement(t.assignmentExpression(op, id, init)); - } else { - node = t.variableDeclaration(this.kind, [t.variableDeclarator(id, init)]); - } +},{"../package.json":63,"./features":60,"./util":62,"@babel/core":19,"@babel/helper-regex":80,"regexpu-core":1066}],62:[function(require,module,exports){ +"use strict"; - node._blockHoist = this.blockHoist; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.generateRegexpuOptions = generateRegexpuOptions; - return node; - }; +var _features = require("./features"); - DestructuringTransformer.prototype.buildVariableDeclaration = function buildVariableDeclaration(id, init) { - var declar = t.variableDeclaration("var", [t.variableDeclarator(id, init)]); - declar._blockHoist = this.blockHoist; - return declar; - }; +function generateRegexpuOptions(node, features) { + var useUnicodeFlag = false, + dotAllFlag = false, + unicodePropertyEscape = false, + namedGroup = false; + var flags = node.flags, + pattern = node.pattern; + var flagsIncludesU = flags.includes("u"); - DestructuringTransformer.prototype.push = function push(id, init) { - if (t.isObjectPattern(id)) { - this.pushObjectPattern(id, init); - } else if (t.isArrayPattern(id)) { - this.pushArrayPattern(id, init); - } else if (t.isAssignmentPattern(id)) { - this.pushAssignmentPattern(id, init); - } else { - this.nodes.push(this.buildVariableAssignment(id, init)); - } - }; + if (flagsIncludesU) { + if (!(0, _features.hasFeature)(features, _features.FEATURES.unicodeFlag)) { + useUnicodeFlag = true; + } - DestructuringTransformer.prototype.toArray = function toArray(node, count) { - if (this.file.opts.loose || t.isIdentifier(node) && this.arrays[node.name]) { - return node; - } else { - return this.scope.toArray(node, count); - } - }; + if ((0, _features.hasFeature)(features, _features.FEATURES.unicodePropertyEscape) && /\\[pP]{/.test(pattern)) { + unicodePropertyEscape = true; + } + } - DestructuringTransformer.prototype.pushAssignmentPattern = function pushAssignmentPattern(pattern, valueRef) { + if ((0, _features.hasFeature)(features, _features.FEATURES.dotAllFlag) && flags.indexOf("s") >= 0) { + dotAllFlag = true; + } - var tempValueRef = this.scope.generateUidIdentifierBasedOnNode(valueRef); + if ((0, _features.hasFeature)(features, _features.FEATURES.namedCaptureGroups) && /\(\?<(?![=!])/.test(pattern)) { + namedGroup = true; + } - var declar = t.variableDeclaration("var", [t.variableDeclarator(tempValueRef, valueRef)]); - declar._blockHoist = this.blockHoist; - this.nodes.push(declar); + if (!namedGroup && !unicodePropertyEscape && !dotAllFlag && (!flagsIncludesU || useUnicodeFlag)) { + return null; + } - var tempConditional = t.conditionalExpression(t.binaryExpression("===", tempValueRef, t.identifier("undefined")), pattern.right, tempValueRef); + if (flagsIncludesU && flags.indexOf("s") >= 0) { + dotAllFlag = true; + } - var left = pattern.left; - if (t.isPattern(left)) { - var tempValueDefault = t.expressionStatement(t.assignmentExpression("=", tempValueRef, tempConditional)); - tempValueDefault._blockHoist = this.blockHoist; + return { + useUnicodeFlag: useUnicodeFlag, + onNamedGroup: function onNamedGroup() {}, + namedGroup: namedGroup, + unicodePropertyEscape: unicodePropertyEscape, + dotAllFlag: dotAllFlag, + lookbehind: true + }; +} - this.nodes.push(tempValueDefault); - this.push(left, tempValueRef); - } else { - this.nodes.push(this.buildVariableAssignment(left, tempConditional)); - } - }; +},{"./features":60}],63:[function(require,module,exports){ +module.exports={ + "_from": "@babel/helper-create-regexp-features-plugin@^7.7.0", + "_id": "@babel/helper-create-regexp-features-plugin@7.7.2", + "_inBundle": false, + "_integrity": "sha512-pAil/ZixjTlrzNpjx+l/C/wJk002Wo7XbbZ8oujH/AoJ3Juv0iN/UTcPUHXKMFLqsfS0Hy6Aow8M31brUYBlQQ==", + "_location": "/@babel/helper-create-regexp-features-plugin", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/helper-create-regexp-features-plugin@^7.7.0", + "name": "@babel/helper-create-regexp-features-plugin", + "escapedName": "@babel%2fhelper-create-regexp-features-plugin", + "scope": "@babel", + "rawSpec": "^7.7.0", + "saveSpec": null, + "fetchSpec": "^7.7.0" + }, + "_requiredBy": [ + "/@babel/plugin-proposal-unicode-property-regex", + "/@babel/plugin-transform-dotall-regex", + "/@babel/plugin-transform-named-capturing-groups-regex", + "/@babel/plugin-transform-unicode-regex" + ], + "_resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.7.2.tgz", + "_shasum": "6f20443778c8fce2af2ff4206284afc0ced65db6", + "_spec": "@babel/helper-create-regexp-features-plugin@^7.7.0", + "_where": "/local/home/ossman/devel/noVNC/node_modules/@babel/plugin-proposal-unicode-property-regex", + "author": { + "name": "The Babel Team", + "url": "https://babeljs.io/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@babel/helper-regex": "^7.4.4", + "regexpu-core": "^4.6.0" + }, + "deprecated": false, + "description": "Compile ESNext Regular Expressions to ES5", + "devDependencies": { + "@babel/core": "^7.7.2", + "@babel/helper-plugin-test-runner": "^7.0.0" + }, + "gitHead": "35f4d1276310bac6fede4a6f86a5c76f951e179e", + "homepage": "https://github.com/babel/babel#readme", + "keywords": [ + "babel", + "babel-plugin" + ], + "license": "MIT", + "main": "lib/index.js", + "name": "@babel/helper-create-regexp-features-plugin", + "peerDependencies": { + "@babel/core": "^7.0.0" + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-helper-create-regexp-features-plugin" + }, + "version": "7.7.2" +} - DestructuringTransformer.prototype.pushObjectRest = function pushObjectRest(pattern, objRef, spreadProp, spreadPropIndex) { +},{}],64:[function(require,module,exports){ +"use strict"; - var keys = []; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.push = push; +exports.hasComputed = hasComputed; +exports.toComputedObjectFromClass = toComputedObjectFromClass; +exports.toClassObject = toClassObject; +exports.toDefineObject = toDefineObject; - for (var i = 0; i < pattern.properties.length; i++) { - var prop = pattern.properties[i]; +var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name")); - if (i >= spreadPropIndex) break; +var _has = _interopRequireDefault(require("lodash/has")); - if (t.isRestProperty(prop)) continue; +var t = _interopRequireWildcard(require("@babel/types")); - var key = prop.key; - if (t.isIdentifier(key) && !prop.computed) key = t.stringLiteral(prop.key.name); - keys.push(key); - } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - keys = t.arrayExpression(keys); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - var value = t.callExpression(this.file.addHelper("objectWithoutProperties"), [objRef, keys]); - this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value)); - }; + return cache; +} - DestructuringTransformer.prototype.pushObjectProperty = function pushObjectProperty(prop, propRef) { - if (t.isLiteral(prop.key)) prop.computed = true; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - var pattern = prop.value; - var objRef = t.memberExpression(propRef, prop.key, prop.computed); + var cache = _getRequireWildcardCache(); - if (t.isPattern(pattern)) { - this.push(pattern, objRef); - } else { - this.nodes.push(this.buildVariableAssignment(pattern, objRef)); - } - }; + if (cache && cache.has(obj)) { + return cache.get(obj); + } - DestructuringTransformer.prototype.pushObjectPattern = function pushObjectPattern(pattern, objRef) { + var newObj = {}; - if (!pattern.properties.length) { - this.nodes.push(t.expressionStatement(t.callExpression(this.file.addHelper("objectDestructuringEmpty"), [objRef]))); - } + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (pattern.properties.length > 1 && !this.scope.isStatic(objRef)) { - var temp = this.scope.generateUidIdentifierBasedOnNode(objRef); - this.nodes.push(this.buildVariableDeclaration(temp, objRef)); - objRef = temp; - } + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - for (var i = 0; i < pattern.properties.length; i++) { - var prop = pattern.properties[i]; - if (t.isRestProperty(prop)) { - this.pushObjectRest(pattern, objRef, prop, i); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); } else { - this.pushObjectProperty(prop, objRef); + newObj[key] = obj[key]; } } - }; - - DestructuringTransformer.prototype.canUnpackArrayPattern = function canUnpackArrayPattern(pattern, arr) { - if (!t.isArrayExpression(arr)) return false; + } + } - if (pattern.elements.length > arr.elements.length) return; - if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false; + newObj.default = obj; - for (var _iterator3 = pattern.elements, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref4; + if (cache) { + cache.set(obj, newObj); + } - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } + return newObj; +} - var elem = _ref4; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - if (!elem) return false; +function toKind(node) { + if (t.isClassMethod(node) || t.isObjectMethod(node)) { + if (node.kind === "get" || node.kind === "set") { + return node.kind; + } + } - if (t.isMemberExpression(elem)) return false; - } + return "value"; +} - for (var _iterator4 = arr.elements, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref5; +function push(mutatorMap, node, kind, file, scope) { + var alias = t.toKeyAlias(node); + var map = {}; + if ((0, _has.default)(mutatorMap, alias)) map = mutatorMap[alias]; + mutatorMap[alias] = map; + map._inherits = map._inherits || []; - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref5 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref5 = _i4.value; - } + map._inherits.push(node); - var _elem = _ref5; + map._key = node.key; - if (t.isSpreadElement(_elem)) return false; + if (node.computed) { + map._computed = true; + } - if (t.isCallExpression(_elem)) return false; + if (node.decorators) { + var decorators = map.decorators = map.decorators || t.arrayExpression([]); + decorators.elements = decorators.elements.concat(node.decorators.map(function (dec) { + return dec.expression; + }).reverse()); + } - if (t.isMemberExpression(_elem)) return false; - } + if (map.value || map.initializer) { + throw file.buildCodeFrameError(node, "Key conflict with sibling node"); + } - var bindings = t.getBindingIdentifiers(pattern); - var state = { deopt: false, bindings: bindings }; - this.scope.traverse(arr, arrayUnpackVisitor, state); - return !state.deopt; - }; + var key, value; - DestructuringTransformer.prototype.pushUnpackedArrayPattern = function pushUnpackedArrayPattern(pattern, arr) { - for (var i = 0; i < pattern.elements.length; i++) { - var elem = pattern.elements[i]; - if (t.isRestElement(elem)) { - this.push(elem.argument, t.arrayExpression(arr.elements.slice(i))); - } else { - this.push(elem, arr.elements[i]); - } - } - }; + if (t.isObjectProperty(node) || t.isObjectMethod(node) || t.isClassMethod(node)) { + key = t.toComputedKey(node, node.key); + } - DestructuringTransformer.prototype.pushArrayPattern = function pushArrayPattern(pattern, arrayRef) { - if (!pattern.elements) return; + if (t.isProperty(node)) { + value = node.value; + } else if (t.isObjectMethod(node) || t.isClassMethod(node)) { + value = t.functionExpression(null, node.params, node.body, node.generator, node.async); + value.returnType = node.returnType; + } - if (this.canUnpackArrayPattern(pattern, arrayRef)) { - return this.pushUnpackedArrayPattern(pattern, arrayRef); - } + var inheritedKind = toKind(node); - var count = !hasRest(pattern) && pattern.elements.length; + if (!kind || inheritedKind !== "value") { + kind = inheritedKind; + } - var toArray = this.toArray(arrayRef, count); + if (scope && t.isStringLiteral(key) && (kind === "value" || kind === "initializer") && t.isFunctionExpression(value)) { + value = (0, _helperFunctionName.default)({ + id: key, + node: value, + scope: scope + }); + } - if (t.isIdentifier(toArray)) { - arrayRef = toArray; - } else { - arrayRef = this.scope.generateUidIdentifierBasedOnNode(arrayRef); - this.arrays[arrayRef.name] = true; - this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray)); - } + if (value) { + t.inheritsComments(value, node); + map[kind] = value; + } - for (var i = 0; i < pattern.elements.length; i++) { - var elem = pattern.elements[i]; + return map; +} - if (!elem) continue; +function hasComputed(mutatorMap) { + for (var _i = 0, _Object$keys = Object.keys(mutatorMap); _i < _Object$keys.length; _i++) { + var key = _Object$keys[_i]; - var elemRef = void 0; + if (mutatorMap[key]._computed) { + return true; + } + } - if (t.isRestElement(elem)) { - elemRef = this.toArray(arrayRef); - elemRef = t.callExpression(t.memberExpression(elemRef, t.identifier("slice")), [t.numericLiteral(i)]); + return false; +} - elem = elem.argument; - } else { - elemRef = t.memberExpression(arrayRef, t.numericLiteral(i), true); - } +function toComputedObjectFromClass(obj) { + var objExpr = t.arrayExpression([]); - this.push(elem, elemRef); - } - }; + for (var i = 0; i < obj.properties.length; i++) { + var prop = obj.properties[i]; + var val = prop.value; + val.properties.unshift(t.objectProperty(t.identifier("key"), t.toComputedKey(prop))); + objExpr.elements.push(val); + } - DestructuringTransformer.prototype.init = function init(pattern, ref) { + return objExpr; +} - if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref)) { - var memo = this.scope.maybeGenerateMemoised(ref, true); - if (memo) { - this.nodes.push(this.buildVariableDeclaration(memo, ref)); - ref = memo; - } - } +function toClassObject(mutatorMap) { + var objExpr = t.objectExpression([]); + Object.keys(mutatorMap).forEach(function (mutatorMapKey) { + var map = mutatorMap[mutatorMapKey]; + var mapNode = t.objectExpression([]); + var propNode = t.objectProperty(map._key, mapNode, map._computed); + Object.keys(map).forEach(function (key) { + var node = map[key]; + if (key[0] === "_") return; + var prop = t.objectProperty(t.identifier(key), node); + t.inheritsComments(prop, node); + t.removeComments(node); + mapNode.properties.push(prop); + }); + objExpr.properties.push(propNode); + }); + return objExpr; +} - this.push(pattern, ref); +function toDefineObject(mutatorMap) { + Object.keys(mutatorMap).forEach(function (key) { + var map = mutatorMap[key]; + if (map.value) map.writable = t.booleanLiteral(true); + map.configurable = t.booleanLiteral(true); + map.enumerable = t.booleanLiteral(true); + }); + return toClassObject(mutatorMap); +} - return this.nodes; - }; +},{"@babel/helper-function-name":66,"@babel/types":242,"lodash/has":1012}],65:[function(require,module,exports){ +"use strict"; - return DestructuringTransformer; - }(); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; - return { - visitor: { - ExportNamedDeclaration: function ExportNamedDeclaration(path) { - var declaration = path.get("declaration"); - if (!declaration.isVariableDeclaration()) return; - if (!variableDeclarationHasPattern(declaration.node)) return; +var t = _interopRequireWildcard(require("@babel/types")); - var specifiers = []; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - for (var name in path.getOuterBindingIdentifiers(path)) { - var id = t.identifier(name); - specifiers.push(t.exportSpecifier(id, id)); - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - path.replaceWith(declaration.node); - path.insertAfter(t.exportNamedDeclaration(null, specifiers)); - }, - ForXStatement: function ForXStatement(path, file) { - var node = path.node, - scope = path.scope; + return cache; +} - var left = node.left; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - if (t.isPattern(left)) { + var cache = _getRequireWildcardCache(); - var temp = scope.generateUidIdentifier("ref"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } - node.left = t.variableDeclaration("var", [t.variableDeclarator(temp)]); + var newObj = {}; - path.ensureBlock(); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - node.body.body.unshift(t.variableDeclaration("var", [t.variableDeclarator(left, temp)])); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - return; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; } + } + } + } - if (!t.isVariableDeclaration(left)) return; - - var pattern = left.declarations[0].id; - if (!t.isPattern(pattern)) return; + newObj.default = obj; - var key = scope.generateUidIdentifier("ref"); - node.left = t.variableDeclaration(left.kind, [t.variableDeclarator(key, null)]); + if (cache) { + cache.set(obj, newObj); + } - var nodes = []; + return newObj; +} - var destructuring = new DestructuringTransformer({ - kind: left.kind, - file: file, - scope: scope, - nodes: nodes - }); +function getObjRef(node, nodes, file, scope) { + var ref; - destructuring.init(pattern, key); + if (t.isSuper(node)) { + return node; + } else if (t.isIdentifier(node)) { + if (scope.hasBinding(node.name)) { + return node; + } else { + ref = node; + } + } else if (t.isMemberExpression(node)) { + ref = node.object; - path.ensureBlock(); + if (t.isSuper(ref) || t.isIdentifier(ref) && scope.hasBinding(ref.name)) { + return ref; + } + } else { + throw new Error("We can't explode this node type ".concat(node.type)); + } - var block = node.body; - block.body = nodes.concat(block.body); - }, - CatchClause: function CatchClause(_ref6, file) { - var node = _ref6.node, - scope = _ref6.scope; + var temp = scope.generateUidIdentifierBasedOnNode(ref); + scope.push({ + id: temp + }); + nodes.push(t.assignmentExpression("=", t.cloneNode(temp), t.cloneNode(ref))); + return temp; +} - var pattern = node.param; - if (!t.isPattern(pattern)) return; +function getPropRef(node, nodes, file, scope) { + var prop = node.property; + var key = t.toComputedKey(node, prop); + if (t.isLiteral(key) && t.isPureish(key)) return key; + var temp = scope.generateUidIdentifierBasedOnNode(prop); + scope.push({ + id: temp + }); + nodes.push(t.assignmentExpression("=", t.cloneNode(temp), t.cloneNode(prop))); + return temp; +} - var ref = scope.generateUidIdentifier("ref"); - node.param = ref; +function _default(node, nodes, file, scope, allowedSingleIdent) { + var obj; - var nodes = []; + if (t.isIdentifier(node) && allowedSingleIdent) { + obj = node; + } else { + obj = getObjRef(node, nodes, file, scope); + } - var destructuring = new DestructuringTransformer({ - kind: "let", - file: file, - scope: scope, - nodes: nodes - }); - destructuring.init(pattern, ref); + var ref, uid; - node.body.body = nodes.concat(node.body.body); - }, - AssignmentExpression: function AssignmentExpression(path, file) { - var node = path.node, - scope = path.scope; + if (t.isIdentifier(node)) { + ref = t.cloneNode(node); + uid = obj; + } else { + var prop = getPropRef(node, nodes, file, scope); + var computed = node.computed || t.isLiteral(prop); + uid = t.memberExpression(t.cloneNode(obj), t.cloneNode(prop), computed); + ref = t.memberExpression(t.cloneNode(obj), t.cloneNode(prop), computed); + } - if (!t.isPattern(node.left)) return; + return { + uid: uid, + ref: ref + }; +} - var nodes = []; +},{"@babel/types":242}],66:[function(require,module,exports){ +"use strict"; - var destructuring = new DestructuringTransformer({ - operator: node.operator, - file: file, - scope: scope, - nodes: nodes - }); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; - var ref = void 0; - if (path.isCompletionRecord() || !path.parentPath.isExpressionStatement()) { - ref = scope.generateUidIdentifierBasedOnNode(node.right, "ref"); +var _helperGetFunctionArity = _interopRequireDefault(require("@babel/helper-get-function-arity")); - nodes.push(t.variableDeclaration("var", [t.variableDeclarator(ref, node.right)])); +var _template = _interopRequireDefault(require("@babel/template")); - if (t.isArrayExpression(node.right)) { - destructuring.arrays[ref.name] = true; - } - } +var t = _interopRequireWildcard(require("@babel/types")); - destructuring.init(node.left, ref || node.right); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - if (ref) { - nodes.push(t.expressionStatement(ref)); - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - path.replaceWithMultiple(nodes); - }, - VariableDeclaration: function VariableDeclaration(path, file) { - var node = path.node, - scope = path.scope, - parent = path.parent; + return cache; +} - if (t.isForXStatement(parent)) return; - if (!parent || !path.container) return; - if (!variableDeclarationHasPattern(node)) return; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - var nodes = []; - var declar = void 0; + var cache = _getRequireWildcardCache(); - for (var i = 0; i < node.declarations.length; i++) { - declar = node.declarations[i]; + if (cache && cache.has(obj)) { + return cache.get(obj); + } - var patternId = declar.init; - var pattern = declar.id; + var newObj = {}; - var destructuring = new DestructuringTransformer({ - blockHoist: node._blockHoist, - nodes: nodes, - scope: scope, - kind: node.kind, - file: file - }); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (t.isPattern(pattern)) { - destructuring.init(pattern, patternId); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (+i !== node.declarations.length - 1) { - t.inherits(nodes[nodes.length - 1], declar); - } - } else { - nodes.push(t.inherits(destructuring.buildVariableAssignment(declar.id, declar.init), declar)); - } + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; } + } + } + } - var nodesOut = []; - for (var _iterator5 = nodes, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref7; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref7 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref7 = _i5.value; - } + newObj.default = obj; - var _node = _ref7; + if (cache) { + cache.set(obj, newObj); + } - var tail = nodesOut[nodesOut.length - 1]; - if (tail && t.isVariableDeclaration(tail) && t.isVariableDeclaration(_node) && tail.kind === _node.kind) { - var _tail$declarations; + return newObj; +} - (_tail$declarations = tail.declarations).push.apply(_tail$declarations, _node.declarations); - } else { - nodesOut.push(_node); - } - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - for (var _iterator6 = nodesOut, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref8; +var buildPropertyMethodAssignmentWrapper = (0, _template.default)("\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); +var buildGeneratorPropertyMethodAssignmentWrapper = (0, _template.default)("\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); +var visitor = { + "ReferencedIdentifier|BindingIdentifier": function ReferencedIdentifierBindingIdentifier(path, state) { + if (path.node.name !== state.name) return; + var localDeclar = path.scope.getBindingIdentifier(state.name); + if (localDeclar !== state.outerDeclar) return; + state.selfReference = true; + path.stop(); + } +}; - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref8 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref8 = _i6.value; - } +function getNameFromLiteralId(id) { + if (t.isNullLiteral(id)) { + return "null"; + } - var nodeOut = _ref8; + if (t.isRegExpLiteral(id)) { + return "_".concat(id.pattern, "_").concat(id.flags); + } - if (!nodeOut.declarations) continue; - for (var _iterator7 = nodeOut.declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref9; + if (t.isTemplateLiteral(id)) { + return id.quasis.map(function (quasi) { + return quasi.value.raw; + }).join(""); + } - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref9 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref9 = _i7.value; - } + if (id.value !== undefined) { + return id.value + ""; + } - var declaration = _ref9; - var name = declaration.id.name; + return ""; +} - if (scope.bindings[name]) { - scope.bindings[name].kind = nodeOut.kind; - } - } - } +function wrap(state, method, id, scope) { + if (state.selfReference) { + if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) { + scope.rename(id.name); + } else { + if (!t.isFunction(method)) return; + var build = buildPropertyMethodAssignmentWrapper; - if (nodesOut.length === 1) { - path.replaceWith(nodesOut[0]); - } else { - path.replaceWithMultiple(nodesOut); - } + if (method.generator) { + build = buildGeneratorPropertyMethodAssignmentWrapper; + } + + var template = build({ + FUNCTION: method, + FUNCTION_ID: id, + FUNCTION_KEY: scope.generateUidIdentifier(id.name) + }).expression; + var params = template.callee.body.body[0].params; + + for (var i = 0, len = (0, _helperGetFunctionArity.default)(method); i < len; i++) { + params.push(scope.generateUidIdentifier("x")); } + + return template; } + } + + method.id = id; + scope.getProgramParent().references[id.name] = true; +} + +function visit(node, name, scope) { + var state = { + selfAssignment: false, + selfReference: false, + outerDeclar: scope.getBindingIdentifier(name), + references: [], + name: name }; -}; + var binding = scope.getOwnBinding(name); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (binding) { + if (binding.kind === "param") { + state.selfReference = true; + } else {} + } else if (state.outerDeclar || scope.hasGlobal(name)) { + scope.traverse(node, visitor, state); + } -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109}],73:[function(require,module,exports){ -"use strict"; + return state; +} -exports.__esModule = true; +function _default(_ref) { + var node = _ref.node, + parent = _ref.parent, + scope = _ref.scope, + id = _ref.id; + var localBinding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (node.id) return; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if ((t.isObjectProperty(parent) || t.isObjectMethod(parent, { + kind: "method" + })) && (!parent.computed || t.isLiteral(parent.key))) { + id = parent.key; + } else if (t.isVariableDeclarator(parent)) { + id = parent.id; -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (t.isIdentifier(id) && !localBinding) { + var binding = scope.parent.getBinding(id.name); -var _create = require("babel-runtime/core-js/object/create"); + if (binding && binding.constant && scope.getBinding(id.name) === binding) { + node.id = t.cloneNode(id); + node.id[t.NOT_LOCAL_BINDING] = true; + return; + } + } + } else if (t.isAssignmentExpression(parent)) { + id = parent.left; + } else if (!id) { + return; + } -var _create2 = _interopRequireDefault(_create); + var name; -exports.default = function () { - return { - visitor: { - ObjectExpression: function ObjectExpression(path) { - var node = path.node; + if (id && t.isLiteral(id)) { + name = getNameFromLiteralId(id); + } else if (id && t.isIdentifier(id)) { + name = id.name; + } - var plainProps = node.properties.filter(function (prop) { - return !t.isSpreadProperty(prop) && !prop.computed; - }); + if (name === undefined) { + return; + } - var alreadySeenData = (0, _create2.default)(null); - var alreadySeenGetters = (0, _create2.default)(null); - var alreadySeenSetters = (0, _create2.default)(null); + name = t.toBindingIdentifierName(name); + id = t.identifier(name); + id[t.NOT_LOCAL_BINDING] = true; + var state = visit(node, name, scope); + return wrap(state, node, id, scope) || node; +} - for (var _iterator = plainProps, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +},{"@babel/helper-get-function-arity":67,"@babel/template":167,"@babel/types":242}],67:[function(require,module,exports){ +"use strict"; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; - var prop = _ref; +var t = _interopRequireWildcard(require("@babel/types")); - var name = getName(prop.key); - var isDuplicate = false; - switch (prop.kind) { - case "get": - if (alreadySeenData[name] || alreadySeenGetters[name]) { - isDuplicate = true; - } - alreadySeenGetters[name] = true; - break; - case "set": - if (alreadySeenData[name] || alreadySeenSetters[name]) { - isDuplicate = true; - } - alreadySeenSetters[name] = true; - break; - default: - if (alreadySeenData[name] || alreadySeenGetters[name] || alreadySeenSetters[name]) { - isDuplicate = true; - } - alreadySeenData[name] = true; - } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - if (isDuplicate) { - prop.computed = true; - prop.key = t.stringLiteral(name); - } - } - } - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; -}; - -var _babelTypes = require("babel-types"); -var t = _interopRequireWildcard(_babelTypes); + return cache; +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var cache = _getRequireWildcardCache(); -function getName(key) { - if (t.isIdentifier(key)) { - return key.name; + if (cache && cache.has(obj)) { + return cache.get(obj); } - return key.value.toString(); -} -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/create":100,"babel-types":151}],74:[function(require,module,exports){ -"use strict"; + var newObj = {}; -exports.__esModule = true; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -exports.default = function (_ref) { - var messages = _ref.messages, - template = _ref.template, - t = _ref.types; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - var buildForOfArray = template("\n for (var KEY = 0; KEY < ARR.length; KEY++) BODY;\n "); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } - var buildForOfLoose = template("\n for (var LOOP_OBJECT = OBJECT,\n IS_ARRAY = Array.isArray(LOOP_OBJECT),\n INDEX = 0,\n LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {\n var ID;\n if (IS_ARRAY) {\n if (INDEX >= LOOP_OBJECT.length) break;\n ID = LOOP_OBJECT[INDEX++];\n } else {\n INDEX = LOOP_OBJECT.next();\n if (INDEX.done) break;\n ID = INDEX.value;\n }\n }\n "); + newObj.default = obj; - var buildForOf = template("\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(ITERATOR_COMPLETION = (STEP_KEY = ITERATOR_KEY.next()).done); ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n "); + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} - function _ForOfStatementArray(path) { - var node = path.node, - scope = path.scope; +function _default(node) { + var params = node.params; - var nodes = []; - var right = node.right; + for (var i = 0; i < params.length; i++) { + var param = params[i]; - if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) { - var uid = scope.generateUidIdentifier("arr"); - nodes.push(t.variableDeclaration("var", [t.variableDeclarator(uid, right)])); - right = uid; + if (t.isAssignmentPattern(param) || t.isRestElement(param)) { + return i; } + } - var iterationKey = scope.generateUidIdentifier("i"); + return params.length; +} - var loop = buildForOfArray({ - BODY: node.body, - KEY: iterationKey, - ARR: right - }); +},{"@babel/types":242}],68:[function(require,module,exports){ +"use strict"; - t.inherits(loop, node); - t.ensureBlock(loop); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; - var iterationValue = t.memberExpression(right, iterationKey, true); +var t = _interopRequireWildcard(require("@babel/types")); - var left = node.left; - if (t.isVariableDeclaration(left)) { - left.declarations[0].init = iterationValue; - loop.body.body.unshift(left); - } else { - loop.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", left, iterationValue))); - } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - if (path.parentPath.isLabeledStatement()) { - loop = t.labeledStatement(path.parentPath.node.label, loop); - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - nodes.push(loop); + return cache; +} - return nodes; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; } - return { - visitor: { - ForOfStatement: function ForOfStatement(path, state) { - if (path.get("right").isArrayExpression()) { - if (path.parentPath.isLabeledStatement()) { - return path.parentPath.replaceWithMultiple(_ForOfStatementArray(path)); - } else { - return path.replaceWithMultiple(_ForOfStatementArray(path)); - } - } - - var callback = spec; - if (state.opts.loose) callback = loose; - - var node = path.node; - - var build = callback(path, state); - var declar = build.declar; - var loop = build.loop; - var block = loop.body; + var cache = _getRequireWildcardCache(); - path.ensureBlock(); + if (cache && cache.has(obj)) { + return cache.get(obj); + } - if (declar) { - block.body.push(declar); - } + var newObj = {}; - block.body = block.body.concat(node.body.body); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - t.inherits(loop, node); - t.inherits(loop.body, node.body); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (build.replaceParent) { - path.parentPath.replaceWithMultiple(build.node); - path.remove(); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); } else { - path.replaceWithMultiple(build.node); + newObj[key] = obj[key]; } } } - }; - - function loose(path, file) { - var node = path.node, - scope = path.scope, - parent = path.parent; - var left = node.left; + } - var declar = void 0, - id = void 0; + newObj.default = obj; - if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { - id = left; - } else if (t.isVariableDeclaration(left)) { - id = scope.generateUidIdentifier("ref"); - declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, id)]); - } else { - throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); - } + if (cache) { + cache.set(obj, newObj); + } - var iteratorKey = scope.generateUidIdentifier("iterator"); - var isArrayKey = scope.generateUidIdentifier("isArray"); + return newObj; +} - var loop = buildForOfLoose({ - LOOP_OBJECT: iteratorKey, - IS_ARRAY: isArrayKey, - OBJECT: node.right, - INDEX: scope.generateUidIdentifier("i"), - ID: id - }); +var visitor = { + Scope: function Scope(path, state) { + if (state.kind === "let") path.skip(); + }, + Function: function Function(path) { + path.skip(); + }, + VariableDeclaration: function VariableDeclaration(path, state) { + if (state.kind && path.node.kind !== state.kind) return; + var nodes = []; + var declarations = path.get("declarations"); + var firstId; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (!declar) { - loop.body.body.shift(); - } + try { + for (var _iterator = declarations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var declar = _step.value; + firstId = declar.node.id; - var isLabeledParent = t.isLabeledStatement(parent); - var labeled = void 0; + if (declar.node.init) { + nodes.push(t.expressionStatement(t.assignmentExpression("=", declar.node.id, declar.node.init))); + } - if (isLabeledParent) { - labeled = t.labeledStatement(parent.label, loop); + for (var _i = 0, _Object$keys = Object.keys(declar.getBindingIdentifiers()); _i < _Object$keys.length; _i++) { + var name = _Object$keys[_i]; + state.emit(t.identifier(name), name, declar.node.init !== null); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } } - return { - replaceParent: isLabeledParent, - declar: declar, - node: labeled || loop, - loop: loop - }; - } - - function spec(path, file) { - var node = path.node, - scope = path.scope, - parent = path.parent; - - var left = node.left; - var declar = void 0; - - var stepKey = scope.generateUidIdentifier("step"); - var stepValue = t.memberExpression(stepKey, t.identifier("value")); - - if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { - declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue)); - } else if (t.isVariableDeclaration(left)) { - declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, stepValue)]); + if (path.parentPath.isFor({ + left: path.node + })) { + path.replaceWith(firstId); } else { - throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); + path.replaceWithMultiple(nodes); } + } +}; - var iteratorKey = scope.generateUidIdentifier("iterator"); - - var template = buildForOf({ - ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), - ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), - ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), - ITERATOR_KEY: iteratorKey, - STEP_KEY: stepKey, - OBJECT: node.right, - BODY: null - }); +function _default(path, emit) { + var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "var"; + path.traverse(visitor, { + kind: kind, + emit: emit + }); +} - var isLabeledParent = t.isLabeledStatement(parent); +},{"@babel/types":242}],69:[function(require,module,exports){ +"use strict"; - var tryBody = template[3].block.body; - var loop = tryBody[0]; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - if (isLabeledParent) { - tryBody[0] = t.labeledStatement(parent.label, loop); - } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - return { - replaceParent: isLabeledParent, - declar: declar, - loop: loop, - node: template - }; - } -}; +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -module.exports = exports["default"]; -},{}],75:[function(require,module,exports){ -"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memberExpressionToFunctions; -exports.__esModule = true; +var t = _interopRequireWildcard(require("@babel/types")); -exports.default = function () { - return { - visitor: { - FunctionExpression: { - exit: function exit(path) { - if (path.key !== "value" && !path.parentPath.isObjectProperty()) { - var replacement = (0, _babelHelperFunctionName2.default)(path); - if (replacement) path.replaceWith(replacement); - } - } - }, +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - ObjectProperty: function ObjectProperty(path) { - var value = path.get("value"); - if (value.isFunction()) { - var newNode = (0, _babelHelperFunctionName2.default)(value); - if (newNode) value.replaceWith(newNode); - } - } - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; -}; -var _babelHelperFunctionName = require("babel-helper-function-name"); + return cache; +} -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var cache = _getRequireWildcardCache(); -module.exports = exports["default"]; -},{"babel-helper-function-name":53}],76:[function(require,module,exports){ -"use strict"; + if (cache && cache.has(obj)) { + return cache.get(obj); + } -exports.__esModule = true; + var newObj = {}; -exports.default = function () { - return { - visitor: { - NumericLiteral: function NumericLiteral(_ref) { - var node = _ref.node; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (node.extra && /^0[ob]/i.test(node.extra.raw)) { - node.extra = undefined; - } - }, - StringLiteral: function StringLiteral(_ref2) { - var node = _ref2.node; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (node.extra && /\\[u]/gi.test(node.extra.raw)) { - node.extra = undefined; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; } } } - }; -}; - -module.exports = exports["default"]; -},{}],77:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; + } -var _create = require("babel-runtime/core-js/object/create"); + newObj.default = obj; -var _create2 = _interopRequireDefault(_create); + if (cache) { + cache.set(obj, newObj); + } -exports.default = function (_ref) { - var t = _ref.types; + return newObj; +} - function isValidRequireCall(path) { - if (!path.isCallExpression()) return false; - if (!path.get("callee").isIdentifier({ name: "require" })) return false; - if (path.scope.getBinding("require")) return false; +var AssignmentMemoiser = +/*#__PURE__*/ +function () { + function AssignmentMemoiser() { + _classCallCheck(this, AssignmentMemoiser); - var args = path.get("arguments"); - if (args.length !== 1) return false; + this._map = new WeakMap(); + } - var arg = args[0]; - if (!arg.isStringLiteral()) return false; + _createClass(AssignmentMemoiser, [{ + key: "has", + value: function has(key) { + return this._map.has(key); + } + }, { + key: "get", + value: function get(key) { + if (!this.has(key)) return; - return true; - } + var record = this._map.get(key); - var amdVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(_ref2) { - var node = _ref2.node, - scope = _ref2.scope; + var value = record.value; + record.count--; - if (node.name === "exports" && !scope.getBinding("exports")) { - this.hasExports = true; + if (record.count === 0) { + return t.assignmentExpression("=", value, key); } - if (node.name === "module" && !scope.getBinding("module")) { - this.hasModule = true; - } - }, - CallExpression: function CallExpression(path) { - if (!isValidRequireCall(path)) return; - this.bareSources.push(path.node.arguments[0]); - path.remove(); - }, - VariableDeclarator: function VariableDeclarator(path) { - var id = path.get("id"); - if (!id.isIdentifier()) return; + return value; + } + }, { + key: "set", + value: function set(key, value, count) { + return this._map.set(key, { + count: count, + value: value + }); + } + }]); - var init = path.get("init"); - if (!isValidRequireCall(init)) return; + return AssignmentMemoiser; +}(); - var source = init.node.arguments[0]; - this.sourceNames[source.value] = true; - this.sources.push([id.node, source]); +var handle = { + memoise: function memoise() {}, + handle: function handle(member) { + var node = member.node, + parent = member.parent, + parentPath = member.parentPath; + + if (parentPath.isUpdateExpression({ + argument: node + })) { + var operator = parent.operator, + prefix = parent.prefix; + this.memoise(member, 2); + var value = t.binaryExpression(operator[0], t.unaryExpression("+", this.get(member)), t.numericLiteral(1)); + + if (prefix) { + parentPath.replaceWith(this.set(member, value)); + } else { + var scope = member.scope; + var ref = scope.generateUidIdentifierBasedOnNode(node); + scope.push({ + id: ref + }); + value.left = t.assignmentExpression("=", t.cloneNode(ref), value.left); + parentPath.replaceWith(t.sequenceExpression([this.set(member, value), t.cloneNode(ref)])); + } - path.remove(); + return; } - }; - return { - inherits: require("babel-plugin-transform-es2015-modules-commonjs"), + if (parentPath.isAssignmentExpression({ + left: node + })) { + var _operator = parent.operator, + right = parent.right; + var _value = right; - pre: function pre() { - this.sources = []; - this.sourceNames = (0, _create2.default)(null); + if (_operator !== "=") { + this.memoise(member, 2); + _value = t.binaryExpression(_operator.slice(0, -1), this.get(member), _value); + } - this.bareSources = []; + parentPath.replaceWith(this.set(member, _value)); + return; + } - this.hasExports = false; - this.hasModule = false; - }, + if (parentPath.isCallExpression({ + callee: node + })) { + var args = parent.arguments; + parentPath.replaceWith(this.call(member, args)); + return; + } + if (parentPath.isObjectProperty({ + value: node + }) && parentPath.parentPath.isObjectPattern() || parentPath.isAssignmentPattern({ + left: node + }) && parentPath.parentPath.isObjectProperty({ + value: parent + }) && parentPath.parentPath.parentPath.isObjectPattern() || parentPath.isArrayPattern() || parentPath.isAssignmentPattern({ + left: node + }) && parentPath.parentPath.isArrayPattern() || parentPath.isRestElement()) { + member.replaceWith(this.destructureSet(member)); + return; + } - visitor: { - Program: { - exit: function exit(path) { - var _this = this; + member.replaceWith(this.get(member)); + } +}; - if (this.ran) return; - this.ran = true; +function memberExpressionToFunctions(path, visitor, state) { + path.traverse(visitor, Object.assign({}, handle, {}, state, { + memoiser: new AssignmentMemoiser() + })); +} - path.traverse(amdVisitor, this); +},{"@babel/types":242}],70:[function(require,module,exports){ +"use strict"; - var params = this.sources.map(function (source) { - return source[0]; - }); - var sources = this.sources.map(function (source) { - return source[1]; - }); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - sources = sources.concat(this.bareSources.filter(function (str) { - return !_this.sourceNames[str.value]; - })); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - var moduleName = this.getModuleName(); - if (moduleName) moduleName = t.stringLiteral(moduleName); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - if (this.hasExports) { - sources.unshift(t.stringLiteral("exports")); - params.unshift(t.identifier("exports")); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - if (this.hasModule) { - sources.unshift(t.stringLiteral("module")); - params.unshift(t.identifier("module")); - } +var _assert = _interopRequireDefault(require("assert")); - var node = path.node; +var t = _interopRequireWildcard(require("@babel/types")); - var factory = buildFactory({ - PARAMS: params, - BODY: node.body - }); - factory.expression.body.directives = node.directives; - node.directives = []; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - node.body = [buildDefine({ - MODULE_NAME: moduleName, - SOURCES: sources, - FACTORY: factory - })]; - } - } - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; -}; -var _babelTemplate = require("babel-template"); + return cache; +} + +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + var cache = _getRequireWildcardCache(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var buildDefine = (0, _babelTemplate2.default)("\n define(MODULE_NAME, [SOURCES], FACTORY);\n"); + var newObj = {}; -var buildFactory = (0, _babelTemplate2.default)("\n (function (PARAMS) {\n BODY;\n })\n"); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -module.exports = exports["default"]; -},{"babel-plugin-transform-es2015-modules-commonjs":78,"babel-runtime/core-js/object/create":100,"babel-template":114}],78:[function(require,module,exports){ -"use strict"; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -exports.__esModule = true; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } + + newObj.default = obj; -var _keys = require("babel-runtime/core-js/object/keys"); + if (cache) { + cache.set(obj, newObj); + } -var _keys2 = _interopRequireDefault(_keys); + return newObj; +} -var _create = require("babel-runtime/core-js/object/create"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} -var _create2 = _interopRequireDefault(_create); +var ImportBuilder = +/*#__PURE__*/ +function () { + function ImportBuilder(importedSource, scope, hub) { + _classCallCheck(this, ImportBuilder); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + this._statements = []; + this._resultName = null; + this._scope = null; + this._hub = null; + this._scope = scope; + this._hub = hub; + this._importedSource = importedSource; + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + _createClass(ImportBuilder, [{ + key: "done", + value: function done() { + return { + statements: this._statements, + resultName: this._resultName + }; + } + }, { + key: "import", + value: function _import() { + this._statements.push(t.importDeclaration([], t.stringLiteral(this._importedSource))); -var _symbol = require("babel-runtime/core-js/symbol"); + return this; + } + }, { + key: "require", + value: function require() { + this._statements.push(t.expressionStatement(t.callExpression(t.identifier("require"), [t.stringLiteral(this._importedSource)]))); -var _symbol2 = _interopRequireDefault(_symbol); + return this; + } + }, { + key: "namespace", + value: function namespace() { + var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "namespace"; + name = this._scope.generateUidIdentifier(name); + var statement = this._statements[this._statements.length - 1]; + (0, _assert.default)(statement.type === "ImportDeclaration"); + (0, _assert.default)(statement.specifiers.length === 0); + statement.specifiers = [t.importNamespaceSpecifier(name)]; + this._resultName = t.cloneNode(name); + return this; + } + }, { + key: "default", + value: function _default(name) { + name = this._scope.generateUidIdentifier(name); + var statement = this._statements[this._statements.length - 1]; + (0, _assert.default)(statement.type === "ImportDeclaration"); + (0, _assert.default)(statement.specifiers.length === 0); + statement.specifiers = [t.importDefaultSpecifier(name)]; + this._resultName = t.cloneNode(name); + return this; + } + }, { + key: "named", + value: function named(name, importName) { + if (importName === "default") return this.default(name); + name = this._scope.generateUidIdentifier(name); + var statement = this._statements[this._statements.length - 1]; + (0, _assert.default)(statement.type === "ImportDeclaration"); + (0, _assert.default)(statement.specifiers.length === 0); + statement.specifiers = [t.importSpecifier(name, t.identifier(importName))]; + this._resultName = t.cloneNode(name); + return this; + } + }, { + key: "var", + value: function _var(name) { + name = this._scope.generateUidIdentifier(name); + var statement = this._statements[this._statements.length - 1]; -exports.default = function () { - var REASSIGN_REMAP_SKIP = (0, _symbol2.default)(); + if (statement.type !== "ExpressionStatement") { + (0, _assert.default)(this._resultName); + statement = t.expressionStatement(this._resultName); - var reassignmentVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path) { - var name = path.node.name; - var remap = this.remaps[name]; - if (!remap) return; + this._statements.push(statement); + } - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; + this._statements[this._statements.length - 1] = t.variableDeclaration("var", [t.variableDeclarator(name, statement.expression)]); + this._resultName = t.cloneNode(name); + return this; + } + }, { + key: "defaultInterop", + value: function defaultInterop() { + return this._interop(this._hub.addHelper("interopRequireDefault")); + } + }, { + key: "wildcardInterop", + value: function wildcardInterop() { + return this._interop(this._hub.addHelper("interopRequireWildcard")); + } + }, { + key: "_interop", + value: function _interop(callee) { + var statement = this._statements[this._statements.length - 1]; + + if (statement.type === "ExpressionStatement") { + statement.expression = t.callExpression(callee, [statement.expression]); + } else if (statement.type === "VariableDeclaration") { + (0, _assert.default)(statement.declarations.length === 1); + statement.declarations[0].init = t.callExpression(callee, [statement.declarations[0].init]); + } else { + _assert.default.fail("Unexpected type."); + } - if (path.parentPath.isCallExpression({ callee: path.node })) { - path.replaceWith(t.sequenceExpression([t.numericLiteral(0), remap])); - } else if (path.isJSXIdentifier() && t.isMemberExpression(remap)) { - var object = remap.object, - property = remap.property; + return this; + } + }, { + key: "prop", + value: function prop(name) { + var statement = this._statements[this._statements.length - 1]; - path.replaceWith(t.JSXMemberExpression(t.JSXIdentifier(object.name), t.JSXIdentifier(property.name))); + if (statement.type === "ExpressionStatement") { + statement.expression = t.memberExpression(statement.expression, t.identifier(name)); + } else if (statement.type === "VariableDeclaration") { + (0, _assert.default)(statement.declarations.length === 1); + statement.declarations[0].init = t.memberExpression(statement.declarations[0].init, t.identifier(name)); } else { - path.replaceWith(remap); + _assert.default.fail("Unexpected type:" + statement.type); } - this.requeueInParent(path); - }, - AssignmentExpression: function AssignmentExpression(path) { - var node = path.node; - if (node[REASSIGN_REMAP_SKIP]) return; - var left = path.get("left"); - if (left.isIdentifier()) { - var name = left.node.name; - var exports = this.exports[name]; - if (!exports) return; + return this; + } + }, { + key: "read", + value: function read(name) { + this._resultName = t.memberExpression(this._resultName, t.identifier(name)); + } + }]); - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; + return ImportBuilder; +}(); - node[REASSIGN_REMAP_SKIP] = true; +exports.default = ImportBuilder; - for (var _iterator = exports, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +},{"@babel/types":242,"assert":278}],71:[function(require,module,exports){ +"use strict"; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var reid = _ref; +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - node = buildExportsAssignment(reid, node).expression; - } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - path.replaceWith(node); - this.requeueInParent(path); - } else if (left.isObjectPattern()) { - for (var _iterator2 = left.node.properties, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +var _assert = _interopRequireDefault(require("assert")); - var property = _ref2; +var t = _interopRequireWildcard(require("@babel/types")); - var _name = property.value.name; +var _importBuilder = _interopRequireDefault(require("./import-builder")); - var _exports = this.exports[_name]; - if (!_exports) continue; +var _isModule = _interopRequireDefault(require("./is-module")); - if (this.scope.getBinding(_name) !== path.scope.getBinding(_name)) return; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - node[REASSIGN_REMAP_SKIP] = true; + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - path.insertAfter(buildExportsAssignment(t.identifier(_name), t.identifier(_name))); - } - } else if (left.isArrayPattern()) { - for (var _iterator3 = left.node.elements, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + return cache; +} - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - var element = _ref3; + var cache = _getRequireWildcardCache(); - if (!element) continue; - var _name2 = element.name; + if (cache && cache.has(obj)) { + return cache.get(obj); + } - var _exports2 = this.exports[_name2]; - if (!_exports2) continue; + var newObj = {}; - if (this.scope.getBinding(_name2) !== path.scope.getBinding(_name2)) return; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - node[REASSIGN_REMAP_SKIP] = true; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - path.insertAfter(buildExportsAssignment(t.identifier(_name2), t.identifier(_name2))); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; } } - }, - UpdateExpression: function UpdateExpression(path) { - var arg = path.get("argument"); - if (!arg.isIdentifier()) return; + } + } - var name = arg.node.name; - var exports = this.exports[name]; - if (!exports) return; + newObj.default = obj; - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; + if (cache) { + cache.set(obj, newObj); + } - var node = t.assignmentExpression(path.node.operator[0] + "=", arg.node, t.numericLiteral(1)); + return newObj; +} - if (path.parentPath.isExpressionStatement() && !path.isCompletionRecord() || path.node.prefix) { - path.replaceWith(node); - this.requeueInParent(path); - return; - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - var nodes = []; - nodes.push(node); +var ImportInjector = +/*#__PURE__*/ +function () { + function ImportInjector(path, importedSource, opts) { + _classCallCheck(this, ImportInjector); - var operator = void 0; - if (path.node.operator === "--") { - operator = "+"; + this._defaultOpts = { + importedSource: null, + importedType: "commonjs", + importedInterop: "babel", + importingInterop: "babel", + ensureLiveReference: false, + ensureNoContext: false + }; + var programPath = path.find(function (p) { + return p.isProgram(); + }); + this._programPath = programPath; + this._programScope = programPath.scope; + this._hub = programPath.hub; + this._defaultOpts = this._applyDefaults(importedSource, opts, true); + } + + _createClass(ImportInjector, [{ + key: "addDefault", + value: function addDefault(importedSourceIn, opts) { + return this.addNamed("default", importedSourceIn, opts); + } + }, { + key: "addNamed", + value: function addNamed(importName, importedSourceIn, opts) { + (0, _assert.default)(typeof importName === "string"); + return this._generateImport(this._applyDefaults(importedSourceIn, opts), importName); + } + }, { + key: "addNamespace", + value: function addNamespace(importedSourceIn, opts) { + return this._generateImport(this._applyDefaults(importedSourceIn, opts), null); + } + }, { + key: "addSideEffect", + value: function addSideEffect(importedSourceIn, opts) { + return this._generateImport(this._applyDefaults(importedSourceIn, opts), false); + } + }, { + key: "_applyDefaults", + value: function _applyDefaults(importedSource, opts) { + var isInit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var optsList = []; + + if (typeof importedSource === "string") { + optsList.push({ + importedSource: importedSource + }); + optsList.push(opts); } else { - operator = "-"; + (0, _assert.default)(!opts, "Unexpected secondary arguments."); + optsList.push(importedSource); } - nodes.push(t.binaryExpression(operator, arg.node, t.numericLiteral(1))); - - path.replaceWithMultiple(t.sequenceExpression(nodes)); - } - }; - return { - inherits: _babelPluginTransformStrictMode2.default, + var newOpts = Object.assign({}, this._defaultOpts); - visitor: { - ThisExpression: function ThisExpression(path, state) { - if (this.ranCommonJS) return; + var _loop = function _loop() { + var opts = _optsList[_i]; + if (!opts) return "continue"; + Object.keys(newOpts).forEach(function (key) { + if (opts[key] !== undefined) newOpts[key] = opts[key]; + }); - if (state.opts.allowTopLevelThis !== true && !path.findParent(function (path) { - return !path.is("shadow") && THIS_BREAK_KEYS.indexOf(path.type) >= 0; - })) { - path.replaceWith(t.identifier("undefined")); + if (!isInit) { + if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint; + if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist; } - }, - - - Program: { - exit: function exit(path) { - this.ranCommonJS = true; - - var strict = !!this.opts.strict; - var noInterop = !!this.opts.noInterop; - - var scope = path.scope; - - scope.rename("module"); - scope.rename("exports"); - scope.rename("require"); - - var hasExports = false; - var hasImports = false; - - var body = path.get("body"); - var imports = (0, _create2.default)(null); - var exports = (0, _create2.default)(null); - - var nonHoistedExportNames = (0, _create2.default)(null); - - var topNodes = []; - var remaps = (0, _create2.default)(null); - - var requires = (0, _create2.default)(null); - - function addRequire(source, blockHoist) { - var cached = requires[source]; - if (cached) return cached; + }; - var ref = path.scope.generateUidIdentifier((0, _path2.basename)(source, (0, _path2.extname)(source))); + for (var _i = 0, _optsList = optsList; _i < _optsList.length; _i++) { + var _ret = _loop(); + + if (_ret === "continue") continue; + } + + return newOpts; + } + }, { + key: "_generateImport", + value: function _generateImport(opts, importName) { + var isDefault = importName === "default"; + var isNamed = !!importName && !isDefault; + var isNamespace = importName === null; + var importedSource = opts.importedSource, + importedType = opts.importedType, + importedInterop = opts.importedInterop, + importingInterop = opts.importingInterop, + ensureLiveReference = opts.ensureLiveReference, + ensureNoContext = opts.ensureNoContext, + nameHint = opts.nameHint, + blockHoist = opts.blockHoist; + var name = nameHint || importName; + var isMod = (0, _isModule.default)(this._programPath); + var isModuleForNode = isMod && importingInterop === "node"; + var isModuleForBabel = isMod && importingInterop === "babel"; + var builder = new _importBuilder.default(importedSource, this._programScope, this._hub); + + if (importedType === "es6") { + if (!isModuleForNode && !isModuleForBabel) { + throw new Error("Cannot import an ES6 module from CommonJS"); + } - var varDecl = t.variableDeclaration("var", [t.variableDeclarator(ref, buildRequire(t.stringLiteral(source)).expression)]); + builder.import(); - if (imports[source]) { - varDecl.loc = imports[source].loc; + if (isNamespace) { + builder.namespace(nameHint || importedSource); + } else if (isDefault || isNamed) { + builder.named(name, importName); + } + } else if (importedType !== "commonjs") { + throw new Error("Unexpected interopType \"".concat(importedType, "\"")); + } else if (importedInterop === "babel") { + if (isModuleForNode) { + name = name !== "default" ? name : importedSource; + var es6Default = "".concat(importedSource, "$es6Default"); + builder.import(); + + if (isNamespace) { + builder.default(es6Default).var(name || importedSource).wildcardInterop(); + } else if (isDefault) { + if (ensureLiveReference) { + builder.default(es6Default).var(name || importedSource).defaultInterop().read("default"); + } else { + builder.default(es6Default).var(name).defaultInterop().prop(importName); } + } else if (isNamed) { + builder.default(es6Default).read(importName); + } + } else if (isModuleForBabel) { + builder.import(); - if (typeof blockHoist === "number" && blockHoist > 0) { - varDecl._blockHoist = blockHoist; + if (isNamespace) { + builder.namespace(name || importedSource); + } else if (isDefault || isNamed) { + builder.named(name, importName); + } + } else { + builder.require(); + + if (isNamespace) { + builder.var(name || importedSource).wildcardInterop(); + } else if ((isDefault || isNamed) && ensureLiveReference) { + if (isDefault) { + name = name !== "default" ? name : importedSource; + builder.var(name).read(importName); + builder.defaultInterop(); + } else { + builder.var(importedSource).read(importName); } + } else if (isDefault) { + builder.var(name).defaultInterop().prop(importName); + } else if (isNamed) { + builder.var(name).prop(importName); + } + } + } else if (importedInterop === "compiled") { + if (isModuleForNode) { + builder.import(); + + if (isNamespace) { + builder.default(name || importedSource); + } else if (isDefault || isNamed) { + builder.default(importedSource).read(name); + } + } else if (isModuleForBabel) { + builder.import(); - topNodes.push(varDecl); - - return requires[source] = ref; + if (isNamespace) { + builder.namespace(name || importedSource); + } else if (isDefault || isNamed) { + builder.named(name, importName); } + } else { + builder.require(); - function addTo(obj, key, arr) { - var existing = obj[key] || []; - obj[key] = existing.concat(arr); + if (isNamespace) { + builder.var(name || importedSource); + } else if (isDefault || isNamed) { + if (ensureLiveReference) { + builder.var(importedSource).read(name); + } else { + builder.prop(importName).var(name); + } } + } + } else if (importedInterop === "uncompiled") { + if (isDefault && ensureLiveReference) { + throw new Error("No live reference for commonjs default"); + } - for (var _iterator4 = body, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; + if (isModuleForNode) { + builder.import(); - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; + if (isNamespace) { + builder.default(name || importedSource); + } else if (isDefault) { + builder.default(name); + } else if (isNamed) { + builder.default(importedSource).read(name); + } + } else if (isModuleForBabel) { + builder.import(); + + if (isNamespace) { + builder.default(name || importedSource); + } else if (isDefault) { + builder.default(name); + } else if (isNamed) { + builder.named(name, importName); + } + } else { + builder.require(); + + if (isNamespace) { + builder.var(name || importedSource); + } else if (isDefault) { + builder.var(name); + } else if (isNamed) { + if (ensureLiveReference) { + builder.var(importedSource).read(name); } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; + builder.var(name).prop(importName); } + } + } + } else { + throw new Error("Unknown importedInterop \"".concat(importedInterop, "\".")); + } - var _path = _ref4; + var _builder$done = builder.done(), + statements = _builder$done.statements, + resultName = _builder$done.resultName; - if (_path.isExportDeclaration()) { - hasExports = true; + this._insertStatements(statements, blockHoist); - var specifiers = [].concat(_path.get("declaration"), _path.get("specifiers")); - for (var _iterator6 = specifiers, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; + if ((isDefault || isNamed) && ensureNoContext && resultName.type !== "Identifier") { + return t.sequenceExpression([t.numericLiteral(0), resultName]); + } - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } + return resultName; + } + }, { + key: "_insertStatements", + value: function _insertStatements(statements) { + var blockHoist = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3; + statements.forEach(function (node) { + node._blockHoist = blockHoist; + }); - var _specifier2 = _ref6; + var targetPath = this._programPath.get("body").find(function (p) { + var val = p.node._blockHoist; + return Number.isFinite(val) && val < 4; + }); - var ids = _specifier2.getBindingIdentifiers(); - if (ids.__esModule) { - throw _specifier2.buildCodeFrameError("Illegal export \"__esModule\""); - } - } - } + if (targetPath) { + targetPath.insertBefore(statements); + } else { + this._programPath.unshiftContainer("body", statements); + } + } + }]); - if (_path.isImportDeclaration()) { - var _importsEntry$specifi; + return ImportInjector; +}(); - hasImports = true; +exports.default = ImportInjector; - var key = _path.node.source.value; - var importsEntry = imports[key] || { - specifiers: [], - maxBlockHoist: 0, - loc: _path.node.loc - }; +},{"./import-builder":70,"./is-module":73,"@babel/types":242,"assert":278}],72:[function(require,module,exports){ +"use strict"; - (_importsEntry$specifi = importsEntry.specifiers).push.apply(_importsEntry$specifi, _path.node.specifiers); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.addDefault = addDefault; +exports.addNamed = addNamed; +exports.addNamespace = addNamespace; +exports.addSideEffect = addSideEffect; +Object.defineProperty(exports, "ImportInjector", { + enumerable: true, + get: function get() { + return _importInjector.default; + } +}); +Object.defineProperty(exports, "isModule", { + enumerable: true, + get: function get() { + return _isModule.default; + } +}); - if (typeof _path.node._blockHoist === "number") { - importsEntry.maxBlockHoist = Math.max(_path.node._blockHoist, importsEntry.maxBlockHoist); - } +var _importInjector = _interopRequireDefault(require("./import-injector")); - imports[key] = importsEntry; - - _path.remove(); - } else if (_path.isExportDefaultDeclaration()) { - var declaration = _path.get("declaration"); - if (declaration.isFunctionDeclaration()) { - var id = declaration.node.id; - var defNode = t.identifier("default"); - if (id) { - addTo(exports, id.name, defNode); - topNodes.push(buildExportsAssignment(defNode, id)); - _path.replaceWith(declaration.node); - } else { - topNodes.push(buildExportsAssignment(defNode, t.toExpression(declaration.node))); - _path.remove(); - } - } else if (declaration.isClassDeclaration()) { - var _id = declaration.node.id; - var _defNode = t.identifier("default"); - if (_id) { - addTo(exports, _id.name, _defNode); - _path.replaceWithMultiple([declaration.node, buildExportsAssignment(_defNode, _id)]); - } else { - _path.replaceWith(buildExportsAssignment(_defNode, t.toExpression(declaration.node))); +var _isModule = _interopRequireDefault(require("./is-module")); - _path.parentPath.requeue(_path.get("expression.left")); - } - } else { - _path.replaceWith(buildExportsAssignment(t.identifier("default"), declaration.node)); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - _path.parentPath.requeue(_path.get("expression.left")); - } - } else if (_path.isExportNamedDeclaration()) { - var _declaration = _path.get("declaration"); - if (_declaration.node) { - if (_declaration.isFunctionDeclaration()) { - var _id2 = _declaration.node.id; - addTo(exports, _id2.name, _id2); - topNodes.push(buildExportsAssignment(_id2, _id2)); - _path.replaceWith(_declaration.node); - } else if (_declaration.isClassDeclaration()) { - var _id3 = _declaration.node.id; - addTo(exports, _id3.name, _id3); - _path.replaceWithMultiple([_declaration.node, buildExportsAssignment(_id3, _id3)]); - nonHoistedExportNames[_id3.name] = true; - } else if (_declaration.isVariableDeclaration()) { - var declarators = _declaration.get("declarations"); - for (var _iterator7 = declarators, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } +function addDefault(path, importedSource, opts) { + return new _importInjector.default(path).addDefault(importedSource, opts); +} - var decl = _ref7; - - var _id4 = decl.get("id"); - - var init = decl.get("init"); - var exportsToInsert = []; - if (!init.node) init.replaceWith(t.identifier("undefined")); - - if (_id4.isIdentifier()) { - addTo(exports, _id4.node.name, _id4.node); - init.replaceWith(buildExportsAssignment(_id4.node, init.node).expression); - nonHoistedExportNames[_id4.node.name] = true; - } else if (_id4.isObjectPattern()) { - for (var _i8 = 0; _i8 < _id4.node.properties.length; _i8++) { - var prop = _id4.node.properties[_i8]; - var propValue = prop.value; - if (t.isAssignmentPattern(propValue)) { - propValue = propValue.left; - } else if (t.isRestProperty(prop)) { - propValue = prop.argument; - } - addTo(exports, propValue.name, propValue); - exportsToInsert.push(buildExportsAssignment(propValue, propValue)); - nonHoistedExportNames[propValue.name] = true; - } - } else if (_id4.isArrayPattern() && _id4.node.elements) { - for (var _i9 = 0; _i9 < _id4.node.elements.length; _i9++) { - var elem = _id4.node.elements[_i9]; - if (!elem) continue; - if (t.isAssignmentPattern(elem)) { - elem = elem.left; - } else if (t.isRestElement(elem)) { - elem = elem.argument; - } - var name = elem.name; - addTo(exports, name, elem); - exportsToInsert.push(buildExportsAssignment(elem, elem)); - nonHoistedExportNames[name] = true; - } - } - _path.insertAfter(exportsToInsert); - } - _path.replaceWith(_declaration.node); - } - continue; - } +function addNamed(path, name, importedSource, opts) { + return new _importInjector.default(path).addNamed(name, importedSource, opts); +} - var _specifiers = _path.get("specifiers"); - var nodes = []; - var _source = _path.node.source; - if (_source) { - var ref = addRequire(_source.value, _path.node._blockHoist); +function addNamespace(path, importedSource, opts) { + return new _importInjector.default(path).addNamespace(importedSource, opts); +} - for (var _iterator8 = _specifiers, _isArray8 = Array.isArray(_iterator8), _i10 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; +function addSideEffect(path, importedSource, opts) { + return new _importInjector.default(path).addSideEffect(importedSource, opts); +} - if (_isArray8) { - if (_i10 >= _iterator8.length) break; - _ref8 = _iterator8[_i10++]; - } else { - _i10 = _iterator8.next(); - if (_i10.done) break; - _ref8 = _i10.value; - } +},{"./import-injector":71,"./is-module":73}],73:[function(require,module,exports){ +"use strict"; - var _specifier3 = _ref8; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isModule; - if (_specifier3.isExportNamespaceSpecifier()) {} else if (_specifier3.isExportDefaultSpecifier()) {} else if (_specifier3.isExportSpecifier()) { - if (!noInterop && _specifier3.node.local.name === "default") { - topNodes.push(buildExportsFrom(t.stringLiteral(_specifier3.node.exported.name), t.memberExpression(t.callExpression(this.addHelper("interopRequireDefault"), [ref]), _specifier3.node.local))); - } else { - topNodes.push(buildExportsFrom(t.stringLiteral(_specifier3.node.exported.name), t.memberExpression(ref, _specifier3.node.local))); - } - nonHoistedExportNames[_specifier3.node.exported.name] = true; - } - } - } else { - for (var _iterator9 = _specifiers, _isArray9 = Array.isArray(_iterator9), _i11 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; +function isModule(path) { + var sourceType = path.node.sourceType; - if (_isArray9) { - if (_i11 >= _iterator9.length) break; - _ref9 = _iterator9[_i11++]; - } else { - _i11 = _iterator9.next(); - if (_i11.done) break; - _ref9 = _i11.value; - } + if (sourceType !== "module" && sourceType !== "script") { + throw path.buildCodeFrameError("Unknown sourceType \"".concat(sourceType, "\", cannot transform.")); + } - var _specifier4 = _ref9; + return path.node.sourceType === "module"; +} - if (_specifier4.isExportSpecifier()) { - addTo(exports, _specifier4.node.local.name, _specifier4.node.exported); - nonHoistedExportNames[_specifier4.node.exported.name] = true; - nodes.push(buildExportsAssignment(_specifier4.node.exported, _specifier4.node.local)); - } - } - } - _path.replaceWithMultiple(nodes); - } else if (_path.isExportAllDeclaration()) { - var exportNode = buildExportAll({ - OBJECT: addRequire(_path.node.source.value, _path.node._blockHoist) - }); - exportNode.loc = _path.node.loc; - topNodes.push(exportNode); - _path.remove(); - } - } +},{}],74:[function(require,module,exports){ +"use strict"; - for (var source in imports) { - var _imports$source = imports[source], - specifiers = _imports$source.specifiers, - maxBlockHoist = _imports$source.maxBlockHoist; +function _templateObject11() { + var data = _taggedTemplateLiteral(["EXPORTS.NAME = VALUE"]); - if (specifiers.length) { - var uid = addRequire(source, maxBlockHoist); + _templateObject11 = function _templateObject11() { + return data; + }; - var wildcard = void 0; + return data; +} - for (var i = 0; i < specifiers.length; i++) { - var specifier = specifiers[i]; - if (t.isImportNamespaceSpecifier(specifier)) { - if (strict || noInterop) { - remaps[specifier.local.name] = uid; - } else { - var varDecl = t.variableDeclaration("var", [t.variableDeclarator(specifier.local, t.callExpression(this.addHelper("interopRequireWildcard"), [uid]))]); +function _templateObject10() { + var data = _taggedTemplateLiteral(["\n if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;\n "]); - if (maxBlockHoist > 0) { - varDecl._blockHoist = maxBlockHoist; - } + _templateObject10 = function _templateObject10() { + return data; + }; - topNodes.push(varDecl); - } - wildcard = specifier.local; - } else if (t.isImportDefaultSpecifier(specifier)) { - specifiers[i] = t.importSpecifier(specifier.local, t.identifier("default")); - } - } + return data; +} - for (var _iterator5 = specifiers, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; +function _templateObject9() { + var data = _taggedTemplateLiteral(["\n Object.keys(NAMESPACE).forEach(function(key) {\n if (key === \"default\" || key === \"__esModule\") return;\n VERIFY_NAME_LIST;\n\n Object.defineProperty(EXPORTS, key, {\n enumerable: true,\n get: function() {\n return NAMESPACE[key];\n },\n });\n });\n "]); - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } + _templateObject9 = function _templateObject9() { + return data; + }; - var _specifier = _ref5; + return data; +} - if (t.isImportSpecifier(_specifier)) { - var target = uid; - if (_specifier.imported.name === "default") { - if (wildcard) { - target = wildcard; - } else if (!noInterop) { - target = wildcard = path.scope.generateUidIdentifier(uid.name); - var _varDecl = t.variableDeclaration("var", [t.variableDeclarator(target, t.callExpression(this.addHelper("interopRequireDefault"), [uid]))]); +function _templateObject8() { + var data = _taggedTemplateLiteral(["\n Object.keys(NAMESPACE).forEach(function(key) {\n if (key === \"default\" || key === \"__esModule\") return;\n VERIFY_NAME_LIST;\n\n EXPORTS[key] = NAMESPACE[key];\n });\n "]); - if (maxBlockHoist > 0) { - _varDecl._blockHoist = maxBlockHoist; - } + _templateObject8 = function _templateObject8() { + return data; + }; - topNodes.push(_varDecl); - } - } - remaps[_specifier.local.name] = t.memberExpression(target, t.cloneWithoutLoc(_specifier.imported)); - } - } - } else { - var requireNode = buildRequire(t.stringLiteral(source)); - requireNode.loc = imports[source].loc; - topNodes.push(requireNode); - } - } + return data; +} - if (hasImports && (0, _keys2.default)(nonHoistedExportNames).length) { - var maxHoistedExportsNodeAssignmentLength = 100; - var nonHoistedExportNamesArr = (0, _keys2.default)(nonHoistedExportNames); +function _templateObject7() { + var data = _taggedTemplateLiteral(["\n Object.defineProperty(EXPORTS, \"__esModule\", {\n value: true,\n });\n "]); - var _loop = function _loop(currentExportsNodeAssignmentLength) { - var nonHoistedExportNamesChunk = nonHoistedExportNamesArr.slice(currentExportsNodeAssignmentLength, currentExportsNodeAssignmentLength + maxHoistedExportsNodeAssignmentLength); + _templateObject7 = function _templateObject7() { + return data; + }; - var hoistedExportsNode = t.identifier("undefined"); + return data; +} - nonHoistedExportNamesChunk.forEach(function (name) { - hoistedExportsNode = buildExportsAssignment(t.identifier(name), hoistedExportsNode).expression; - }); +function _templateObject6() { + var data = _taggedTemplateLiteral(["\n EXPORTS.__esModule = true;\n "]); - var node = t.expressionStatement(hoistedExportsNode); - node._blockHoist = 3; + _templateObject6 = function _templateObject6() { + return data; + }; - topNodes.unshift(node); - }; + return data; +} - for (var currentExportsNodeAssignmentLength = 0; currentExportsNodeAssignmentLength < nonHoistedExportNamesArr.length; currentExportsNodeAssignmentLength += maxHoistedExportsNodeAssignmentLength) { - _loop(currentExportsNodeAssignmentLength); - } - } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - if (hasExports && !strict) { - var buildTemplate = buildExportsModuleDeclaration; - if (this.opts.loose) buildTemplate = buildLooseExportsModuleDeclaration; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - var declar = buildTemplate(); - declar._blockHoist = 3; +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - topNodes.unshift(declar); - } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - path.unshiftContainer("body", topNodes); - path.traverse(reassignmentVisitor, { - remaps: remaps, - scope: scope, - exports: exports, - requeueInParent: function requeueInParent(newPath) { - return path.requeue(newPath); - } - }); - } - } - } +function _templateObject5() { + var data = _taggedTemplateLiteral(["\n Object.defineProperty(EXPORTS, \"EXPORT_NAME\", {\n enumerable: true,\n get: function() {\n return NAMESPACE.IMPORT_NAME;\n },\n });\n "]); + + _templateObject5 = function _templateObject5() { + return data; }; -}; -var _path2 = require("path"); + return data; +} + +function _templateObject4() { + var data = _taggedTemplateLiteral(["EXPORTS.EXPORT_NAME = NAMESPACE.IMPORT_NAME;"]); -var _babelTemplate = require("babel-template"); + _templateObject4 = function _templateObject4() { + return data; + }; -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + return data; +} -var _babelPluginTransformStrictMode = require("babel-plugin-transform-strict-mode"); +function _templateObject3() { + var data = _taggedTemplateLiteral(["EXPORTS.NAME = NAMESPACE;"]); -var _babelPluginTransformStrictMode2 = _interopRequireDefault(_babelPluginTransformStrictMode); + _templateObject3 = function _templateObject3() { + return data; + }; -var _babelTypes = require("babel-types"); + return data; +} -var t = _interopRequireWildcard(_babelTypes); +function _templateObject2() { + var data = _taggedTemplateLiteral(["\n Object.defineProperty(EXPORTS, \"NAME\", {\n enumerable: true,\n get: function() {\n return NAMESPACE;\n }\n });\n "]); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + _templateObject2 = function _templateObject2() { + return data; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return data; +} -var buildRequire = (0, _babelTemplate2.default)("\n require($0);\n"); +function _templateObject() { + var data = _taggedTemplateLiteral(["var NAME = SOURCE;"]); -var buildExportsModuleDeclaration = (0, _babelTemplate2.default)("\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n"); + _templateObject = function _templateObject() { + return data; + }; -var buildExportsFrom = (0, _babelTemplate2.default)("\n Object.defineProperty(exports, $0, {\n enumerable: true,\n get: function () {\n return $1;\n }\n });\n"); + return data; +} -var buildLooseExportsModuleDeclaration = (0, _babelTemplate2.default)("\n exports.__esModule = true;\n"); +function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } -var buildExportsAssignment = (0, _babelTemplate2.default)("\n exports.$0 = $1;\n"); +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } -var buildExportAll = (0, _babelTemplate2.default)("\n Object.keys(OBJECT).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return OBJECT[key];\n }\n });\n });\n"); +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } -var THIS_BREAK_KEYS = ["FunctionExpression", "FunctionDeclaration", "ClassProperty", "ClassMethod", "ObjectMethod"]; +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -module.exports = exports["default"]; -},{"babel-plugin-transform-strict-mode":93,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/create":100,"babel-runtime/core-js/object/keys":102,"babel-runtime/core-js/symbol":104,"babel-template":114,"babel-types":151,"path":522}],79:[function(require,module,exports){ -"use strict"; +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader; +exports.ensureStatementsHoisted = ensureStatementsHoisted; +exports.wrapInterop = wrapInterop; +exports.buildNamespaceInitStatements = buildNamespaceInitStatements; +Object.defineProperty(exports, "isModule", { + enumerable: true, + get: function get() { + return _helperModuleImports.isModule; + } +}); +Object.defineProperty(exports, "hasExports", { + enumerable: true, + get: function get() { + return _normalizeAndLoadMetadata.hasExports; + } +}); +Object.defineProperty(exports, "isSideEffectImport", { + enumerable: true, + get: function get() { + return _normalizeAndLoadMetadata.isSideEffectImport; + } +}); -var _create = require("babel-runtime/core-js/object/create"); +var _assert = _interopRequireDefault(require("assert")); -var _create2 = _interopRequireDefault(_create); +var t = _interopRequireWildcard(require("@babel/types")); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _template = _interopRequireDefault(require("@babel/template")); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var _chunk = _interopRequireDefault(require("lodash/chunk")); -var _symbol = require("babel-runtime/core-js/symbol"); +var _helperModuleImports = require("@babel/helper-module-imports"); -var _symbol2 = _interopRequireDefault(_symbol); +var _rewriteThis = _interopRequireDefault(require("./rewrite-this")); -exports.default = function (_ref) { - var t = _ref.types; +var _rewriteLiveReferences = _interopRequireDefault(require("./rewrite-live-references")); - var IGNORE_REASSIGNMENT_SYMBOL = (0, _symbol2.default)(); +var _normalizeAndLoadMetadata = _interopRequireWildcard(require("./normalize-and-load-metadata")); - var reassignmentVisitor = { - "AssignmentExpression|UpdateExpression": function AssignmentExpressionUpdateExpression(path) { - if (path.node[IGNORE_REASSIGNMENT_SYMBOL]) return; - path.node[IGNORE_REASSIGNMENT_SYMBOL] = true; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - var arg = path.get(path.isAssignmentExpression() ? "left" : "argument"); - if (!arg.isIdentifier()) return; + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - var name = arg.node.name; + return cache; +} - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - var exportedNames = this.exports[name]; - if (!exportedNames) return; + var cache = _getRequireWildcardCache(); - var node = path.node; + if (cache && cache.has(obj)) { + return cache.get(obj); + } - var isPostUpdateExpression = path.isUpdateExpression() && !node.prefix; - if (isPostUpdateExpression) { - if (node.operator === "++") node = t.binaryExpression("+", node.argument, t.numericLiteral(1));else if (node.operator === "--") node = t.binaryExpression("-", node.argument, t.numericLiteral(1));else isPostUpdateExpression = false; - } + var newObj = {}; + + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var _iterator = exportedNames, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; + newObj[key] = obj[key]; } - - var exportedName = _ref2; - - node = this.buildCall(exportedName, node).expression; } - - if (isPostUpdateExpression) node = t.sequenceExpression([node, path.node]); - - path.replaceWith(node); } - }; - - return { - visitor: { - CallExpression: function CallExpression(path, state) { - if (path.node.callee.type === TYPE_IMPORT) { - var contextIdent = state.contextIdent; - path.replaceWith(t.callExpression(t.memberExpression(contextIdent, t.identifier("import")), path.node.arguments)); - } - }, - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (path.node.name == "__moduleName" && !path.scope.hasBinding("__moduleName")) { - path.replaceWith(t.memberExpression(state.contextIdent, t.identifier("id"))); - } - }, - - - Program: { - enter: function enter(path, state) { - state.contextIdent = path.scope.generateUidIdentifier("context"); - }, - exit: function exit(path, state) { - var exportIdent = path.scope.generateUidIdentifier("export"); - var contextIdent = state.contextIdent; + } - var exportNames = (0, _create2.default)(null); - var modules = []; + newObj.default = obj; - var beforeBody = []; - var setters = []; - var sources = []; - var variableIds = []; - var removedPaths = []; + if (cache) { + cache.set(obj, newObj); + } - function addExportName(key, val) { - exportNames[key] = exportNames[key] || []; - exportNames[key].push(val); - } + return newObj; +} - function pushModule(source, key, specifiers) { - var module = void 0; - modules.forEach(function (m) { - if (m.key === source) { - module = m; - } - }); - if (!module) { - modules.push(module = { key: source, imports: [], exports: [] }); - } - module[key] = module[key].concat(specifiers); - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - function buildExportCall(name, val) { - return t.expressionStatement(t.callExpression(exportIdent, [t.stringLiteral(name), val])); - } +function rewriteModuleStatementsAndPrepareHeader(path, _ref) { + var exportName = _ref.exportName, + strict = _ref.strict, + allowTopLevelThis = _ref.allowTopLevelThis, + strictMode = _ref.strictMode, + loose = _ref.loose, + noInterop = _ref.noInterop, + lazy = _ref.lazy, + esNamespaceOnly = _ref.esNamespaceOnly; + (0, _assert.default)((0, _helperModuleImports.isModule)(path), "Cannot process module statements in a script"); + path.node.sourceType = "script"; + var meta = (0, _normalizeAndLoadMetadata.default)(path, exportName, { + noInterop: noInterop, + loose: loose, + lazy: lazy, + esNamespaceOnly: esNamespaceOnly + }); - var body = path.get("body"); + if (!allowTopLevelThis) { + (0, _rewriteThis.default)(path); + } - var canHoist = true; - for (var _iterator2 = body, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; + (0, _rewriteLiveReferences.default)(path, meta); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } + if (strictMode !== false) { + var hasStrict = path.node.directives.some(function (directive) { + return directive.value.value === "use strict"; + }); - var _path = _ref3; + if (!hasStrict) { + path.unshiftContainer("directives", t.directive(t.directiveLiteral("use strict"))); + } + } - if (_path.isExportDeclaration()) _path = _path.get("declaration"); - if (_path.isVariableDeclaration() && _path.node.kind !== "var") { - canHoist = false; - break; - } - } + var headers = []; - for (var _iterator3 = body, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref4; + if ((0, _normalizeAndLoadMetadata.hasExports)(meta) && !strict) { + headers.push(buildESModuleHeader(meta, loose)); + } - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } - - var _path2 = _ref4; - - if (canHoist && _path2.isFunctionDeclaration()) { - beforeBody.push(_path2.node); - removedPaths.push(_path2); - } else if (_path2.isImportDeclaration()) { - var source = _path2.node.source.value; - pushModule(source, "imports", _path2.node.specifiers); - for (var name in _path2.getBindingIdentifiers()) { - _path2.scope.removeBinding(name); - variableIds.push(t.identifier(name)); - } - _path2.remove(); - } else if (_path2.isExportAllDeclaration()) { - pushModule(_path2.node.source.value, "exports", _path2.node); - _path2.remove(); - } else if (_path2.isExportDefaultDeclaration()) { - var declar = _path2.get("declaration"); - if (declar.isClassDeclaration() || declar.isFunctionDeclaration()) { - var id = declar.node.id; - var nodes = []; + var nameList = buildExportNameListDeclaration(path, meta); - if (id) { - nodes.push(declar.node); - nodes.push(buildExportCall("default", id)); - addExportName(id.name, "default"); - } else { - nodes.push(buildExportCall("default", t.toExpression(declar.node))); - } + if (nameList) { + meta.exportNameListName = nameList.name; + headers.push(nameList.statement); + } - if (!canHoist || declar.isClassDeclaration()) { - _path2.replaceWithMultiple(nodes); - } else { - beforeBody = beforeBody.concat(nodes); - removedPaths.push(_path2); - } - } else { - _path2.replaceWith(buildExportCall("default", declar.node)); - } - } else if (_path2.isExportNamedDeclaration()) { - var _declar = _path2.get("declaration"); - - if (_declar.node) { - _path2.replaceWith(_declar); - - var _nodes = []; - var bindingIdentifiers = void 0; - if (_path2.isFunction()) { - var node = _declar.node; - var _name = node.id.name; - if (canHoist) { - addExportName(_name, _name); - beforeBody.push(node); - beforeBody.push(buildExportCall(_name, node.id)); - removedPaths.push(_path2); - } else { - var _bindingIdentifiers; + headers.push.apply(headers, _toConsumableArray(buildExportInitializationStatements(path, meta, loose))); + return { + meta: meta, + headers: headers + }; +} - bindingIdentifiers = (_bindingIdentifiers = {}, _bindingIdentifiers[_name] = node.id, _bindingIdentifiers); - } - } else { - bindingIdentifiers = _declar.getBindingIdentifiers(); - } - for (var _name2 in bindingIdentifiers) { - addExportName(_name2, _name2); - _nodes.push(buildExportCall(_name2, t.identifier(_name2))); - } - _path2.insertAfter(_nodes); - } else { - var specifiers = _path2.node.specifiers; - if (specifiers && specifiers.length) { - if (_path2.node.source) { - pushModule(_path2.node.source.value, "exports", specifiers); - _path2.remove(); - } else { - var _nodes2 = []; - - for (var _iterator7 = specifiers, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref8; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref8 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref8 = _i7.value; - } +function ensureStatementsHoisted(statements) { + statements.forEach(function (header) { + header._blockHoist = 3; + }); +} - var specifier = _ref8; +function wrapInterop(programPath, expr, type) { + if (type === "none") { + return null; + } - _nodes2.push(buildExportCall(specifier.exported.name, specifier.local)); - addExportName(specifier.local.name, specifier.exported.name); - } + var helper; - _path2.replaceWithMultiple(_nodes2); - } - } - } - } - } + if (type === "default") { + helper = "interopRequireDefault"; + } else if (type === "namespace") { + helper = "interopRequireWildcard"; + } else { + throw new Error("Unknown interop: ".concat(type)); + } - modules.forEach(function (specifiers) { - var setterBody = []; - var target = path.scope.generateUidIdentifier(specifiers.key); + return t.callExpression(programPath.hub.addHelper(helper), [expr]); +} - for (var _iterator4 = specifiers.imports, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref5; +function buildNamespaceInitStatements(metadata, sourceMetadata) { + var loose = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var statements = []; + var srcNamespace = t.identifier(sourceMetadata.name); + if (sourceMetadata.lazy) srcNamespace = t.callExpression(srcNamespace, []); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref5 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref5 = _i4.value; - } + try { + for (var _iterator = sourceMetadata.importsNamespace[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var localName = _step.value; + if (localName === sourceMetadata.name) continue; + statements.push(_template.default.statement(_templateObject())({ + NAME: localName, + SOURCE: t.cloneNode(srcNamespace) + })); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } - var specifier = _ref5; + if (loose) { + statements.push.apply(statements, _toConsumableArray(buildReexportsFromMeta(metadata, sourceMetadata, loose))); + } - if (t.isImportNamespaceSpecifier(specifier)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", specifier.local, target))); - } else if (t.isImportDefaultSpecifier(specifier)) { - specifier = t.importSpecifier(specifier.local, t.identifier("default")); - } + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - if (t.isImportSpecifier(specifier)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", specifier.local, t.memberExpression(target, specifier.imported)))); - } - } + try { + for (var _iterator2 = sourceMetadata.reexportNamespace[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var exportName = _step2.value; + statements.push((sourceMetadata.lazy ? _template.default.statement(_templateObject2()) : _template.default.statement(_templateObject3()))({ + EXPORTS: metadata.exportName, + NAME: exportName, + NAMESPACE: t.cloneNode(srcNamespace) + })); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } - if (specifiers.exports.length) { - var exportObjRef = path.scope.generateUidIdentifier("exportObj"); + if (sourceMetadata.reexportAll) { + var statement = buildNamespaceReexport(metadata, t.cloneNode(srcNamespace), loose); + statement.loc = sourceMetadata.reexportAll.loc; + statements.push(statement); + } - setterBody.push(t.variableDeclaration("var", [t.variableDeclarator(exportObjRef, t.objectExpression([]))])); + return statements; +} - for (var _iterator5 = specifiers.exports, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref6; +var getTemplateForReexport = function getTemplateForReexport(loose) { + return loose ? _template.default.statement(_templateObject4()) : _template.default(_templateObject5()); +}; - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref6 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref6 = _i5.value; - } +var buildReexportsFromMeta = function buildReexportsFromMeta(meta, metadata, loose) { + var namespace = metadata.lazy ? t.callExpression(t.identifier(metadata.name), []) : t.identifier(metadata.name); + var templateForCurrentMode = getTemplateForReexport(loose); + return Array.from(metadata.reexports, function (_ref2) { + var _ref3 = _slicedToArray(_ref2, 2), + exportName = _ref3[0], + importName = _ref3[1]; - var node = _ref6; - - if (t.isExportAllDeclaration(node)) { - setterBody.push(buildExportAll({ - KEY: path.scope.generateUidIdentifier("key"), - EXPORT_OBJ: exportObjRef, - TARGET: target - })); - } else if (t.isExportSpecifier(node)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(exportObjRef, node.exported), t.memberExpression(target, node.local)))); - } else {} - } + return templateForCurrentMode({ + EXPORTS: meta.exportName, + EXPORT_NAME: exportName, + NAMESPACE: t.cloneNode(namespace), + IMPORT_NAME: importName + }); + }); +}; - setterBody.push(t.expressionStatement(t.callExpression(exportIdent, [exportObjRef]))); - } +function buildESModuleHeader(metadata) { + var enumerable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + return (enumerable ? _template.default.statement(_templateObject6()) : _template.default.statement(_templateObject7()))({ + EXPORTS: metadata.exportName + }); +} - sources.push(t.stringLiteral(specifiers.key)); - setters.push(t.functionExpression(null, [target], t.blockStatement(setterBody))); - }); +function buildNamespaceReexport(metadata, namespace, loose) { + return (loose ? _template.default.statement(_templateObject8()) : _template.default.statement(_templateObject9()))({ + NAMESPACE: namespace, + EXPORTS: metadata.exportName, + VERIFY_NAME_LIST: metadata.exportNameListName ? _template.default(_templateObject10())({ + EXPORTS_LIST: metadata.exportNameListName + }) : null + }); +} - var moduleName = this.getModuleName(); - if (moduleName) moduleName = t.stringLiteral(moduleName); +function buildExportNameListDeclaration(programPath, metadata) { + var exportedVars = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; - if (canHoist) { - (0, _babelHelperHoistVariables2.default)(path, function (id) { - return variableIds.push(id); - }); - } + try { + for (var _iterator3 = metadata.local.values()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var data = _step3.value; + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; - if (variableIds.length) { - beforeBody.unshift(t.variableDeclaration("var", variableIds.map(function (id) { - return t.variableDeclarator(id); - }))); + try { + for (var _iterator5 = data.names[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var _name = _step5.value; + exportedVars[_name] = true; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); } - - path.traverse(reassignmentVisitor, { - exports: exportNames, - buildCall: buildExportCall, - scope: path.scope - }); - - for (var _iterator6 = removedPaths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref7; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref7 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref7 = _i6.value; - } - - var _path3 = _ref7; - - _path3.remove(); + } finally { + if (_didIteratorError5) { + throw _iteratorError5; } - - path.node.body = [buildTemplate({ - SYSTEM_REGISTER: t.memberExpression(t.identifier(state.opts.systemGlobal || "System"), t.identifier("register")), - BEFORE_BODY: beforeBody, - MODULE_NAME: moduleName, - SETTERS: setters, - SOURCES: sources, - BODY: path.node.body, - EXPORT_IDENTIFIER: exportIdent, - CONTEXT_IDENTIFIER: contextIdent - })]; } } } - }; -}; - -var _babelHelperHoistVariables = require("babel-helper-hoist-variables"); - -var _babelHelperHoistVariables2 = _interopRequireDefault(_babelHelperHoistVariables); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildTemplate = (0, _babelTemplate2.default)("\n SYSTEM_REGISTER(MODULE_NAME, [SOURCES], function (EXPORT_IDENTIFIER, CONTEXT_IDENTIFIER) {\n \"use strict\";\n BEFORE_BODY;\n return {\n setters: [SETTERS],\n execute: function () {\n BODY;\n }\n };\n });\n"); - -var buildExportAll = (0, _babelTemplate2.default)("\n for (var KEY in TARGET) {\n if (KEY !== \"default\" && KEY !== \"__esModule\") EXPORT_OBJ[KEY] = TARGET[KEY];\n }\n"); - -var TYPE_IMPORT = "Import"; - -module.exports = exports["default"]; -},{"babel-helper-hoist-variables":55,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/create":100,"babel-runtime/core-js/symbol":104,"babel-template":114}],80:[function(require,module,exports){ -"use strict"; + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } -exports.__esModule = true; + var hasReexport = false; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; -exports.default = function (_ref) { - var t = _ref.types; + try { + for (var _iterator4 = metadata.source.values()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _data = _step4.value; + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; - function isValidDefine(path) { - if (!path.isExpressionStatement()) return; + try { + for (var _iterator6 = _data.reexports.keys()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var exportName = _step6.value; + exportedVars[exportName] = true; + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } - var expr = path.get("expression"); - if (!expr.isCallExpression()) return false; - if (!expr.get("callee").isIdentifier({ name: "define" })) return false; + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; - var args = expr.get("arguments"); - if (args.length === 3 && !args.shift().isStringLiteral()) return false; - if (args.length !== 2) return false; - if (!args.shift().isArrayExpression()) return false; - if (!args.shift().isFunctionExpression()) return false; + try { + for (var _iterator7 = _data.reexportNamespace[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var _exportName = _step7.value; + exportedVars[_exportName] = true; + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } - return true; + hasReexport = hasReexport || _data.reexportAll; + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } } + if (!hasReexport || Object.keys(exportedVars).length === 0) return null; + var name = programPath.scope.generateUidIdentifier("exportNames"); + delete exportedVars.default; return { - inherits: require("babel-plugin-transform-es2015-modules-amd"), - - visitor: { - Program: { - exit: function exit(path, state) { - var last = path.get("body").pop(); - if (!isValidDefine(last)) return; - - var call = last.node.expression; - var args = call.arguments; + name: name.name, + statement: t.variableDeclaration("var", [t.variableDeclarator(name, t.valueToNode(exportedVars))]) + }; +} - var moduleName = args.length === 3 ? args.shift() : null; - var amdArgs = call.arguments[0]; - var func = call.arguments[1]; - var browserGlobals = state.opts.globals || {}; +function buildExportInitializationStatements(programPath, metadata) { + var loose = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var initStatements = []; + var exportNames = []; + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; - var commonArgs = amdArgs.elements.map(function (arg) { - if (arg.value === "module" || arg.value === "exports") { - return t.identifier(arg.value); - } else { - return t.callExpression(t.identifier("require"), [arg]); - } - }); + try { + for (var _iterator8 = metadata.local[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _step8$value = _slicedToArray(_step8.value, 2), + localName = _step8$value[0], + data = _step8$value[1]; - var browserArgs = amdArgs.elements.map(function (arg) { - if (arg.value === "module") { - return t.identifier("mod"); - } else if (arg.value === "exports") { - return t.memberExpression(t.identifier("mod"), t.identifier("exports")); - } else { - var memberExpression = void 0; - - if (state.opts.exactGlobals) { - var globalRef = browserGlobals[arg.value]; - if (globalRef) { - memberExpression = globalRef.split(".").reduce(function (accum, curr) { - return t.memberExpression(accum, t.identifier(curr)); - }, t.identifier("global")); - } else { - memberExpression = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(arg.value))); - } - } else { - var requireName = (0, _path.basename)(arg.value, (0, _path.extname)(arg.value)); - var globalName = browserGlobals[requireName] || requireName; - memberExpression = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(globalName))); - } + if (data.kind === "import") {} else if (data.kind === "hoisted") { + initStatements.push(buildInitStatement(metadata, data.names, t.identifier(localName))); + } else { + exportNames.push.apply(exportNames, _toConsumableArray(data.names)); + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } - return memberExpression; - } - }); + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; - var moduleNameOrBasename = moduleName ? moduleName.value : this.file.opts.basename; - var globalToAssign = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(moduleNameOrBasename))); - var prerequisiteAssignments = null; + try { + for (var _iterator9 = metadata.source.values()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var _data2 = _step9.value; - if (state.opts.exactGlobals) { - var globalName = browserGlobals[moduleNameOrBasename]; + if (!loose) { + initStatements.push.apply(initStatements, _toConsumableArray(buildReexportsFromMeta(metadata, _data2, loose))); + } - if (globalName) { - prerequisiteAssignments = []; + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; - var members = globalName.split("."); - globalToAssign = members.slice(1).reduce(function (accum, curr) { - prerequisiteAssignments.push(buildPrerequisiteAssignment({ GLOBAL_REFERENCE: accum })); - return t.memberExpression(accum, t.identifier(curr)); - }, t.memberExpression(t.identifier("global"), t.identifier(members[0]))); - } + try { + for (var _iterator10 = _data2.reexportNamespace[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var exportName = _step10.value; + exportNames.push(exportName); + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; } - - var globalExport = buildGlobalExport({ - BROWSER_ARGUMENTS: browserArgs, - PREREQUISITE_ASSIGNMENTS: prerequisiteAssignments, - GLOBAL_TO_ASSIGN: globalToAssign - }); - - last.replaceWith(buildWrapper({ - MODULE_NAME: moduleName, - AMD_ARGUMENTS: amdArgs, - COMMON_ARGUMENTS: commonArgs, - GLOBAL_EXPORT: globalExport, - FUNC: func - })); } } } - }; -}; - -var _path = require("path"); + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } -var _babelTemplate = require("babel-template"); + initStatements.push.apply(initStatements, _toConsumableArray((0, _chunk.default)(exportNames, 100).map(function (members) { + return buildInitStatement(metadata, members, programPath.scope.buildUndefinedNode()); + }))); + return initStatements; +} -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); +function buildInitStatement(metadata, exportNames, initExpr) { + return t.expressionStatement(exportNames.reduce(function (acc, exportName) { + return _template.default.expression(_templateObject11())({ + EXPORTS: metadata.exportName, + NAME: exportName, + VALUE: acc + }); + }, initExpr)); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +},{"./normalize-and-load-metadata":75,"./rewrite-live-references":76,"./rewrite-this":77,"@babel/helper-module-imports":72,"@babel/template":167,"@babel/types":242,"assert":278,"lodash/chunk":1003}],75:[function(require,module,exports){ +"use strict"; -var buildPrerequisiteAssignment = (0, _babelTemplate2.default)("\n GLOBAL_REFERENCE = GLOBAL_REFERENCE || {}\n"); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -var buildGlobalExport = (0, _babelTemplate2.default)("\n var mod = { exports: {} };\n factory(BROWSER_ARGUMENTS);\n PREREQUISITE_ASSIGNMENTS\n GLOBAL_TO_ASSIGN = mod.exports;\n"); +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -var buildWrapper = (0, _babelTemplate2.default)("\n (function (global, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(MODULE_NAME, AMD_ARGUMENTS, factory);\n } else if (typeof exports !== \"undefined\") {\n factory(COMMON_ARGUMENTS);\n } else {\n GLOBAL_EXPORT\n }\n })(this, FUNC);\n"); +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -module.exports = exports["default"]; -},{"babel-plugin-transform-es2015-modules-amd":77,"babel-template":114,"path":522}],81:[function(require,module,exports){ -"use strict"; +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasExports = hasExports; +exports.isSideEffectImport = isSideEffectImport; +exports.default = normalizeModuleAndLoadMetadata; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _path = require("path"); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var _helperSplitExportDeclaration = _interopRequireDefault(require("@babel/helper-split-export-declaration")); -var _symbol = require("babel-runtime/core-js/symbol"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} -var _symbol2 = _interopRequireDefault(_symbol); +function hasExports(metadata) { + return metadata.hasExports; +} -exports.default = function (_ref) { - var t = _ref.types; +function isSideEffectImport(source) { + return source.imports.size === 0 && source.importsNamespace.size === 0 && source.reexports.size === 0 && source.reexportNamespace.size === 0 && !source.reexportAll; +} - function Property(path, node, scope, getObjectRef, file) { - var replaceSupers = new _babelHelperReplaceSupers2.default({ - getObjectRef: getObjectRef, - methodNode: node, - methodPath: path, - isStatic: true, - scope: scope, - file: file - }); +function normalizeModuleAndLoadMetadata(programPath, exportName) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref$noInterop = _ref.noInterop, + noInterop = _ref$noInterop === void 0 ? false : _ref$noInterop, + _ref$loose = _ref.loose, + loose = _ref$loose === void 0 ? false : _ref$loose, + _ref$lazy = _ref.lazy, + lazy = _ref$lazy === void 0 ? false : _ref$lazy, + _ref$esNamespaceOnly = _ref.esNamespaceOnly, + esNamespaceOnly = _ref$esNamespaceOnly === void 0 ? false : _ref$esNamespaceOnly; - replaceSupers.replace(); + if (!exportName) { + exportName = programPath.scope.generateUidIdentifier("exports").name; } - var CONTAINS_SUPER = (0, _symbol2.default)(); + nameAnonymousExports(programPath); - return { - visitor: { - Super: function Super(path) { - var parentObj = path.findParent(function (path) { - return path.isObjectExpression(); - }); - if (parentObj) parentObj.node[CONTAINS_SUPER] = true; - }, + var _getModuleMetadata = getModuleMetadata(programPath, { + loose: loose, + lazy: lazy + }), + local = _getModuleMetadata.local, + source = _getModuleMetadata.source, + hasExports = _getModuleMetadata.hasExports; + removeModuleDeclarations(programPath); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - ObjectExpression: { - exit: function exit(path, file) { - if (!path.node[CONTAINS_SUPER]) return; + try { + for (var _iterator = source[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _step$value = _slicedToArray(_step.value, 2), + metadata = _step$value[1]; - var objectRef = void 0; - var getObjectRef = function getObjectRef() { - return objectRef = objectRef || path.scope.generateUidIdentifier("obj"); - }; + if (metadata.importsNamespace.size > 0) { + metadata.name = metadata.importsNamespace.values().next().value; + } - var propPaths = path.get("properties"); - for (var _iterator = propPaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; + if (noInterop) metadata.interop = "none";else if (esNamespaceOnly) { + if (metadata.interop === "namespace") { + metadata.interop = "default"; + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } + return { + exportName: exportName, + exportNameListName: null, + hasExports: hasExports, + local: local, + source: source + }; +} - var propPath = _ref2; +function getModuleMetadata(programPath, _ref2) { + var loose = _ref2.loose, + lazy = _ref2.lazy; + var localData = getLocalExportMetadata(programPath, loose); + var sourceData = new Map(); + + var getData = function getData(sourceNode) { + var source = sourceNode.value; + var data = sourceData.get(source); + + if (!data) { + data = { + name: programPath.scope.generateUidIdentifier((0, _path.basename)(source, (0, _path.extname)(source))).name, + interop: "none", + loc: null, + imports: new Map(), + importsNamespace: new Set(), + reexports: new Map(), + reexportNamespace: new Set(), + reexportAll: null, + lazy: false + }; + sourceData.set(source, data); + } - if (propPath.isObjectProperty()) propPath = propPath.get("value"); - Property(propPath, propPath.node, path.scope, getObjectRef, file); - } + return data; + }; - if (objectRef) { - path.scope.push({ id: objectRef }); - path.replaceWith(t.assignmentExpression("=", objectRef, path.node)); + var hasExports = false; + programPath.get("body").forEach(function (child) { + if (child.isImportDeclaration()) { + var data = getData(child.node.source); + if (!data.loc) data.loc = child.node.loc; + child.get("specifiers").forEach(function (spec) { + if (spec.isImportDefaultSpecifier()) { + var localName = spec.get("local").node.name; + data.imports.set(localName, "default"); + var reexport = localData.get(localName); + + if (reexport) { + localData.delete(localName); + reexport.names.forEach(function (name) { + data.reexports.set(name, "default"); + }); } - } - } - } - }; -}; + } else if (spec.isImportNamespaceSpecifier()) { + var _localName = spec.get("local").node.name; + data.importsNamespace.add(_localName); -var _babelHelperReplaceSupers = require("babel-helper-replace-supers"); + var _reexport = localData.get(_localName); -var _babelHelperReplaceSupers2 = _interopRequireDefault(_babelHelperReplaceSupers); + if (_reexport) { + localData.delete(_localName); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _reexport.names.forEach(function (name) { + data.reexportNamespace.add(name); + }); + } + } else if (spec.isImportSpecifier()) { + var importName = spec.get("imported").node.name; + var _localName2 = spec.get("local").node.name; + data.imports.set(_localName2, importName); -module.exports = exports["default"]; -},{"babel-helper-replace-supers":58,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/symbol":104}],82:[function(require,module,exports){ -"use strict"; + var _reexport2 = localData.get(_localName2); -exports.__esModule = true; -exports.visitor = undefined; + if (_reexport2) { + localData.delete(_localName2); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + _reexport2.names.forEach(function (name) { + data.reexports.set(name, importName); + }); + } + } + }); + } else if (child.isExportAllDeclaration()) { + hasExports = true; -var _getIterator3 = _interopRequireDefault(_getIterator2); + var _data = getData(child.node.source); -var _babelHelperGetFunctionArity = require("babel-helper-get-function-arity"); + if (!_data.loc) _data.loc = child.node.loc; + _data.reexportAll = { + loc: child.node.loc + }; + } else if (child.isExportNamedDeclaration() && child.node.source) { + hasExports = true; -var _babelHelperGetFunctionArity2 = _interopRequireDefault(_babelHelperGetFunctionArity); + var _data2 = getData(child.node.source); -var _babelHelperCallDelegate = require("babel-helper-call-delegate"); + if (!_data2.loc) _data2.loc = child.node.loc; + child.get("specifiers").forEach(function (spec) { + if (!spec.isExportSpecifier()) { + throw spec.buildCodeFrameError("Unexpected export specifier type"); + } -var _babelHelperCallDelegate2 = _interopRequireDefault(_babelHelperCallDelegate); + var importName = spec.get("local").node.name; + var exportName = spec.get("exported").node.name; -var _babelTemplate = require("babel-template"); + _data2.reexports.set(exportName, importName); -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + if (exportName === "__esModule") { + throw exportName.buildCodeFrameError('Illegal export "__esModule".'); + } + }); + } else if (child.isExportNamedDeclaration() || child.isExportDefaultDeclaration()) { + hasExports = true; + } + }); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; -var _babelTypes = require("babel-types"); + try { + for (var _iterator2 = sourceData.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var metadata = _step2.value; + var needsDefault = false; + var needsNamed = false; -var t = _interopRequireWildcard(_babelTypes); + if (metadata.importsNamespace.size > 0) { + needsDefault = true; + needsNamed = true; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (metadata.reexportAll) { + needsNamed = true; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; -var buildDefaultParam = (0, _babelTemplate2.default)("\n let VARIABLE_NAME =\n ARGUMENTS.length > ARGUMENT_KEY && ARGUMENTS[ARGUMENT_KEY] !== undefined ?\n ARGUMENTS[ARGUMENT_KEY]\n :\n DEFAULT_VALUE;\n"); + try { + for (var _iterator4 = metadata.imports.values()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var importName = _step4.value; + if (importName === "default") needsDefault = true;else needsNamed = true; + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } -var buildCutOff = (0, _babelTemplate2.default)("\n let $0 = $1[$2];\n"); + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; -function hasDefaults(node) { - for (var _iterator = node.params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + try { + for (var _iterator5 = metadata.reexports.values()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var _importName = _step5.value; + if (_importName === "default") needsDefault = true;else needsNamed = true; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + if (needsDefault && needsNamed) { + metadata.interop = "namespace"; + } else if (needsDefault) { + metadata.interop = "default"; + } } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } - var param = _ref; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; - if (!t.isIdentifier(param)) return true; - } - return false; -} - -function isSafeBinding(scope, node) { - if (!scope.hasOwnBinding(node.name)) return true; - - var _scope$getOwnBinding = scope.getOwnBinding(node.name), - kind = _scope$getOwnBinding.kind; + try { + for (var _iterator3 = sourceData[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _step3$value = _slicedToArray(_step3.value, 2), + source = _step3$value[0], + _metadata = _step3$value[1]; + + if (lazy !== false && !(isSideEffectImport(_metadata) || _metadata.reexportAll)) { + if (lazy === true) { + _metadata.lazy = !/\./.test(source); + } else if (Array.isArray(lazy)) { + _metadata.lazy = lazy.indexOf(source) !== -1; + } else if (typeof lazy === "function") { + _metadata.lazy = lazy(source); + } else { + throw new Error(".lazy must be a boolean, string array, or function"); + } + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } - return kind === "param" || kind === "local"; + return { + hasExports: hasExports, + local: localData, + source: sourceData + }; } -var iifeVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - var scope = path.scope, - node = path.node; +function getLocalExportMetadata(programPath, loose) { + var bindingKindLookup = new Map(); + programPath.get("body").forEach(function (child) { + var kind; - if (node.name === "eval" || !isSafeBinding(scope, node)) { - state.iife = true; - path.stop(); + if (child.isImportDeclaration()) { + kind = "import"; + } else { + if (child.isExportDefaultDeclaration()) child = child.get("declaration"); + + if (child.isExportNamedDeclaration()) { + if (child.node.declaration) { + child = child.get("declaration"); + } else if (loose && child.node.source && child.get("source").isStringLiteral()) { + child.node.specifiers.forEach(function (specifier) { + bindingKindLookup.set(specifier.local.name, "block"); + }); + return; + } + } + + if (child.isFunctionDeclaration()) { + kind = "hoisted"; + } else if (child.isClassDeclaration()) { + kind = "block"; + } else if (child.isVariableDeclaration({ + kind: "var" + })) { + kind = "var"; + } else if (child.isVariableDeclaration()) { + kind = "block"; + } else { + return; + } } - }, - Scope: function Scope(path) { - path.skip(); - } -}; -var visitor = exports.visitor = { - Function: function Function(path) { - var node = path.node, - scope = path.scope; + Object.keys(child.getOuterBindingIdentifiers()).forEach(function (name) { + bindingKindLookup.set(name, kind); + }); + }); + var localMetadata = new Map(); - if (!hasDefaults(node)) return; + var getLocalMetadata = function getLocalMetadata(idPath) { + var localName = idPath.node.name; + var metadata = localMetadata.get(localName); - path.ensureBlock(); + if (!metadata) { + var kind = bindingKindLookup.get(localName); - var state = { - iife: false, - scope: scope - }; + if (kind === undefined) { + throw idPath.buildCodeFrameError("Exporting local \"".concat(localName, "\", which is not declared.")); + } - var body = []; + metadata = { + names: [], + kind: kind + }; + localMetadata.set(localName, metadata); + } - var argsIdentifier = t.identifier("arguments"); - argsIdentifier._shadowedFunctionLiteral = path; + return metadata; + }; - function pushDefNode(left, right, i) { - var defNode = buildDefaultParam({ - VARIABLE_NAME: left, - DEFAULT_VALUE: right, - ARGUMENT_KEY: t.numericLiteral(i), - ARGUMENTS: argsIdentifier - }); - defNode._blockHoist = node.params.length - i; - body.push(defNode); - } + programPath.get("body").forEach(function (child) { + if (child.isExportNamedDeclaration() && (loose || !child.node.source)) { + if (child.node.declaration) { + var declaration = child.get("declaration"); + var ids = declaration.getOuterBindingIdentifierPaths(); + Object.keys(ids).forEach(function (name) { + if (name === "__esModule") { + throw declaration.buildCodeFrameError('Illegal export "__esModule".'); + } - var lastNonDefaultParam = (0, _babelHelperGetFunctionArity2.default)(node); + getLocalMetadata(ids[name]).names.push(name); + }); + } else { + child.get("specifiers").forEach(function (spec) { + var local = spec.get("local"); + var exported = spec.get("exported"); - var params = path.get("params"); - for (var i = 0; i < params.length; i++) { - var param = params[i]; + if (exported.node.name === "__esModule") { + throw exported.buildCodeFrameError('Illegal export "__esModule".'); + } - if (!param.isAssignmentPattern()) { - if (!state.iife && !param.isIdentifier()) { - param.traverse(iifeVisitor, state); - } + getLocalMetadata(local).names.push(exported.node.name); + }); + } + } else if (child.isExportDefaultDeclaration()) { + var _declaration = child.get("declaration"); - continue; + if (_declaration.isFunctionDeclaration() || _declaration.isClassDeclaration()) { + getLocalMetadata(_declaration.get("id")).names.push("default"); + } else { + throw _declaration.buildCodeFrameError("Unexpected default expression export."); } + } + }); + return localMetadata; +} - var left = param.get("left"); - var right = param.get("right"); +function nameAnonymousExports(programPath) { + programPath.get("body").forEach(function (child) { + if (!child.isExportDefaultDeclaration()) return; + (0, _helperSplitExportDeclaration.default)(child); + }); +} - if (i >= lastNonDefaultParam || left.isPattern()) { - var placeholder = scope.generateUidIdentifier("x"); - placeholder._isDefaultPlaceholder = true; - node.params[i] = placeholder; +function removeModuleDeclarations(programPath) { + programPath.get("body").forEach(function (child) { + if (child.isImportDeclaration()) { + child.remove(); + } else if (child.isExportNamedDeclaration()) { + if (child.node.declaration) { + child.node.declaration._blockHoist = child.node._blockHoist; + child.replaceWith(child.node.declaration); } else { - node.params[i] = left.node; + child.remove(); } + } else if (child.isExportDefaultDeclaration()) { + var declaration = child.get("declaration"); - if (!state.iife) { - if (right.isIdentifier() && !isSafeBinding(scope, right.node)) { - state.iife = true; - } else { - right.traverse(iifeVisitor, state); - } + if (declaration.isFunctionDeclaration() || declaration.isClassDeclaration()) { + declaration._blockHoist = child.node._blockHoist; + child.replaceWith(declaration); + } else { + throw declaration.buildCodeFrameError("Unexpected default expression export."); } - - pushDefNode(left.node, right.node, i); + } else if (child.isExportAllDeclaration()) { + child.remove(); } + }); +} - for (var _i2 = lastNonDefaultParam + 1; _i2 < node.params.length; _i2++) { - var _param = node.params[_i2]; - if (_param._isDefaultPlaceholder) continue; - - var declar = buildCutOff(_param, argsIdentifier, t.numericLiteral(_i2)); - declar._blockHoist = node.params.length - _i2; - body.push(declar); - } +},{"@babel/helper-split-export-declaration":84,"path":1052}],76:[function(require,module,exports){ +"use strict"; - node.params = node.params.slice(0, lastNonDefaultParam); +function _templateObject() { + var data = _taggedTemplateLiteral(["\n (function() {\n throw new Error('\"' + '", "' + '\" is read-only.');\n })()\n "]); - if (state.iife) { - body.push((0, _babelHelperCallDelegate2.default)(path, scope)); - path.set("body", t.blockStatement(body)); - } else { - path.get("body").unshiftContainer("body", body); - } - } -}; -},{"babel-helper-call-delegate":51,"babel-helper-get-function-arity":54,"babel-runtime/core-js/get-iterator":95,"babel-template":114,"babel-types":151}],83:[function(require,module,exports){ -"use strict"; + _templateObject = function _templateObject() { + return data; + }; -exports.__esModule = true; -exports.visitor = undefined; + return data; +} -var _babelTypes = require("babel-types"); +function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } -var t = _interopRequireWildcard(_babelTypes); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -var visitor = exports.visitor = { - Function: function Function(path) { - var params = path.get("params"); +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - var hoistTweak = t.isRestElement(params[params.length - 1]) ? 1 : 0; - var outputParamsLength = params.length - hoistTweak; +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - for (var i = 0; i < outputParamsLength; i++) { - var param = params[i]; - if (param.isArrayPattern() || param.isObjectPattern()) { - var uid = path.scope.generateUidIdentifier("ref"); +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } - var declar = t.variableDeclaration("let", [t.variableDeclarator(param.node, uid)]); - declar._blockHoist = outputParamsLength - i; +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } - path.ensureBlock(); - path.get("body").unshiftContainer("body", declar); +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } - param.replaceWith(uid); - } - } - } -}; -},{"babel-types":151}],84:[function(require,module,exports){ -"use strict"; +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rewriteLiveReferences; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _assert = _interopRequireDefault(require("assert")); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var t = _interopRequireWildcard(require("@babel/types")); -exports.default = function () { - return { - visitor: _babelTraverse.visitors.merge([{ - ArrowFunctionExpression: function ArrowFunctionExpression(path) { - var params = path.get("params"); - for (var _iterator = params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var _template = _interopRequireDefault(require("@babel/template")); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +var _helperSimpleAccess = _interopRequireDefault(require("@babel/helper-simple-access")); - var param = _ref; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - if (param.isRestElement() || param.isAssignmentPattern()) { - path.arrowFunctionToShadowed(); - break; - } - } - } - }, destructuring.visitor, rest.visitor, def.visitor]) + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; -}; -var _babelTraverse = require("babel-traverse"); + return cache; +} -var _destructuring = require("./destructuring"); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -var destructuring = _interopRequireWildcard(_destructuring); + var cache = _getRequireWildcardCache(); -var _default = require("./default"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var def = _interopRequireWildcard(_default); + var newObj = {}; -var _rest = require("./rest"); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -var rest = _interopRequireWildcard(_rest); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + newObj.default = obj; -module.exports = exports["default"]; -},{"./default":82,"./destructuring":83,"./rest":85,"babel-runtime/core-js/get-iterator":95,"babel-traverse":118}],85:[function(require,module,exports){ -"use strict"; + if (cache) { + cache.set(obj, newObj); + } -exports.__esModule = true; -exports.visitor = undefined; + return newObj; +} -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} -var _getIterator3 = _interopRequireDefault(_getIterator2); +function rewriteLiveReferences(programPath, metadata) { + var imported = new Map(); + var exported = new Map(); -var _babelTemplate = require("babel-template"); + var requeueInParent = function requeueInParent(path) { + programPath.requeue(path); + }; -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; -var _babelTypes = require("babel-types"); + try { + for (var _iterator = metadata.source[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _step$value = _slicedToArray(_step.value, 2), + source = _step$value[0], + data = _step$value[1]; -var t = _interopRequireWildcard(_babelTypes); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + try { + for (var _iterator3 = data.imports[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _step3$value = _slicedToArray(_step3.value, 2), + localName = _step3$value[0], + importName = _step3$value[1]; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + imported.set(localName, [source, importName, null]); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } -var buildRest = (0, _babelTemplate2.default)("\n for (var LEN = ARGUMENTS.length,\n ARRAY = Array(ARRAY_LEN),\n KEY = START;\n KEY < LEN;\n KEY++) {\n ARRAY[ARRAY_KEY] = ARGUMENTS[KEY];\n }\n"); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; -var restIndex = (0, _babelTemplate2.default)("\n ARGUMENTS.length <= INDEX ? undefined : ARGUMENTS[INDEX]\n"); + try { + for (var _iterator4 = data.importsNamespace[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _localName = _step4.value; + imported.set(_localName, [source, null, _localName]); + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } -var restIndexImpure = (0, _babelTemplate2.default)("\n REF = INDEX, ARGUMENTS.length <= REF ? undefined : ARGUMENTS[REF]\n"); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; -var restLength = (0, _babelTemplate2.default)("\n ARGUMENTS.length <= OFFSET ? 0 : ARGUMENTS.length - OFFSET\n"); + try { + for (var _iterator2 = metadata.local[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _exportMeta; -var memberExpressionOptimisationVisitor = { - Scope: function Scope(path, state) { - if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) { - path.skip(); - } - }, - Flow: function Flow(path) { - if (path.isTypeCastExpression()) return; + var _step2$value = _slicedToArray(_step2.value, 2), + local = _step2$value[0], + _data = _step2$value[1]; - path.skip(); - }, + var exportMeta = exported.get(local); + if (!exportMeta) { + exportMeta = []; + exported.set(local, exportMeta); + } - "Function|ClassProperty": function FunctionClassProperty(path, state) { - var oldNoOptimise = state.noOptimise; - state.noOptimise = true; - path.traverse(memberExpressionOptimisationVisitor, state); - state.noOptimise = oldNoOptimise; + (_exportMeta = exportMeta).push.apply(_exportMeta, _toConsumableArray(_data.names)); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + programPath.traverse(rewriteBindingInitVisitor, { + metadata: metadata, + requeueInParent: requeueInParent, + scope: programPath.scope, + exported: exported + }); + (0, _helperSimpleAccess.default)(programPath, new Set([].concat(_toConsumableArray(Array.from(imported.keys())), _toConsumableArray(Array.from(exported.keys()))))); + programPath.traverse(rewriteReferencesVisitor, { + seen: new WeakSet(), + metadata: metadata, + requeueInParent: requeueInParent, + scope: programPath.scope, + imported: imported, + exported: exported, + buildImportReference: function buildImportReference(_ref, identNode) { + var _ref2 = _slicedToArray(_ref, 3), + source = _ref2[0], + importName = _ref2[1], + localName = _ref2[2]; + + var meta = metadata.source.get(source); + + if (localName) { + if (meta.lazy) identNode = t.callExpression(identNode, []); + return identNode; + } + + var namespace = t.identifier(meta.name); + if (meta.lazy) namespace = t.callExpression(namespace, []); + return t.memberExpression(namespace, t.identifier(importName)); + } + }); +} +var rewriteBindingInitVisitor = { + ClassProperty: function ClassProperty(path) { path.skip(); }, + Function: function Function(path) { + path.skip(); + }, + ClassDeclaration: function ClassDeclaration(path) { + var requeueInParent = this.requeueInParent, + exported = this.exported, + metadata = this.metadata; + var id = path.node.id; + if (!id) throw new Error("Expected class to have a name"); + var localName = id.name; + var exportNames = exported.get(localName) || []; - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - var node = path.node; - - if (node.name === "arguments") { - state.deopted = true; + if (exportNames.length > 0) { + var statement = t.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t.identifier(localName))); + statement._blockHoist = path.node._blockHoist; + requeueInParent(path.insertAfter(statement)[0]); } + }, + VariableDeclaration: function VariableDeclaration(path) { + var requeueInParent = this.requeueInParent, + exported = this.exported, + metadata = this.metadata; + Object.keys(path.getOuterBindingIdentifiers()).forEach(function (localName) { + var exportNames = exported.get(localName) || []; - if (node.name !== state.name) return; - - if (state.noOptimise) { - state.deopted = true; - } else { - var parentPath = path.parentPath; - - if (parentPath.listKey === "params" && parentPath.key < state.offset) { - return; + if (exportNames.length > 0) { + var statement = t.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t.identifier(localName))); + statement._blockHoist = path.node._blockHoist; + requeueInParent(path.insertAfter(statement)[0]); } + }); + } +}; - if (parentPath.isMemberExpression({ object: node })) { - var grandparentPath = parentPath.parentPath; +var buildBindingExportAssignmentExpression = function buildBindingExportAssignmentExpression(metadata, exportNames, localExpr) { + return (exportNames || []).reduce(function (expr, exportName) { + return t.assignmentExpression("=", t.memberExpression(t.identifier(metadata.exportName), t.identifier(exportName)), expr); + }, localExpr); +}; - var argsOptEligible = !state.deopted && !(grandparentPath.isAssignmentExpression() && parentPath.node === grandparentPath.node.left || grandparentPath.isLVal() || grandparentPath.isForXStatement() || grandparentPath.isUpdateExpression() || grandparentPath.isUnaryExpression({ operator: "delete" }) || (grandparentPath.isCallExpression() || grandparentPath.isNewExpression()) && parentPath.node === grandparentPath.node.callee); +var buildImportThrow = function buildImportThrow(localName) { + return _template.default.expression.ast(_templateObject(), localName); +}; - if (argsOptEligible) { - if (parentPath.node.computed) { - if (parentPath.get("property").isBaseType("number")) { - state.candidates.push({ cause: "indexGetter", path: path }); - return; - } - } else if (parentPath.node.property.name === "length") { - state.candidates.push({ cause: "lengthGetter", path: path }); - return; - } - } - } +var rewriteReferencesVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(path) { + var seen = this.seen, + buildImportReference = this.buildImportReference, + scope = this.scope, + imported = this.imported, + requeueInParent = this.requeueInParent; + if (seen.has(path.node)) return; + seen.add(path.node); + var localName = path.node.name; + var localBinding = path.scope.getBinding(localName); + var rootBinding = scope.getBinding(localName); + if (rootBinding !== localBinding) return; + var importData = imported.get(localName); - if (state.offset === 0 && parentPath.isSpreadElement()) { - var call = parentPath.parentPath; - if (call.isCallExpression() && call.node.arguments.length === 1) { - state.candidates.push({ cause: "argSpread", path: path }); - return; - } + if (importData) { + var ref = buildImportReference(importData, path.node); + ref.loc = path.node.loc; + + if (path.parentPath.isCallExpression({ + callee: path.node + }) && t.isMemberExpression(ref)) { + path.replaceWith(t.sequenceExpression([t.numericLiteral(0), ref])); + } else if (path.isJSXIdentifier() && t.isMemberExpression(ref)) { + var object = ref.object, + property = ref.property; + path.replaceWith(t.JSXMemberExpression(t.JSXIdentifier(object.name), t.JSXIdentifier(property.name))); + } else { + path.replaceWith(ref); } - state.references.push(path); + requeueInParent(path); + path.skip(); } }, - BindingIdentifier: function BindingIdentifier(_ref, state) { - var node = _ref.node; - - if (node.name === state.name) { - state.deopted = true; - } - } -}; -function hasRest(node) { - return t.isRestElement(node.params[node.params.length - 1]); -} + AssignmentExpression: { + exit: function exit(path) { + var _this = this; -function optimiseIndexGetter(path, argsId, offset) { - var index = void 0; + var scope = this.scope, + seen = this.seen, + imported = this.imported, + exported = this.exported, + requeueInParent = this.requeueInParent, + buildImportReference = this.buildImportReference; + if (seen.has(path.node)) return; + seen.add(path.node); + var left = path.get("left"); + if (left.isMemberExpression()) return; - if (t.isNumericLiteral(path.parent.property)) { - index = t.numericLiteral(path.parent.property.value + offset); - } else if (offset === 0) { - index = path.parent.property; - } else { - index = t.binaryExpression("+", path.parent.property, t.numericLiteral(offset)); - } + if (left.isIdentifier()) { + var localName = left.node.name; - var scope = path.scope; + if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { + return; + } - if (!scope.isPure(index)) { - var temp = scope.generateUidIdentifierBasedOnNode(index); - scope.push({ id: temp, kind: "var" }); - path.parentPath.replaceWith(restIndexImpure({ - ARGUMENTS: argsId, - INDEX: index, - REF: temp - })); - } else { - path.parentPath.replaceWith(restIndex({ - ARGUMENTS: argsId, - INDEX: index - })); - } -} + var exportedNames = exported.get(localName); + var importData = imported.get(localName); -function optimiseLengthGetter(path, argsId, offset) { - if (offset) { - path.parentPath.replaceWith(restLength({ - ARGUMENTS: argsId, - OFFSET: t.numericLiteral(offset) - })); - } else { - path.replaceWith(argsId); - } -} + if ((exportedNames === null || exportedNames === void 0 ? void 0 : exportedNames.length) > 0 || importData) { + (0, _assert.default)(path.node.operator === "=", "Path was not simplified"); + var assignment = path.node; -var visitor = exports.visitor = { - Function: function Function(path) { - var node = path.node, - scope = path.scope; + if (importData) { + assignment.left = buildImportReference(importData, assignment.left); + assignment.right = t.sequenceExpression([assignment.right, buildImportThrow(localName)]); + } - if (!hasRest(node)) return; + path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment)); + requeueInParent(path); + } + } else { + var ids = left.getOuterBindingIdentifiers(); + var programScopeIds = Object.keys(ids).filter(function (localName) { + return scope.getBinding(localName) === path.scope.getBinding(localName); + }); + var id = programScopeIds.find(function (localName) { + return imported.has(localName); + }); - var rest = node.params.pop().argument; + if (id) { + path.node.right = t.sequenceExpression([path.node.right, buildImportThrow(id)]); + } - var argsId = t.identifier("arguments"); + var items = []; + programScopeIds.forEach(function (localName) { + var exportedNames = exported.get(localName) || []; - argsId._shadowedFunctionLiteral = path; + if (exportedNames.length > 0) { + items.push(buildBindingExportAssignmentExpression(_this.metadata, exportedNames, t.identifier(localName))); + } + }); - var state = { - references: [], - offset: node.params.length, + if (items.length > 0) { + var node = t.sequenceExpression(items); - argumentsNode: argsId, - outerBinding: scope.getBindingIdentifier(rest.name), + if (path.parentPath.isExpressionStatement()) { + node = t.expressionStatement(node); + node._blockHoist = path.parentPath.node._blockHoist; + } - candidates: [], + var statement = path.insertAfter(node)[0]; + requeueInParent(statement); + } + } + } + } +}; - name: rest.name, +},{"@babel/helper-simple-access":83,"@babel/template":167,"@babel/types":242,"assert":278}],77:[function(require,module,exports){ +"use strict"; - deopted: false - }; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rewriteThis; - path.traverse(memberExpressionOptimisationVisitor, state); +function rewriteThis(programPath) { + programPath.traverse(rewriteThisVisitor); +} - if (!state.deopted && !state.references.length) { - for (var _iterator = state.candidates, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref3; +var rewriteThisVisitor = { + ThisExpression: function ThisExpression(path) { + path.replaceWith(path.scope.buildUndefinedNode()); + }, + Function: function Function(path) { + if (!path.isArrowFunctionExpression()) path.skip(); + }, + ClassProperty: function ClassProperty(path) { + path.skip(); + }, + ClassPrivateProperty: function ClassPrivateProperty(path) { + path.skip(); + } +}; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref3 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref3 = _i.value; - } +},{}],78:[function(require,module,exports){ +"use strict"; - var _ref4 = _ref3; - var _path = _ref4.path, - cause = _ref4.cause; +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } - switch (cause) { - case "indexGetter": - optimiseIndexGetter(_path, argsId, state.offset); - break; - case "lengthGetter": - optimiseLengthGetter(_path, argsId, state.offset); - break; - default: - _path.replaceWith(argsId); - } - } - return; - } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } - state.references = state.references.concat(state.candidates.map(function (_ref5) { - var path = _ref5.path; - return path; - })); +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } - state.deopted = state.deopted || !!node.shadow; +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } - var start = t.numericLiteral(node.params.length); - var key = scope.generateUidIdentifier("key"); - var len = scope.generateUidIdentifier("len"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; - var arrKey = key; - var arrLen = len; - if (node.params.length) { - arrKey = t.binaryExpression("-", key, start); +var t = _interopRequireWildcard(require("@babel/types")); - arrLen = t.conditionalExpression(t.binaryExpression(">", len, start), t.binaryExpression("-", len, start), t.numericLiteral(0)); - } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - var loop = buildRest({ - ARGUMENTS: argsId, - ARRAY_KEY: arrKey, - ARRAY_LEN: arrLen, - START: start, - ARRAY: rest, - KEY: key, - LEN: len - }); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - if (state.deopted) { - loop._blockHoist = node.params.length + 1; - node.body.body.unshift(loop); - } else { - loop._blockHoist = 1; + return cache; +} - var target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent(); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - target.findParent(function (path) { - if (path.isLoop()) { - target = path; - } else { - return path.isFunction(); - } - }); + var cache = _getRequireWildcardCache(); - target.insertBefore(loop); - } + if (cache && cache.has(obj)) { + return cache.get(obj); } -}; -},{"babel-runtime/core-js/get-iterator":95,"babel-template":114,"babel-types":151}],86:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = function () { - return { - visitor: { - ObjectMethod: function ObjectMethod(path) { - var node = path.node; + var newObj = {}; - if (node.kind === "method") { - var func = t.functionExpression(null, node.params, node.body, node.generator, node.async); - func.returnType = node.returnType; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - path.replaceWith(t.objectProperty(node.key, func, node.computed)); - } - }, - ObjectProperty: function ObjectProperty(_ref) { - var node = _ref.node; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (node.shorthand) { - node.shorthand = false; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; } } } - }; -}; + } + + newObj.default = obj; -var _babelTypes = require("babel-types"); + if (cache) { + cache.set(obj, newObj); + } -var t = _interopRequireWildcard(_babelTypes); + return newObj; +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _default(callee, thisNode, args) { + if (args.length === 1 && t.isSpreadElement(args[0]) && t.isIdentifier(args[0].argument, { + name: "arguments" + })) { + return t.callExpression(t.memberExpression(callee, t.identifier("apply")), [thisNode, args[0].argument]); + } else { + return t.callExpression(t.memberExpression(callee, t.identifier("call")), [thisNode].concat(_toConsumableArray(args))); + } +} -module.exports = exports["default"]; -},{"babel-types":151}],87:[function(require,module,exports){ +},{"@babel/types":242}],79:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.declare = declare; + +function declare(builder) { + return function (api, options, dirname) { + if (!api.assertVersion) { + api = Object.assign(copyApiObject(api), { + assertVersion: function assertVersion(range) { + throwVersionError(range, api.version); + } + }); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + return builder(api, options || {}, dirname); + }; +} -var _getIterator3 = _interopRequireDefault(_getIterator2); +function copyApiObject(api) { + var proto = null; -exports.default = function (_ref) { - var t = _ref.types; + if (typeof api.version === "string" && /^7\./.test(api.version)) { + proto = Object.getPrototypeOf(api); - function getSpreadLiteral(spread, scope, state) { - if (state.opts.loose && !t.isIdentifier(spread.argument, { name: "arguments" })) { - return spread.argument; - } else { - return scope.toArray(spread.argument, true); + if (proto && (!has(proto, "version") || !has(proto, "transform") || !has(proto, "template") || !has(proto, "types"))) { + proto = null; } } - function hasSpread(nodes) { - for (var i = 0; i < nodes.length; i++) { - if (t.isSpreadElement(nodes[i])) { - return true; - } + return Object.assign({}, proto, api); +} + +function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function throwVersionError(range, version) { + if (typeof range === "number") { + if (!Number.isInteger(range)) { + throw new Error("Expected string or integer value."); } - return false; + + range = "^".concat(range, ".0.0-0"); } - function build(props, scope, state) { - var nodes = []; + if (typeof range !== "string") { + throw new Error("Expected string or integer value."); + } - var _props = []; + var limit = Error.stackTraceLimit; - function push() { - if (!_props.length) return; - nodes.push(t.arrayExpression(_props)); - _props = []; - } + if (typeof limit === "number" && limit < 25) { + Error.stackTraceLimit = 25; + } - for (var _iterator = props, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; + var err; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } + if (version.slice(0, 2) === "7.") { + err = new Error("Requires Babel \"^7.0.0-beta.41\", but was loaded with \"".concat(version, "\". ") + "You'll need to update your @babel/core version."); + } else { + err = new Error("Requires Babel \"".concat(range, "\", but was loaded with \"").concat(version, "\". ") + "If you are sure you have a compatible version of @babel/core, " + "it is likely that something in your build process is loading the " + "wrong version. Inspect the stack trace of this error to look for " + "the first entry that doesn't mention \"@babel/core\" or \"babel-core\" " + "to see what is calling Babel."); + } - var prop = _ref2; + if (typeof limit === "number") { + Error.stackTraceLimit = limit; + } - if (t.isSpreadElement(prop)) { - push(); - nodes.push(getSpreadLiteral(prop, scope, state)); - } else { - _props.push(prop); - } - } + throw Object.assign(err, { + code: "BABEL_VERSION_UNSUPPORTED", + version: version, + range: range + }); +} - push(); +},{}],80:[function(require,module,exports){ +"use strict"; - return nodes; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.is = is; +exports.pullFlag = pullFlag; - return { - visitor: { - ArrayExpression: function ArrayExpression(path, state) { - var node = path.node, - scope = path.scope; +function _pull() { + var data = _interopRequireDefault(require("lodash/pull")); - var elements = node.elements; - if (!hasSpread(elements)) return; + _pull = function _pull() { + return data; + }; - var nodes = build(elements, scope, state); - var first = nodes.shift(); + return data; +} - if (!t.isArrayExpression(first)) { - nodes.unshift(first); - first = t.arrayExpression([]); - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - path.replaceWith(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes)); - }, - CallExpression: function CallExpression(path, state) { - var node = path.node, - scope = path.scope; +function is(node, flag) { + return node.type === "RegExpLiteral" && node.flags.indexOf(flag) >= 0; +} +function pullFlag(node, flag) { + var flags = node.flags.split(""); + if (node.flags.indexOf(flag) < 0) return; + (0, _pull().default)(flags, flag); + node.flags = flags.join(""); +} - var args = node.arguments; - if (!hasSpread(args)) return; +},{"lodash/pull":1037}],81:[function(require,module,exports){ +"use strict"; - var calleePath = path.get("callee"); - if (calleePath.isSuper()) return; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; - var contextLiteral = t.identifier("undefined"); +var _helperWrapFunction = _interopRequireDefault(require("@babel/helper-wrap-function")); - node.arguments = []; +var _helperAnnotateAsPure = _interopRequireDefault(require("@babel/helper-annotate-as-pure")); - var nodes = void 0; - if (args.length === 1 && args[0].argument.name === "arguments") { - nodes = [args[0].argument]; - } else { - nodes = build(args, scope, state); - } +var t = _interopRequireWildcard(require("@babel/types")); - var first = nodes.shift(); - if (nodes.length) { - node.arguments.push(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes)); - } else { - node.arguments.push(first); - } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - var callee = node.callee; + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - if (calleePath.isMemberExpression()) { - var temp = scope.maybeGenerateMemoised(callee.object); - if (temp) { - callee.object = t.assignmentExpression("=", temp, callee.object); - contextLiteral = temp; - } else { - contextLiteral = callee.object; - } - t.appendToMemberExpression(callee, t.identifier("apply")); - } else { - node.callee = t.memberExpression(node.callee, t.identifier("apply")); - } + return cache; +} - if (t.isSuper(contextLiteral)) { - contextLiteral = t.thisExpression(); - } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - node.arguments.unshift(contextLiteral); - }, - NewExpression: function NewExpression(path, state) { - var node = path.node, - scope = path.scope; + var cache = _getRequireWildcardCache(); - var args = node.arguments; - if (!hasSpread(args)) return; + if (cache && cache.has(obj)) { + return cache.get(obj); + } - var nodes = build(args, scope, state); + var newObj = {}; - var context = t.arrayExpression([t.nullLiteral()]); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - args = t.callExpression(t.memberExpression(context, t.identifier("concat")), nodes); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - path.replaceWith(t.newExpression(t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Function"), t.identifier("prototype")), t.identifier("bind")), t.identifier("apply")), [node.callee, args]), [])); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } } - }; -}; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + newObj.default = obj; -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],88:[function(require,module,exports){ -"use strict"; + if (cache) { + cache.set(obj, newObj); + } -exports.__esModule = true; + return newObj; +} -exports.default = function () { - return { - visitor: { - RegExpLiteral: function RegExpLiteral(path) { - var node = path.node; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - if (!regex.is(node, "y")) return; +var awaitVisitor = { + Function: function Function(path) { + path.skip(); + }, + AwaitExpression: function AwaitExpression(path, _ref) { + var wrapAwait = _ref.wrapAwait; + var argument = path.get("argument"); - path.replaceWith(t.newExpression(t.identifier("RegExp"), [t.stringLiteral(node.pattern), t.stringLiteral(node.flags)])); - } + if (path.parentPath.isYieldExpression()) { + path.replaceWith(argument.node); + return; } - }; + + path.replaceWith(t.yieldExpression(wrapAwait ? t.callExpression(t.cloneNode(wrapAwait), [argument.node]) : argument.node)); + } }; -var _babelHelperRegex = require("babel-helper-regex"); +function _default(path, helpers) { + path.traverse(awaitVisitor, { + wrapAwait: helpers.wrapAwait + }); + var isIIFE = checkIsIIFE(path); + path.node.async = false; + path.node.generator = true; + (0, _helperWrapFunction.default)(path, t.cloneNode(helpers.wrapAsync)); + var isProperty = path.isObjectMethod() || path.isClassMethod() || path.parentPath.isObjectProperty() || path.parentPath.isClassProperty(); + + if (!isProperty && !isIIFE && path.isExpression()) { + (0, _helperAnnotateAsPure.default)(path); + } -var regex = _interopRequireWildcard(_babelHelperRegex); + function checkIsIIFE(path) { + if (path.parentPath.isCallExpression({ + callee: path.node + })) { + return true; + } -var _babelTypes = require("babel-types"); + var parentPath = path.parentPath; -var t = _interopRequireWildcard(_babelTypes); + if (parentPath.isMemberExpression() && t.isIdentifier(parentPath.node.property, { + name: "bind" + })) { + var bindCall = parentPath.parentPath; + return bindCall.isCallExpression() && bindCall.node.arguments.length === 1 && t.isThisExpression(bindCall.node.arguments[0]) && bindCall.parentPath.isCallExpression({ + callee: bindCall.node + }); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return false; + } +} -module.exports = exports["default"]; -},{"babel-helper-regex":57,"babel-types":151}],89:[function(require,module,exports){ +},{"@babel/helper-annotate-as-pure":57,"@babel/helper-wrap-function":85,"@babel/types":242}],82:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -var _getIterator3 = _interopRequireDefault(_getIterator2); +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -exports.default = function (_ref) { - var t = _ref.types; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.environmentVisitor = void 0; - function isString(node) { - return t.isLiteral(node) && typeof node.value === "string"; - } +var _traverse = _interopRequireDefault(require("@babel/traverse")); - function buildBinaryExpression(left, right) { - return t.binaryExpression("+", left, right); - } +var _helperMemberExpressionToFunctions = _interopRequireDefault(require("@babel/helper-member-expression-to-functions")); - return { - visitor: { - TaggedTemplateExpression: function TaggedTemplateExpression(path, state) { - var node = path.node; +var _helperOptimiseCallExpression = _interopRequireDefault(require("@babel/helper-optimise-call-expression")); - var quasi = node.quasi; - var args = []; +var t = _interopRequireWildcard(require("@babel/types")); - var strings = []; - var raw = []; +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - for (var _iterator = quasi.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } + return cache; +} - var elem = _ref2; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - strings.push(t.stringLiteral(elem.value.cooked)); - raw.push(t.stringLiteral(elem.value.raw)); - } + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } - strings = t.arrayExpression(strings); - raw = t.arrayExpression(raw); + var newObj = {}; - var templateName = "taggedTemplateLiteral"; - if (state.opts.loose) templateName += "Loose"; + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - var templateObject = state.file.addTemplateObject(templateName, strings, raw); - args.push(templateObject); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - args = args.concat(quasi.expressions); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } - path.replaceWith(t.callExpression(node.tag, args)); - }, - TemplateLiteral: function TemplateLiteral(path, state) { - var nodes = []; + newObj.default = obj; - var expressions = path.get("expressions"); + if (cache) { + cache.set(obj, newObj); + } - for (var _iterator2 = path.node.quasis, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; + return newObj; +} - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - var elem = _ref3; +function getPrototypeOfExpression(objectRef, isStatic, file, isPrivateMethod) { + objectRef = t.cloneNode(objectRef); + var targetRef = isStatic || isPrivateMethod ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); + return t.callExpression(file.addHelper("getPrototypeOf"), [targetRef]); +} - nodes.push(t.stringLiteral(elem.value.cooked)); +function skipAllButComputedKey(path) { + if (!path.node.computed) { + path.skip(); + return; + } - var expr = expressions.shift(); - if (expr) { - if (state.opts.spec && !expr.isBaseType("string") && !expr.isBaseType("number")) { - nodes.push(t.callExpression(t.identifier("String"), [expr.node])); - } else { - nodes.push(expr.node); - } - } - } + var keys = t.VISITOR_KEYS[path.type]; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - nodes = nodes.filter(function (n) { - return !t.isLiteral(n, { value: "" }); - }); + try { + for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var key = _step.value; + if (key !== "key") path.skipKey(key); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } +} - if (!isString(nodes[0]) && !isString(nodes[1])) { - nodes.unshift(t.stringLiteral("")); - } +var environmentVisitor = { + TypeAnnotation: function TypeAnnotation(path) { + path.skip(); + }, + Function: function Function(path) { + if (path.isMethod()) return; + if (path.isArrowFunctionExpression()) return; + path.skip(); + }, + "Method|ClassProperty|ClassPrivateProperty": function MethodClassPropertyClassPrivateProperty(path) { + skipAllButComputedKey(path); + } +}; +exports.environmentVisitor = environmentVisitor; - if (nodes.length > 1) { - var root = buildBinaryExpression(nodes.shift(), nodes.shift()); +var visitor = _traverse.default.visitors.merge([environmentVisitor, { + Super: function Super(path, state) { + var node = path.node, + parentPath = path.parentPath; + if (!parentPath.isMemberExpression({ + object: node + })) return; + state.handle(parentPath); + } +}]); - for (var _iterator3 = nodes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref4; +var specHandlers = { + memoise: function memoise(superMember, count) { + var scope = superMember.scope, + node = superMember.node; + var computed = node.computed, + property = node.property; - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } + if (!computed) { + return; + } - var node = _ref4; + var memo = scope.maybeGenerateMemoised(property); - root = buildBinaryExpression(root, node); - } + if (!memo) { + return; + } - path.replaceWith(root); - } else { - path.replaceWith(nodes[0]); - } - } + this.memoiser.set(property, memo, count); + }, + prop: function prop(superMember) { + var _superMember$node = superMember.node, + computed = _superMember$node.computed, + property = _superMember$node.property; + + if (this.memoiser.has(property)) { + return t.cloneNode(this.memoiser.get(property)); } - }; + + if (computed) { + return t.cloneNode(property); + } + + return t.stringLiteral(property.name); + }, + get: function get(superMember) { + return t.callExpression(this.file.addHelper("get"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic, this.file, this.isPrivateMethod), this.prop(superMember), t.thisExpression()]); + }, + set: function set(superMember, value) { + return t.callExpression(this.file.addHelper("set"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic, this.file, this.isPrivateMethod), this.prop(superMember), value, t.thisExpression(), t.booleanLiteral(superMember.isInStrictMode())]); + }, + destructureSet: function destructureSet(superMember) { + throw superMember.buildCodeFrameError("Destructuring to a super field is not supported yet."); + }, + call: function call(superMember, args) { + return (0, _helperOptimiseCallExpression.default)(this.get(superMember), t.thisExpression(), args); + } }; +var looseHandlers = Object.assign({}, specHandlers, { + prop: function prop(superMember) { + var property = superMember.node.property; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this.memoiser.has(property)) { + return t.cloneNode(this.memoiser.get(property)); + } -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95}],90:[function(require,module,exports){ -"use strict"; + return t.cloneNode(property); + }, + get: function get(superMember) { + var isStatic = this.isStatic, + superRef = this.superRef; + var computed = superMember.node.computed; + var prop = this.prop(superMember); + var object; + + if (isStatic) { + object = superRef ? t.cloneNode(superRef) : t.memberExpression(t.identifier("Function"), t.identifier("prototype")); + } else { + object = superRef ? t.memberExpression(t.cloneNode(superRef), t.identifier("prototype")) : t.memberExpression(t.identifier("Object"), t.identifier("prototype")); + } -exports.__esModule = true; + return t.memberExpression(object, prop, computed); + }, + set: function set(superMember, value) { + var computed = superMember.node.computed; + var prop = this.prop(superMember); + return t.assignmentExpression("=", t.memberExpression(t.thisExpression(), prop, computed), value); + }, + destructureSet: function destructureSet(superMember) { + var computed = superMember.node.computed; + var prop = this.prop(superMember); + return t.memberExpression(t.thisExpression(), prop, computed); + } +}); -var _symbol = require("babel-runtime/core-js/symbol"); +var ReplaceSupers = +/*#__PURE__*/ +function () { + function ReplaceSupers(opts) { + _classCallCheck(this, ReplaceSupers); -var _symbol2 = _interopRequireDefault(_symbol); + var path = opts.methodPath; + this.methodPath = path; + this.isStatic = path.isObjectMethod() || path.node.static; + this.isPrivateMethod = path.isPrivate() && path.isMethod(); + this.file = opts.file; + this.superRef = opts.superRef; + this.isLoose = opts.isLoose; + this.opts = opts; + } -exports.default = function (_ref) { - var t = _ref.types; + _createClass(ReplaceSupers, [{ + key: "getObjectRef", + value: function getObjectRef() { + return t.cloneNode(this.opts.objectRef || this.opts.getObjectRef()); + } + }, { + key: "replace", + value: function replace() { + var handler = this.isLoose ? looseHandlers : specHandlers; + (0, _helperMemberExpressionToFunctions.default)(this.methodPath, visitor, Object.assign({ + file: this.file, + isStatic: this.isStatic, + isPrivateMethod: this.isPrivateMethod, + getObjectRef: this.getObjectRef.bind(this), + superRef: this.superRef + }, handler)); + } + }]); - var IGNORE = (0, _symbol2.default)(); + return ReplaceSupers; +}(); - return { - visitor: { - Scope: function Scope(_ref2) { - var scope = _ref2.scope; +exports.default = ReplaceSupers; - if (!scope.getBinding("Symbol")) { - return; - } +},{"@babel/helper-member-expression-to-functions":69,"@babel/helper-optimise-call-expression":78,"@babel/traverse":176,"@babel/types":242}],83:[function(require,module,exports){ +"use strict"; - scope.rename("Symbol"); - }, - UnaryExpression: function UnaryExpression(path) { - var node = path.node, - parent = path.parent; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = simplifyAccess; - if (node[IGNORE]) return; - if (path.find(function (path) { - return path.node && !!path.node._generated; - })) return; +var t = _interopRequireWildcard(require("@babel/types")); - if (path.parentPath.isBinaryExpression() && t.EQUALITY_BINARY_OPERATORS.indexOf(parent.operator) >= 0) { - var opposite = path.getOpposite(); - if (opposite.isLiteral() && opposite.node.value !== "symbol" && opposite.node.value !== "object") { - return; - } - } +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); - if (node.operator === "typeof") { - var call = t.callExpression(this.addHelper("typeof"), [node.argument]); - if (path.get("argument").isIdentifier()) { - var undefLiteral = t.stringLiteral("undefined"); - var unary = t.unaryExpression("typeof", node.argument); - unary[IGNORE] = true; - path.replaceWith(t.conditionalExpression(t.binaryExpression("===", unary, undefLiteral), undefLiteral, call)); - } else { - path.replaceWith(call); - } - } - } - } + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; }; -}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return cache; +} -module.exports = exports["default"]; -},{"babel-runtime/core-js/symbol":104}],91:[function(require,module,exports){ -"use strict"; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -exports.__esModule = true; + var cache = _getRequireWildcardCache(); -exports.default = function () { - return { - visitor: { - RegExpLiteral: function RegExpLiteral(_ref) { - var node = _ref.node; + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - if (!regex.is(node, "u")) return; - node.pattern = (0, _regexpuCore2.default)(node.pattern, node.flags); - regex.pullFlag(node, "u"); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } } - }; -}; + } -var _regexpuCore = require("regexpu-core"); + newObj.default = obj; -var _regexpuCore2 = _interopRequireDefault(_regexpuCore); + if (cache) { + cache.set(obj, newObj); + } -var _babelHelperRegex = require("babel-helper-regex"); + return newObj; +} -var regex = _interopRequireWildcard(_babelHelperRegex); +function simplifyAccess(path, bindingNames) { + path.traverse(simpleAssignmentVisitor, { + scope: path.scope, + bindingNames: bindingNames, + seen: new WeakSet() + }); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var simpleAssignmentVisitor = { + UpdateExpression: { + exit: function exit(path) { + var scope = this.scope, + bindingNames = this.bindingNames; + var arg = path.get("argument"); + if (!arg.isIdentifier()) return; + var localName = arg.node.name; + if (!bindingNames.has(localName)) return; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { + return; + } -module.exports = exports["default"]; -},{"babel-helper-regex":57,"regexpu-core":537}],92:[function(require,module,exports){ -"use strict"; + if (path.parentPath.isExpressionStatement() && !path.isCompletionRecord()) { + var operator = path.node.operator == "++" ? "+=" : "-="; + path.replaceWith(t.assignmentExpression(operator, arg.node, t.numericLiteral(1))); + } else if (path.node.prefix) { + path.replaceWith(t.assignmentExpression("=", t.identifier(localName), t.binaryExpression(path.node.operator[0], t.unaryExpression("+", arg.node), t.numericLiteral(1)))); + } else { + var old = path.scope.generateUidIdentifierBasedOnNode(arg.node, "old"); + var varName = old.name; + path.scope.push({ + id: old + }); + var binary = t.binaryExpression(path.node.operator[0], t.identifier(varName), t.numericLiteral(1)); + path.replaceWith(t.sequenceExpression([t.assignmentExpression("=", t.identifier(varName), t.unaryExpression("+", arg.node)), t.assignmentExpression("=", t.cloneNode(arg.node), binary), t.identifier(varName)])); + } + } + }, + AssignmentExpression: { + exit: function exit(path) { + var scope = this.scope, + seen = this.seen, + bindingNames = this.bindingNames; + if (path.node.operator === "=") return; + if (seen.has(path.node)) return; + seen.add(path.node); + var left = path.get("left"); + if (!left.isIdentifier()) return; + var localName = left.node.name; + if (!bindingNames.has(localName)) return; + + if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { + return; + } + + path.node.right = t.binaryExpression(path.node.operator.slice(0, -1), t.cloneNode(path.node.left), path.node.right); + path.node.operator = "="; + } + } +}; -module.exports = require("regenerator-transform"); -},{"regenerator-transform":529}],93:[function(require,module,exports){ +},{"@babel/types":242}],84:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = splitExportDeclaration; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var t = _interopRequireWildcard(require("@babel/types")); -var _getIterator3 = _interopRequireDefault(_getIterator2); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -exports.default = function () { - return { - visitor: { - Program: function Program(path, state) { - if (state.opts.strict === false || state.opts.strictMode === false) return; + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; - var node = path.node; + return cache; +} +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - for (var _iterator = node.directives, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + var cache = _getRequireWildcardCache(); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (cache && cache.has(obj)) { + return cache.get(obj); + } - var directive = _ref; + var newObj = {}; - if (directive.value.value === "use strict") return; - } + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - path.unshiftContainer("directives", t.directive(t.directiveLiteral("use strict"))); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } } - }; -}; - -var _babelTypes = require("babel-types"); + } -var t = _interopRequireWildcard(_babelTypes); + newObj.default = obj; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (cache) { + cache.set(obj, newObj); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return newObj; +} -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],94:[function(require,module,exports){ -"use strict"; +function splitExportDeclaration(exportDeclaration) { + if (!exportDeclaration.isExportDeclaration()) { + throw new Error("Only export declarations can be splitted."); + } -exports.__esModule = true; + var isDefault = exportDeclaration.isExportDefaultDeclaration(); + var declaration = exportDeclaration.get("declaration"); + var isClassDeclaration = declaration.isClassDeclaration(); -var _babelPluginTransformEs2015TemplateLiterals = require("babel-plugin-transform-es2015-template-literals"); + if (isDefault) { + var standaloneDeclaration = declaration.isFunctionDeclaration() || isClassDeclaration; + var scope = declaration.isScope() ? declaration.scope.parent : declaration.scope; + var id = declaration.node.id; + var needBindingRegistration = false; -var _babelPluginTransformEs2015TemplateLiterals2 = _interopRequireDefault(_babelPluginTransformEs2015TemplateLiterals); + if (!id) { + needBindingRegistration = true; + id = scope.generateUidIdentifier("default"); -var _babelPluginTransformEs2015Literals = require("babel-plugin-transform-es2015-literals"); + if (standaloneDeclaration || declaration.isFunctionExpression() || declaration.isClassExpression()) { + declaration.node.id = t.cloneNode(id); + } + } -var _babelPluginTransformEs2015Literals2 = _interopRequireDefault(_babelPluginTransformEs2015Literals); + var updatedDeclaration = standaloneDeclaration ? declaration : t.variableDeclaration("var", [t.variableDeclarator(t.cloneNode(id), declaration.node)]); + var updatedExportDeclaration = t.exportNamedDeclaration(null, [t.exportSpecifier(t.cloneNode(id), t.identifier("default"))]); + exportDeclaration.insertAfter(updatedExportDeclaration); + exportDeclaration.replaceWith(updatedDeclaration); -var _babelPluginTransformEs2015FunctionName = require("babel-plugin-transform-es2015-function-name"); + if (needBindingRegistration) { + scope.registerDeclaration(exportDeclaration); + } -var _babelPluginTransformEs2015FunctionName2 = _interopRequireDefault(_babelPluginTransformEs2015FunctionName); + return exportDeclaration; + } -var _babelPluginTransformEs2015ArrowFunctions = require("babel-plugin-transform-es2015-arrow-functions"); + if (exportDeclaration.get("specifiers").length > 0) { + throw new Error("It doesn't make sense to split exported specifiers."); + } -var _babelPluginTransformEs2015ArrowFunctions2 = _interopRequireDefault(_babelPluginTransformEs2015ArrowFunctions); + var bindingIdentifiers = declaration.getOuterBindingIdentifiers(); + var specifiers = Object.keys(bindingIdentifiers).map(function (name) { + return t.exportSpecifier(t.identifier(name), t.identifier(name)); + }); + var aliasDeclar = t.exportNamedDeclaration(null, specifiers); + exportDeclaration.insertAfter(aliasDeclar); + exportDeclaration.replaceWith(declaration.node); + return exportDeclaration; +} -var _babelPluginTransformEs2015BlockScopedFunctions = require("babel-plugin-transform-es2015-block-scoped-functions"); +},{"@babel/types":242}],85:[function(require,module,exports){ +"use strict"; -var _babelPluginTransformEs2015BlockScopedFunctions2 = _interopRequireDefault(_babelPluginTransformEs2015BlockScopedFunctions); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = wrapFunction; -var _babelPluginTransformEs2015Classes = require("babel-plugin-transform-es2015-classes"); +var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name")); -var _babelPluginTransformEs2015Classes2 = _interopRequireDefault(_babelPluginTransformEs2015Classes); +var _template = _interopRequireDefault(require("@babel/template")); -var _babelPluginTransformEs2015ObjectSuper = require("babel-plugin-transform-es2015-object-super"); +var t = _interopRequireWildcard(require("@babel/types")); -var _babelPluginTransformEs2015ObjectSuper2 = _interopRequireDefault(_babelPluginTransformEs2015ObjectSuper); +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); -var _babelPluginTransformEs2015ShorthandProperties = require("babel-plugin-transform-es2015-shorthand-properties"); + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; -var _babelPluginTransformEs2015ShorthandProperties2 = _interopRequireDefault(_babelPluginTransformEs2015ShorthandProperties); + return cache; +} -var _babelPluginTransformEs2015DuplicateKeys = require("babel-plugin-transform-es2015-duplicate-keys"); +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } -var _babelPluginTransformEs2015DuplicateKeys2 = _interopRequireDefault(_babelPluginTransformEs2015DuplicateKeys); + var cache = _getRequireWildcardCache(); -var _babelPluginTransformEs2015ComputedProperties = require("babel-plugin-transform-es2015-computed-properties"); + if (cache && cache.has(obj)) { + return cache.get(obj); + } -var _babelPluginTransformEs2015ComputedProperties2 = _interopRequireDefault(_babelPluginTransformEs2015ComputedProperties); + var newObj = {}; -var _babelPluginTransformEs2015ForOf = require("babel-plugin-transform-es2015-for-of"); + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; -var _babelPluginTransformEs2015ForOf2 = _interopRequireDefault(_babelPluginTransformEs2015ForOf); + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; -var _babelPluginTransformEs2015StickyRegex = require("babel-plugin-transform-es2015-sticky-regex"); + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } -var _babelPluginTransformEs2015StickyRegex2 = _interopRequireDefault(_babelPluginTransformEs2015StickyRegex); + newObj.default = obj; -var _babelPluginTransformEs2015UnicodeRegex = require("babel-plugin-transform-es2015-unicode-regex"); + if (cache) { + cache.set(obj, newObj); + } -var _babelPluginTransformEs2015UnicodeRegex2 = _interopRequireDefault(_babelPluginTransformEs2015UnicodeRegex); + return newObj; +} -var _babelPluginCheckEs2015Constants = require("babel-plugin-check-es2015-constants"); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} -var _babelPluginCheckEs2015Constants2 = _interopRequireDefault(_babelPluginCheckEs2015Constants); +var buildAnonymousExpressionWrapper = _template.default.expression("\n (function () {\n var REF = FUNCTION;\n return function NAME(PARAMS) {\n return REF.apply(this, arguments);\n };\n })()\n"); -var _babelPluginTransformEs2015Spread = require("babel-plugin-transform-es2015-spread"); +var buildNamedExpressionWrapper = _template.default.expression("\n (function () {\n var REF = FUNCTION;\n function NAME(PARAMS) {\n return REF.apply(this, arguments);\n }\n return NAME;\n })()\n"); -var _babelPluginTransformEs2015Spread2 = _interopRequireDefault(_babelPluginTransformEs2015Spread); +var buildDeclarationWrapper = (0, _template.default)("\n function NAME(PARAMS) { return REF.apply(this, arguments); }\n function REF() {\n REF = FUNCTION;\n return REF.apply(this, arguments);\n }\n"); -var _babelPluginTransformEs2015Parameters = require("babel-plugin-transform-es2015-parameters"); +function classOrObjectMethod(path, callId) { + var node = path.node; + var body = node.body; + var container = t.functionExpression(null, [], t.blockStatement(body.body), true); + body.body = [t.returnStatement(t.callExpression(t.callExpression(callId, [container]), []))]; + node.async = false; + node.generator = false; + path.get("body.body.0.argument.callee.arguments.0").unwrapFunctionEnvironment(); +} -var _babelPluginTransformEs2015Parameters2 = _interopRequireDefault(_babelPluginTransformEs2015Parameters); +function plainFunction(path, callId) { + var node = path.node; + var isDeclaration = path.isFunctionDeclaration(); + var functionId = node.id; + var wrapper = isDeclaration ? buildDeclarationWrapper : functionId ? buildNamedExpressionWrapper : buildAnonymousExpressionWrapper; -var _babelPluginTransformEs2015Destructuring = require("babel-plugin-transform-es2015-destructuring"); + if (path.isArrowFunctionExpression()) { + path.arrowFunctionToExpression(); + } -var _babelPluginTransformEs2015Destructuring2 = _interopRequireDefault(_babelPluginTransformEs2015Destructuring); + node.id = null; -var _babelPluginTransformEs2015BlockScoping = require("babel-plugin-transform-es2015-block-scoping"); + if (isDeclaration) { + node.type = "FunctionExpression"; + } -var _babelPluginTransformEs2015BlockScoping2 = _interopRequireDefault(_babelPluginTransformEs2015BlockScoping); + var built = t.callExpression(callId, [node]); + var container = wrapper({ + NAME: functionId || null, + REF: path.scope.generateUidIdentifier(functionId ? functionId.name : "ref"), + FUNCTION: built, + PARAMS: node.params.reduce(function (acc, param) { + acc.done = acc.done || t.isAssignmentPattern(param) || t.isRestElement(param); -var _babelPluginTransformEs2015TypeofSymbol = require("babel-plugin-transform-es2015-typeof-symbol"); + if (!acc.done) { + acc.params.push(path.scope.generateUidIdentifier("x")); + } -var _babelPluginTransformEs2015TypeofSymbol2 = _interopRequireDefault(_babelPluginTransformEs2015TypeofSymbol); + return acc; + }, { + params: [], + done: false + }).params + }); -var _babelPluginTransformEs2015ModulesCommonjs = require("babel-plugin-transform-es2015-modules-commonjs"); + if (isDeclaration) { + path.replaceWith(container[0]); + path.insertAfter(container[1]); + } else { + var retFunction = container.callee.body.body[1].argument; -var _babelPluginTransformEs2015ModulesCommonjs2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesCommonjs); + if (!functionId) { + (0, _helperFunctionName.default)({ + node: retFunction, + parent: path.parent, + scope: path.scope + }); + } -var _babelPluginTransformEs2015ModulesSystemjs = require("babel-plugin-transform-es2015-modules-systemjs"); + if (!retFunction || retFunction.id || node.params.length) { + path.replaceWith(container); + } else { + path.replaceWith(built); + } + } +} -var _babelPluginTransformEs2015ModulesSystemjs2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesSystemjs); +function wrapFunction(path, callId) { + if (path.isClassMethod() || path.isObjectMethod()) { + classOrObjectMethod(path, callId); + } else { + plainFunction(path, callId); + } +} -var _babelPluginTransformEs2015ModulesAmd = require("babel-plugin-transform-es2015-modules-amd"); +},{"@babel/helper-function-name":66,"@babel/template":167,"@babel/types":242}],86:[function(require,module,exports){ +"use strict"; -var _babelPluginTransformEs2015ModulesAmd2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesAmd); +function _templateObject73() { + var data = _taggedTemplateLiteral(["\n import wrapNativeSuper from \"wrapNativeSuper\";\n import getPrototypeOf from \"getPrototypeOf\";\n import possibleConstructorReturn from \"possibleConstructorReturn\";\n import inherits from \"inherits\";\n\n export default function _wrapRegExp(re, groups) {\n _wrapRegExp = function(re, groups) {\n return new BabelRegExp(re, undefined, groups);\n };\n\n var _RegExp = wrapNativeSuper(RegExp);\n var _super = RegExp.prototype;\n var _groups = new WeakMap();\n\n function BabelRegExp(re, flags, groups) {\n var _this = _RegExp.call(this, re, flags);\n // if the regex is recreated with 'g' flag\n _groups.set(_this, groups || _groups.get(re));\n return _this;\n }\n inherits(BabelRegExp, _RegExp);\n\n BabelRegExp.prototype.exec = function(str) {\n var result = _super.exec.call(this, str);\n if (result) result.groups = buildGroups(result, this);\n return result;\n };\n BabelRegExp.prototype[Symbol.replace] = function(str, substitution) {\n if (typeof substitution === \"string\") {\n var groups = _groups.get(this);\n return _super[Symbol.replace].call(\n this,\n str,\n substitution.replace(/\\$<([^>]+)>/g, function(_, name) {\n return \"$\" + groups[name];\n })\n );\n } else if (typeof substitution === \"function\") {\n var _this = this;\n return _super[Symbol.replace].call(\n this,\n str,\n function() {\n var args = [];\n args.push.apply(args, arguments);\n if (typeof args[args.length - 1] !== \"object\") {\n // Modern engines already pass result.groups as the last arg.\n args.push(buildGroups(args, _this));\n }\n return substitution.apply(this, args);\n }\n );\n } else {\n return _super[Symbol.replace].call(this, str, substitution);\n }\n }\n\n function buildGroups(result, re) {\n // NOTE: This function should return undefined if there are no groups,\n // but in that case Babel doesn't add the wrapper anyway.\n\n var g = _groups.get(re);\n return Object.keys(g).reduce(function(groups, name) {\n groups[name] = result[g[name]];\n return groups;\n }, Object.create(null));\n }\n\n return _wrapRegExp.apply(this, arguments);\n }\n"], ["\n import wrapNativeSuper from \"wrapNativeSuper\";\n import getPrototypeOf from \"getPrototypeOf\";\n import possibleConstructorReturn from \"possibleConstructorReturn\";\n import inherits from \"inherits\";\n\n export default function _wrapRegExp(re, groups) {\n _wrapRegExp = function(re, groups) {\n return new BabelRegExp(re, undefined, groups);\n };\n\n var _RegExp = wrapNativeSuper(RegExp);\n var _super = RegExp.prototype;\n var _groups = new WeakMap();\n\n function BabelRegExp(re, flags, groups) {\n var _this = _RegExp.call(this, re, flags);\n // if the regex is recreated with 'g' flag\n _groups.set(_this, groups || _groups.get(re));\n return _this;\n }\n inherits(BabelRegExp, _RegExp);\n\n BabelRegExp.prototype.exec = function(str) {\n var result = _super.exec.call(this, str);\n if (result) result.groups = buildGroups(result, this);\n return result;\n };\n BabelRegExp.prototype[Symbol.replace] = function(str, substitution) {\n if (typeof substitution === \"string\") {\n var groups = _groups.get(this);\n return _super[Symbol.replace].call(\n this,\n str,\n substitution.replace(/\\\\$<([^>]+)>/g, function(_, name) {\n return \"$\" + groups[name];\n })\n );\n } else if (typeof substitution === \"function\") {\n var _this = this;\n return _super[Symbol.replace].call(\n this,\n str,\n function() {\n var args = [];\n args.push.apply(args, arguments);\n if (typeof args[args.length - 1] !== \"object\") {\n // Modern engines already pass result.groups as the last arg.\n args.push(buildGroups(args, _this));\n }\n return substitution.apply(this, args);\n }\n );\n } else {\n return _super[Symbol.replace].call(this, str, substitution);\n }\n }\n\n function buildGroups(result, re) {\n // NOTE: This function should return undefined if there are no groups,\n // but in that case Babel doesn't add the wrapper anyway.\n\n var g = _groups.get(re);\n return Object.keys(g).reduce(function(groups, name) {\n groups[name] = result[g[name]];\n return groups;\n }, Object.create(null));\n }\n\n return _wrapRegExp.apply(this, arguments);\n }\n"]); -var _babelPluginTransformEs2015ModulesUmd = require("babel-plugin-transform-es2015-modules-umd"); + _templateObject73 = function _templateObject73() { + return data; + }; -var _babelPluginTransformEs2015ModulesUmd2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesUmd); + return data; +} -var _babelPluginTransformRegenerator = require("babel-plugin-transform-regenerator"); +function _templateObject72() { + var data = _taggedTemplateLiteral(["\n export default function _classPrivateMethodSet() {\n throw new TypeError(\"attempted to reassign private method\");\n }\n"]); -var _babelPluginTransformRegenerator2 = _interopRequireDefault(_babelPluginTransformRegenerator); + _templateObject72 = function _templateObject72() { + return data; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return data; +} -function preset(context) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +function _templateObject71() { + var data = _taggedTemplateLiteral(["\n export default function _classPrivateMethodGet(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return fn;\n }\n"]); - var moduleTypes = ["commonjs", "amd", "umd", "systemjs"]; - var loose = false; - var modules = "commonjs"; - var spec = false; + _templateObject71 = function _templateObject71() { + return data; + }; - if (opts !== undefined) { - if (opts.loose !== undefined) loose = opts.loose; - if (opts.modules !== undefined) modules = opts.modules; - if (opts.spec !== undefined) spec = opts.spec; - } + return data; +} - if (typeof loose !== "boolean") throw new Error("Preset es2015 'loose' option must be a boolean."); - if (typeof spec !== "boolean") throw new Error("Preset es2015 'spec' option must be a boolean."); - if (modules !== false && moduleTypes.indexOf(modules) === -1) { - throw new Error("Preset es2015 'modules' option must be 'false' to indicate no modules\n" + "or a module type which be be one of: 'commonjs' (default), 'amd', 'umd', 'systemjs'"); - } +function _templateObject70() { + var data = _taggedTemplateLiteral(["\n import toArray from \"toArray\";\n import toPropertyKey from \"toPropertyKey\";\n\n // These comments are stripped by @babel/template\n /*::\n type PropertyDescriptor =\n | {\n value: any,\n writable: boolean,\n configurable: boolean,\n enumerable: boolean,\n }\n | {\n get?: () => any,\n set?: (v: any) => void,\n configurable: boolean,\n enumerable: boolean,\n };\n\n type FieldDescriptor ={\n writable: boolean,\n configurable: boolean,\n enumerable: boolean,\n };\n\n type Placement = \"static\" | \"prototype\" | \"own\";\n type Key = string | symbol; // PrivateName is not supported yet.\n\n type ElementDescriptor =\n | {\n kind: \"method\",\n key: Key,\n placement: Placement,\n descriptor: PropertyDescriptor\n }\n | {\n kind: \"field\",\n key: Key,\n placement: Placement,\n descriptor: FieldDescriptor,\n initializer?: () => any,\n };\n\n // This is exposed to the user code\n type ElementObjectInput = ElementDescriptor & {\n [@@toStringTag]?: \"Descriptor\"\n };\n\n // This is exposed to the user code\n type ElementObjectOutput = ElementDescriptor & {\n [@@toStringTag]?: \"Descriptor\"\n extras?: ElementDescriptor[],\n finisher?: ClassFinisher,\n };\n\n // This is exposed to the user code\n type ClassObject = {\n [@@toStringTag]?: \"Descriptor\",\n kind: \"class\",\n elements: ElementDescriptor[],\n };\n\n type ElementDecorator = (descriptor: ElementObjectInput) => ?ElementObjectOutput;\n type ClassDecorator = (descriptor: ClassObject) => ?ClassObject;\n type ClassFinisher = (cl: Class) => Class;\n\n // Only used by Babel in the transform output, not part of the spec.\n type ElementDefinition =\n | {\n kind: \"method\",\n value: any,\n key: Key,\n static?: boolean,\n decorators?: ElementDecorator[],\n }\n | {\n kind: \"field\",\n value: () => any,\n key: Key,\n static?: boolean,\n decorators?: ElementDecorator[],\n };\n\n declare function ClassFactory(initialize: (instance: C) => void): {\n F: Class,\n d: ElementDefinition[]\n }\n\n */\n\n /*::\n // Various combinations with/without extras and with one or many finishers\n\n type ElementFinisherExtras = {\n element: ElementDescriptor,\n finisher?: ClassFinisher,\n extras?: ElementDescriptor[],\n };\n\n type ElementFinishersExtras = {\n element: ElementDescriptor,\n finishers: ClassFinisher[],\n extras: ElementDescriptor[],\n };\n\n type ElementsFinisher = {\n elements: ElementDescriptor[],\n finisher?: ClassFinisher,\n };\n\n type ElementsFinishers = {\n elements: ElementDescriptor[],\n finishers: ClassFinisher[],\n };\n\n */\n\n /*::\n\n type Placements = {\n static: Key[],\n prototype: Key[],\n own: Key[],\n };\n\n */\n\n // ClassDefinitionEvaluation (Steps 26-*)\n export default function _decorate(\n decorators /*: ClassDecorator[] */,\n factory /*: ClassFactory */,\n superClass /*: ?Class<*> */,\n mixins /*: ?Array */,\n ) /*: Class<*> */ {\n var api = _getDecoratorsApi();\n if (mixins) {\n for (var i = 0; i < mixins.length; i++) {\n api = mixins[i](api);\n }\n }\n\n var r = factory(function initialize(O) {\n api.initializeInstanceElements(O, decorated.elements);\n }, superClass);\n var decorated = api.decorateClass(\n _coalesceClassElements(r.d.map(_createElementDescriptor)),\n decorators,\n );\n\n api.initializeClassElements(r.F, decorated.elements);\n\n return api.runClassFinishers(r.F, decorated.finishers);\n }\n\n function _getDecoratorsApi() {\n _getDecoratorsApi = function() {\n return api;\n };\n\n var api = {\n elementsDefinitionOrder: [[\"method\"], [\"field\"]],\n\n // InitializeInstanceElements\n initializeInstanceElements: function(\n /*::*/ O /*: C */,\n elements /*: ElementDescriptor[] */,\n ) {\n [\"method\", \"field\"].forEach(function(kind) {\n elements.forEach(function(element /*: ElementDescriptor */) {\n if (element.kind === kind && element.placement === \"own\") {\n this.defineClassElement(O, element);\n }\n }, this);\n }, this);\n },\n\n // InitializeClassElements\n initializeClassElements: function(\n /*::*/ F /*: Class */,\n elements /*: ElementDescriptor[] */,\n ) {\n var proto = F.prototype;\n\n [\"method\", \"field\"].forEach(function(kind) {\n elements.forEach(function(element /*: ElementDescriptor */) {\n var placement = element.placement;\n if (\n element.kind === kind &&\n (placement === \"static\" || placement === \"prototype\")\n ) {\n var receiver = placement === \"static\" ? F : proto;\n this.defineClassElement(receiver, element);\n }\n }, this);\n }, this);\n },\n\n // DefineClassElement\n defineClassElement: function(\n /*::*/ receiver /*: C | Class */,\n element /*: ElementDescriptor */,\n ) {\n var descriptor /*: PropertyDescriptor */ = element.descriptor;\n if (element.kind === \"field\") {\n var initializer = element.initializer;\n descriptor = {\n enumerable: descriptor.enumerable,\n writable: descriptor.writable,\n configurable: descriptor.configurable,\n value: initializer === void 0 ? void 0 : initializer.call(receiver),\n };\n }\n Object.defineProperty(receiver, element.key, descriptor);\n },\n\n // DecorateClass\n decorateClass: function(\n elements /*: ElementDescriptor[] */,\n decorators /*: ClassDecorator[] */,\n ) /*: ElementsFinishers */ {\n var newElements /*: ElementDescriptor[] */ = [];\n var finishers /*: ClassFinisher[] */ = [];\n var placements /*: Placements */ = {\n static: [],\n prototype: [],\n own: [],\n };\n\n elements.forEach(function(element /*: ElementDescriptor */) {\n this.addElementPlacement(element, placements);\n }, this);\n\n elements.forEach(function(element /*: ElementDescriptor */) {\n if (!_hasDecorators(element)) return newElements.push(element);\n\n var elementFinishersExtras /*: ElementFinishersExtras */ = this.decorateElement(\n element,\n placements,\n );\n newElements.push(elementFinishersExtras.element);\n newElements.push.apply(newElements, elementFinishersExtras.extras);\n finishers.push.apply(finishers, elementFinishersExtras.finishers);\n }, this);\n\n if (!decorators) {\n return { elements: newElements, finishers: finishers };\n }\n\n var result /*: ElementsFinishers */ = this.decorateConstructor(\n newElements,\n decorators,\n );\n finishers.push.apply(finishers, result.finishers);\n result.finishers = finishers;\n\n return result;\n },\n\n // AddElementPlacement\n addElementPlacement: function(\n element /*: ElementDescriptor */,\n placements /*: Placements */,\n silent /*: boolean */,\n ) {\n var keys = placements[element.placement];\n if (!silent && keys.indexOf(element.key) !== -1) {\n throw new TypeError(\"Duplicated element (\" + element.key + \")\");\n }\n keys.push(element.key);\n },\n\n // DecorateElement\n decorateElement: function(\n element /*: ElementDescriptor */,\n placements /*: Placements */,\n ) /*: ElementFinishersExtras */ {\n var extras /*: ElementDescriptor[] */ = [];\n var finishers /*: ClassFinisher[] */ = [];\n\n for (\n var decorators = element.decorators, i = decorators.length - 1;\n i >= 0;\n i--\n ) {\n // (inlined) RemoveElementPlacement\n var keys = placements[element.placement];\n keys.splice(keys.indexOf(element.key), 1);\n\n var elementObject /*: ElementObjectInput */ = this.fromElementDescriptor(\n element,\n );\n var elementFinisherExtras /*: ElementFinisherExtras */ = this.toElementFinisherExtras(\n (0, decorators[i])(elementObject) /*: ElementObjectOutput */ ||\n elementObject,\n );\n\n element = elementFinisherExtras.element;\n this.addElementPlacement(element, placements);\n\n if (elementFinisherExtras.finisher) {\n finishers.push(elementFinisherExtras.finisher);\n }\n\n var newExtras /*: ElementDescriptor[] | void */ =\n elementFinisherExtras.extras;\n if (newExtras) {\n for (var j = 0; j < newExtras.length; j++) {\n this.addElementPlacement(newExtras[j], placements);\n }\n extras.push.apply(extras, newExtras);\n }\n }\n\n return { element: element, finishers: finishers, extras: extras };\n },\n\n // DecorateConstructor\n decorateConstructor: function(\n elements /*: ElementDescriptor[] */,\n decorators /*: ClassDecorator[] */,\n ) /*: ElementsFinishers */ {\n var finishers /*: ClassFinisher[] */ = [];\n\n for (var i = decorators.length - 1; i >= 0; i--) {\n var obj /*: ClassObject */ = this.fromClassDescriptor(elements);\n var elementsAndFinisher /*: ElementsFinisher */ = this.toClassDescriptor(\n (0, decorators[i])(obj) /*: ClassObject */ || obj,\n );\n\n if (elementsAndFinisher.finisher !== undefined) {\n finishers.push(elementsAndFinisher.finisher);\n }\n\n if (elementsAndFinisher.elements !== undefined) {\n elements = elementsAndFinisher.elements;\n\n for (var j = 0; j < elements.length - 1; j++) {\n for (var k = j + 1; k < elements.length; k++) {\n if (\n elements[j].key === elements[k].key &&\n elements[j].placement === elements[k].placement\n ) {\n throw new TypeError(\n \"Duplicated element (\" + elements[j].key + \")\",\n );\n }\n }\n }\n }\n }\n\n return { elements: elements, finishers: finishers };\n },\n\n // FromElementDescriptor\n fromElementDescriptor: function(\n element /*: ElementDescriptor */,\n ) /*: ElementObject */ {\n var obj /*: ElementObject */ = {\n kind: element.kind,\n key: element.key,\n placement: element.placement,\n descriptor: element.descriptor,\n };\n\n var desc = {\n value: \"Descriptor\",\n configurable: true,\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n\n if (element.kind === \"field\") obj.initializer = element.initializer;\n\n return obj;\n },\n\n // ToElementDescriptors\n toElementDescriptors: function(\n elementObjects /*: ElementObject[] */,\n ) /*: ElementDescriptor[] */ {\n if (elementObjects === undefined) return;\n return toArray(elementObjects).map(function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n this.disallowProperty(elementObject, \"finisher\", \"An element descriptor\");\n this.disallowProperty(elementObject, \"extras\", \"An element descriptor\");\n return element;\n }, this);\n },\n\n // ToElementDescriptor\n toElementDescriptor: function(\n elementObject /*: ElementObject */,\n ) /*: ElementDescriptor */ {\n var kind = String(elementObject.kind);\n if (kind !== \"method\" && kind !== \"field\") {\n throw new TypeError(\n 'An element descriptor\\'s .kind property must be either \"method\" or' +\n ' \"field\", but a decorator created an element descriptor with' +\n ' .kind \"' +\n kind +\n '\"',\n );\n }\n\n var key = toPropertyKey(elementObject.key);\n\n var placement = String(elementObject.placement);\n if (\n placement !== \"static\" &&\n placement !== \"prototype\" &&\n placement !== \"own\"\n ) {\n throw new TypeError(\n 'An element descriptor\\'s .placement property must be one of \"static\",' +\n ' \"prototype\" or \"own\", but a decorator created an element descriptor' +\n ' with .placement \"' +\n placement +\n '\"',\n );\n }\n\n var descriptor /*: PropertyDescriptor */ = elementObject.descriptor;\n\n this.disallowProperty(elementObject, \"elements\", \"An element descriptor\");\n\n var element /*: ElementDescriptor */ = {\n kind: kind,\n key: key,\n placement: placement,\n descriptor: Object.assign({}, descriptor),\n };\n\n if (kind !== \"field\") {\n this.disallowProperty(elementObject, \"initializer\", \"A method descriptor\");\n } else {\n this.disallowProperty(\n descriptor,\n \"get\",\n \"The property descriptor of a field descriptor\",\n );\n this.disallowProperty(\n descriptor,\n \"set\",\n \"The property descriptor of a field descriptor\",\n );\n this.disallowProperty(\n descriptor,\n \"value\",\n \"The property descriptor of a field descriptor\",\n );\n\n element.initializer = elementObject.initializer;\n }\n\n return element;\n },\n\n toElementFinisherExtras: function(\n elementObject /*: ElementObject */,\n ) /*: ElementFinisherExtras */ {\n var element /*: ElementDescriptor */ = this.toElementDescriptor(\n elementObject,\n );\n var finisher /*: ClassFinisher */ = _optionalCallableProperty(\n elementObject,\n \"finisher\",\n );\n var extras /*: ElementDescriptors[] */ = this.toElementDescriptors(\n elementObject.extras,\n );\n\n return { element: element, finisher: finisher, extras: extras };\n },\n\n // FromClassDescriptor\n fromClassDescriptor: function(\n elements /*: ElementDescriptor[] */,\n ) /*: ClassObject */ {\n var obj = {\n kind: \"class\",\n elements: elements.map(this.fromElementDescriptor, this),\n };\n\n var desc = { value: \"Descriptor\", configurable: true };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n\n return obj;\n },\n\n // ToClassDescriptor\n toClassDescriptor: function(\n obj /*: ClassObject */,\n ) /*: ElementsFinisher */ {\n var kind = String(obj.kind);\n if (kind !== \"class\") {\n throw new TypeError(\n 'A class descriptor\\'s .kind property must be \"class\", but a decorator' +\n ' created a class descriptor with .kind \"' +\n kind +\n '\"',\n );\n }\n\n this.disallowProperty(obj, \"key\", \"A class descriptor\");\n this.disallowProperty(obj, \"placement\", \"A class descriptor\");\n this.disallowProperty(obj, \"descriptor\", \"A class descriptor\");\n this.disallowProperty(obj, \"initializer\", \"A class descriptor\");\n this.disallowProperty(obj, \"extras\", \"A class descriptor\");\n\n var finisher = _optionalCallableProperty(obj, \"finisher\");\n var elements = this.toElementDescriptors(obj.elements);\n\n return { elements: elements, finisher: finisher };\n },\n\n // RunClassFinishers\n runClassFinishers: function(\n constructor /*: Class<*> */,\n finishers /*: ClassFinisher[] */,\n ) /*: Class<*> */ {\n for (var i = 0; i < finishers.length; i++) {\n var newConstructor /*: ?Class<*> */ = (0, finishers[i])(constructor);\n if (newConstructor !== undefined) {\n // NOTE: This should check if IsConstructor(newConstructor) is false.\n if (typeof newConstructor !== \"function\") {\n throw new TypeError(\"Finishers must return a constructor.\");\n }\n constructor = newConstructor;\n }\n }\n return constructor;\n },\n\n disallowProperty: function(obj, name, objectType) {\n if (obj[name] !== undefined) {\n throw new TypeError(objectType + \" can't have a .\" + name + \" property.\");\n }\n }\n };\n\n return api;\n }\n\n // ClassElementEvaluation\n function _createElementDescriptor(\n def /*: ElementDefinition */,\n ) /*: ElementDescriptor */ {\n var key = toPropertyKey(def.key);\n\n var descriptor /*: PropertyDescriptor */;\n if (def.kind === \"method\") {\n descriptor = {\n value: def.value,\n writable: true,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === \"get\") {\n descriptor = { get: def.value, configurable: true, enumerable: false };\n } else if (def.kind === \"set\") {\n descriptor = { set: def.value, configurable: true, enumerable: false };\n } else if (def.kind === \"field\") {\n descriptor = { configurable: true, writable: true, enumerable: true };\n }\n\n var element /*: ElementDescriptor */ = {\n kind: def.kind === \"field\" ? \"field\" : \"method\",\n key: key,\n placement: def.static\n ? \"static\"\n : def.kind === \"field\"\n ? \"own\"\n : \"prototype\",\n descriptor: descriptor,\n };\n if (def.decorators) element.decorators = def.decorators;\n if (def.kind === \"field\") element.initializer = def.value;\n\n return element;\n }\n\n // CoalesceGetterSetter\n function _coalesceGetterSetter(\n element /*: ElementDescriptor */,\n other /*: ElementDescriptor */,\n ) {\n if (element.descriptor.get !== undefined) {\n other.descriptor.get = element.descriptor.get;\n } else {\n other.descriptor.set = element.descriptor.set;\n }\n }\n\n // CoalesceClassElements\n function _coalesceClassElements(\n elements /*: ElementDescriptor[] */,\n ) /*: ElementDescriptor[] */ {\n var newElements /*: ElementDescriptor[] */ = [];\n\n var isSameElement = function(\n other /*: ElementDescriptor */,\n ) /*: boolean */ {\n return (\n other.kind === \"method\" &&\n other.key === element.key &&\n other.placement === element.placement\n );\n };\n\n for (var i = 0; i < elements.length; i++) {\n var element /*: ElementDescriptor */ = elements[i];\n var other /*: ElementDescriptor */;\n\n if (\n element.kind === \"method\" &&\n (other = newElements.find(isSameElement))\n ) {\n if (\n _isDataDescriptor(element.descriptor) ||\n _isDataDescriptor(other.descriptor)\n ) {\n if (_hasDecorators(element) || _hasDecorators(other)) {\n throw new ReferenceError(\n \"Duplicated methods (\" + element.key + \") can't be decorated.\",\n );\n }\n other.descriptor = element.descriptor;\n } else {\n if (_hasDecorators(element)) {\n if (_hasDecorators(other)) {\n throw new ReferenceError(\n \"Decorators can't be placed on different accessors with for \" +\n \"the same property (\" +\n element.key +\n \").\",\n );\n }\n other.decorators = element.decorators;\n }\n _coalesceGetterSetter(element, other);\n }\n } else {\n newElements.push(element);\n }\n }\n\n return newElements;\n }\n\n function _hasDecorators(element /*: ElementDescriptor */) /*: boolean */ {\n return element.decorators && element.decorators.length;\n }\n\n function _isDataDescriptor(desc /*: PropertyDescriptor */) /*: boolean */ {\n return (\n desc !== undefined &&\n !(desc.value === undefined && desc.writable === undefined)\n );\n }\n\n function _optionalCallableProperty /*::*/(\n obj /*: T */,\n name /*: $Keys */,\n ) /*: ?Function */ {\n var value = obj[name];\n if (value !== undefined && typeof value !== \"function\") {\n throw new TypeError(\"Expected '\" + name + \"' to be a function\");\n }\n return value;\n }\n\n"], ["\n import toArray from \"toArray\";\n import toPropertyKey from \"toPropertyKey\";\n\n // These comments are stripped by @babel/template\n /*::\n type PropertyDescriptor =\n | {\n value: any,\n writable: boolean,\n configurable: boolean,\n enumerable: boolean,\n }\n | {\n get?: () => any,\n set?: (v: any) => void,\n configurable: boolean,\n enumerable: boolean,\n };\n\n type FieldDescriptor ={\n writable: boolean,\n configurable: boolean,\n enumerable: boolean,\n };\n\n type Placement = \"static\" | \"prototype\" | \"own\";\n type Key = string | symbol; // PrivateName is not supported yet.\n\n type ElementDescriptor =\n | {\n kind: \"method\",\n key: Key,\n placement: Placement,\n descriptor: PropertyDescriptor\n }\n | {\n kind: \"field\",\n key: Key,\n placement: Placement,\n descriptor: FieldDescriptor,\n initializer?: () => any,\n };\n\n // This is exposed to the user code\n type ElementObjectInput = ElementDescriptor & {\n [@@toStringTag]?: \"Descriptor\"\n };\n\n // This is exposed to the user code\n type ElementObjectOutput = ElementDescriptor & {\n [@@toStringTag]?: \"Descriptor\"\n extras?: ElementDescriptor[],\n finisher?: ClassFinisher,\n };\n\n // This is exposed to the user code\n type ClassObject = {\n [@@toStringTag]?: \"Descriptor\",\n kind: \"class\",\n elements: ElementDescriptor[],\n };\n\n type ElementDecorator = (descriptor: ElementObjectInput) => ?ElementObjectOutput;\n type ClassDecorator = (descriptor: ClassObject) => ?ClassObject;\n type ClassFinisher = (cl: Class) => Class;\n\n // Only used by Babel in the transform output, not part of the spec.\n type ElementDefinition =\n | {\n kind: \"method\",\n value: any,\n key: Key,\n static?: boolean,\n decorators?: ElementDecorator[],\n }\n | {\n kind: \"field\",\n value: () => any,\n key: Key,\n static?: boolean,\n decorators?: ElementDecorator[],\n };\n\n declare function ClassFactory(initialize: (instance: C) => void): {\n F: Class,\n d: ElementDefinition[]\n }\n\n */\n\n /*::\n // Various combinations with/without extras and with one or many finishers\n\n type ElementFinisherExtras = {\n element: ElementDescriptor,\n finisher?: ClassFinisher,\n extras?: ElementDescriptor[],\n };\n\n type ElementFinishersExtras = {\n element: ElementDescriptor,\n finishers: ClassFinisher[],\n extras: ElementDescriptor[],\n };\n\n type ElementsFinisher = {\n elements: ElementDescriptor[],\n finisher?: ClassFinisher,\n };\n\n type ElementsFinishers = {\n elements: ElementDescriptor[],\n finishers: ClassFinisher[],\n };\n\n */\n\n /*::\n\n type Placements = {\n static: Key[],\n prototype: Key[],\n own: Key[],\n };\n\n */\n\n // ClassDefinitionEvaluation (Steps 26-*)\n export default function _decorate(\n decorators /*: ClassDecorator[] */,\n factory /*: ClassFactory */,\n superClass /*: ?Class<*> */,\n mixins /*: ?Array */,\n ) /*: Class<*> */ {\n var api = _getDecoratorsApi();\n if (mixins) {\n for (var i = 0; i < mixins.length; i++) {\n api = mixins[i](api);\n }\n }\n\n var r = factory(function initialize(O) {\n api.initializeInstanceElements(O, decorated.elements);\n }, superClass);\n var decorated = api.decorateClass(\n _coalesceClassElements(r.d.map(_createElementDescriptor)),\n decorators,\n );\n\n api.initializeClassElements(r.F, decorated.elements);\n\n return api.runClassFinishers(r.F, decorated.finishers);\n }\n\n function _getDecoratorsApi() {\n _getDecoratorsApi = function() {\n return api;\n };\n\n var api = {\n elementsDefinitionOrder: [[\"method\"], [\"field\"]],\n\n // InitializeInstanceElements\n initializeInstanceElements: function(\n /*::*/ O /*: C */,\n elements /*: ElementDescriptor[] */,\n ) {\n [\"method\", \"field\"].forEach(function(kind) {\n elements.forEach(function(element /*: ElementDescriptor */) {\n if (element.kind === kind && element.placement === \"own\") {\n this.defineClassElement(O, element);\n }\n }, this);\n }, this);\n },\n\n // InitializeClassElements\n initializeClassElements: function(\n /*::*/ F /*: Class */,\n elements /*: ElementDescriptor[] */,\n ) {\n var proto = F.prototype;\n\n [\"method\", \"field\"].forEach(function(kind) {\n elements.forEach(function(element /*: ElementDescriptor */) {\n var placement = element.placement;\n if (\n element.kind === kind &&\n (placement === \"static\" || placement === \"prototype\")\n ) {\n var receiver = placement === \"static\" ? F : proto;\n this.defineClassElement(receiver, element);\n }\n }, this);\n }, this);\n },\n\n // DefineClassElement\n defineClassElement: function(\n /*::*/ receiver /*: C | Class */,\n element /*: ElementDescriptor */,\n ) {\n var descriptor /*: PropertyDescriptor */ = element.descriptor;\n if (element.kind === \"field\") {\n var initializer = element.initializer;\n descriptor = {\n enumerable: descriptor.enumerable,\n writable: descriptor.writable,\n configurable: descriptor.configurable,\n value: initializer === void 0 ? void 0 : initializer.call(receiver),\n };\n }\n Object.defineProperty(receiver, element.key, descriptor);\n },\n\n // DecorateClass\n decorateClass: function(\n elements /*: ElementDescriptor[] */,\n decorators /*: ClassDecorator[] */,\n ) /*: ElementsFinishers */ {\n var newElements /*: ElementDescriptor[] */ = [];\n var finishers /*: ClassFinisher[] */ = [];\n var placements /*: Placements */ = {\n static: [],\n prototype: [],\n own: [],\n };\n\n elements.forEach(function(element /*: ElementDescriptor */) {\n this.addElementPlacement(element, placements);\n }, this);\n\n elements.forEach(function(element /*: ElementDescriptor */) {\n if (!_hasDecorators(element)) return newElements.push(element);\n\n var elementFinishersExtras /*: ElementFinishersExtras */ = this.decorateElement(\n element,\n placements,\n );\n newElements.push(elementFinishersExtras.element);\n newElements.push.apply(newElements, elementFinishersExtras.extras);\n finishers.push.apply(finishers, elementFinishersExtras.finishers);\n }, this);\n\n if (!decorators) {\n return { elements: newElements, finishers: finishers };\n }\n\n var result /*: ElementsFinishers */ = this.decorateConstructor(\n newElements,\n decorators,\n );\n finishers.push.apply(finishers, result.finishers);\n result.finishers = finishers;\n\n return result;\n },\n\n // AddElementPlacement\n addElementPlacement: function(\n element /*: ElementDescriptor */,\n placements /*: Placements */,\n silent /*: boolean */,\n ) {\n var keys = placements[element.placement];\n if (!silent && keys.indexOf(element.key) !== -1) {\n throw new TypeError(\"Duplicated element (\" + element.key + \")\");\n }\n keys.push(element.key);\n },\n\n // DecorateElement\n decorateElement: function(\n element /*: ElementDescriptor */,\n placements /*: Placements */,\n ) /*: ElementFinishersExtras */ {\n var extras /*: ElementDescriptor[] */ = [];\n var finishers /*: ClassFinisher[] */ = [];\n\n for (\n var decorators = element.decorators, i = decorators.length - 1;\n i >= 0;\n i--\n ) {\n // (inlined) RemoveElementPlacement\n var keys = placements[element.placement];\n keys.splice(keys.indexOf(element.key), 1);\n\n var elementObject /*: ElementObjectInput */ = this.fromElementDescriptor(\n element,\n );\n var elementFinisherExtras /*: ElementFinisherExtras */ = this.toElementFinisherExtras(\n (0, decorators[i])(elementObject) /*: ElementObjectOutput */ ||\n elementObject,\n );\n\n element = elementFinisherExtras.element;\n this.addElementPlacement(element, placements);\n\n if (elementFinisherExtras.finisher) {\n finishers.push(elementFinisherExtras.finisher);\n }\n\n var newExtras /*: ElementDescriptor[] | void */ =\n elementFinisherExtras.extras;\n if (newExtras) {\n for (var j = 0; j < newExtras.length; j++) {\n this.addElementPlacement(newExtras[j], placements);\n }\n extras.push.apply(extras, newExtras);\n }\n }\n\n return { element: element, finishers: finishers, extras: extras };\n },\n\n // DecorateConstructor\n decorateConstructor: function(\n elements /*: ElementDescriptor[] */,\n decorators /*: ClassDecorator[] */,\n ) /*: ElementsFinishers */ {\n var finishers /*: ClassFinisher[] */ = [];\n\n for (var i = decorators.length - 1; i >= 0; i--) {\n var obj /*: ClassObject */ = this.fromClassDescriptor(elements);\n var elementsAndFinisher /*: ElementsFinisher */ = this.toClassDescriptor(\n (0, decorators[i])(obj) /*: ClassObject */ || obj,\n );\n\n if (elementsAndFinisher.finisher !== undefined) {\n finishers.push(elementsAndFinisher.finisher);\n }\n\n if (elementsAndFinisher.elements !== undefined) {\n elements = elementsAndFinisher.elements;\n\n for (var j = 0; j < elements.length - 1; j++) {\n for (var k = j + 1; k < elements.length; k++) {\n if (\n elements[j].key === elements[k].key &&\n elements[j].placement === elements[k].placement\n ) {\n throw new TypeError(\n \"Duplicated element (\" + elements[j].key + \")\",\n );\n }\n }\n }\n }\n }\n\n return { elements: elements, finishers: finishers };\n },\n\n // FromElementDescriptor\n fromElementDescriptor: function(\n element /*: ElementDescriptor */,\n ) /*: ElementObject */ {\n var obj /*: ElementObject */ = {\n kind: element.kind,\n key: element.key,\n placement: element.placement,\n descriptor: element.descriptor,\n };\n\n var desc = {\n value: \"Descriptor\",\n configurable: true,\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n\n if (element.kind === \"field\") obj.initializer = element.initializer;\n\n return obj;\n },\n\n // ToElementDescriptors\n toElementDescriptors: function(\n elementObjects /*: ElementObject[] */,\n ) /*: ElementDescriptor[] */ {\n if (elementObjects === undefined) return;\n return toArray(elementObjects).map(function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n this.disallowProperty(elementObject, \"finisher\", \"An element descriptor\");\n this.disallowProperty(elementObject, \"extras\", \"An element descriptor\");\n return element;\n }, this);\n },\n\n // ToElementDescriptor\n toElementDescriptor: function(\n elementObject /*: ElementObject */,\n ) /*: ElementDescriptor */ {\n var kind = String(elementObject.kind);\n if (kind !== \"method\" && kind !== \"field\") {\n throw new TypeError(\n 'An element descriptor\\\\'s .kind property must be either \"method\" or' +\n ' \"field\", but a decorator created an element descriptor with' +\n ' .kind \"' +\n kind +\n '\"',\n );\n }\n\n var key = toPropertyKey(elementObject.key);\n\n var placement = String(elementObject.placement);\n if (\n placement !== \"static\" &&\n placement !== \"prototype\" &&\n placement !== \"own\"\n ) {\n throw new TypeError(\n 'An element descriptor\\\\'s .placement property must be one of \"static\",' +\n ' \"prototype\" or \"own\", but a decorator created an element descriptor' +\n ' with .placement \"' +\n placement +\n '\"',\n );\n }\n\n var descriptor /*: PropertyDescriptor */ = elementObject.descriptor;\n\n this.disallowProperty(elementObject, \"elements\", \"An element descriptor\");\n\n var element /*: ElementDescriptor */ = {\n kind: kind,\n key: key,\n placement: placement,\n descriptor: Object.assign({}, descriptor),\n };\n\n if (kind !== \"field\") {\n this.disallowProperty(elementObject, \"initializer\", \"A method descriptor\");\n } else {\n this.disallowProperty(\n descriptor,\n \"get\",\n \"The property descriptor of a field descriptor\",\n );\n this.disallowProperty(\n descriptor,\n \"set\",\n \"The property descriptor of a field descriptor\",\n );\n this.disallowProperty(\n descriptor,\n \"value\",\n \"The property descriptor of a field descriptor\",\n );\n\n element.initializer = elementObject.initializer;\n }\n\n return element;\n },\n\n toElementFinisherExtras: function(\n elementObject /*: ElementObject */,\n ) /*: ElementFinisherExtras */ {\n var element /*: ElementDescriptor */ = this.toElementDescriptor(\n elementObject,\n );\n var finisher /*: ClassFinisher */ = _optionalCallableProperty(\n elementObject,\n \"finisher\",\n );\n var extras /*: ElementDescriptors[] */ = this.toElementDescriptors(\n elementObject.extras,\n );\n\n return { element: element, finisher: finisher, extras: extras };\n },\n\n // FromClassDescriptor\n fromClassDescriptor: function(\n elements /*: ElementDescriptor[] */,\n ) /*: ClassObject */ {\n var obj = {\n kind: \"class\",\n elements: elements.map(this.fromElementDescriptor, this),\n };\n\n var desc = { value: \"Descriptor\", configurable: true };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n\n return obj;\n },\n\n // ToClassDescriptor\n toClassDescriptor: function(\n obj /*: ClassObject */,\n ) /*: ElementsFinisher */ {\n var kind = String(obj.kind);\n if (kind !== \"class\") {\n throw new TypeError(\n 'A class descriptor\\\\'s .kind property must be \"class\", but a decorator' +\n ' created a class descriptor with .kind \"' +\n kind +\n '\"',\n );\n }\n\n this.disallowProperty(obj, \"key\", \"A class descriptor\");\n this.disallowProperty(obj, \"placement\", \"A class descriptor\");\n this.disallowProperty(obj, \"descriptor\", \"A class descriptor\");\n this.disallowProperty(obj, \"initializer\", \"A class descriptor\");\n this.disallowProperty(obj, \"extras\", \"A class descriptor\");\n\n var finisher = _optionalCallableProperty(obj, \"finisher\");\n var elements = this.toElementDescriptors(obj.elements);\n\n return { elements: elements, finisher: finisher };\n },\n\n // RunClassFinishers\n runClassFinishers: function(\n constructor /*: Class<*> */,\n finishers /*: ClassFinisher[] */,\n ) /*: Class<*> */ {\n for (var i = 0; i < finishers.length; i++) {\n var newConstructor /*: ?Class<*> */ = (0, finishers[i])(constructor);\n if (newConstructor !== undefined) {\n // NOTE: This should check if IsConstructor(newConstructor) is false.\n if (typeof newConstructor !== \"function\") {\n throw new TypeError(\"Finishers must return a constructor.\");\n }\n constructor = newConstructor;\n }\n }\n return constructor;\n },\n\n disallowProperty: function(obj, name, objectType) {\n if (obj[name] !== undefined) {\n throw new TypeError(objectType + \" can't have a .\" + name + \" property.\");\n }\n }\n };\n\n return api;\n }\n\n // ClassElementEvaluation\n function _createElementDescriptor(\n def /*: ElementDefinition */,\n ) /*: ElementDescriptor */ {\n var key = toPropertyKey(def.key);\n\n var descriptor /*: PropertyDescriptor */;\n if (def.kind === \"method\") {\n descriptor = {\n value: def.value,\n writable: true,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === \"get\") {\n descriptor = { get: def.value, configurable: true, enumerable: false };\n } else if (def.kind === \"set\") {\n descriptor = { set: def.value, configurable: true, enumerable: false };\n } else if (def.kind === \"field\") {\n descriptor = { configurable: true, writable: true, enumerable: true };\n }\n\n var element /*: ElementDescriptor */ = {\n kind: def.kind === \"field\" ? \"field\" : \"method\",\n key: key,\n placement: def.static\n ? \"static\"\n : def.kind === \"field\"\n ? \"own\"\n : \"prototype\",\n descriptor: descriptor,\n };\n if (def.decorators) element.decorators = def.decorators;\n if (def.kind === \"field\") element.initializer = def.value;\n\n return element;\n }\n\n // CoalesceGetterSetter\n function _coalesceGetterSetter(\n element /*: ElementDescriptor */,\n other /*: ElementDescriptor */,\n ) {\n if (element.descriptor.get !== undefined) {\n other.descriptor.get = element.descriptor.get;\n } else {\n other.descriptor.set = element.descriptor.set;\n }\n }\n\n // CoalesceClassElements\n function _coalesceClassElements(\n elements /*: ElementDescriptor[] */,\n ) /*: ElementDescriptor[] */ {\n var newElements /*: ElementDescriptor[] */ = [];\n\n var isSameElement = function(\n other /*: ElementDescriptor */,\n ) /*: boolean */ {\n return (\n other.kind === \"method\" &&\n other.key === element.key &&\n other.placement === element.placement\n );\n };\n\n for (var i = 0; i < elements.length; i++) {\n var element /*: ElementDescriptor */ = elements[i];\n var other /*: ElementDescriptor */;\n\n if (\n element.kind === \"method\" &&\n (other = newElements.find(isSameElement))\n ) {\n if (\n _isDataDescriptor(element.descriptor) ||\n _isDataDescriptor(other.descriptor)\n ) {\n if (_hasDecorators(element) || _hasDecorators(other)) {\n throw new ReferenceError(\n \"Duplicated methods (\" + element.key + \") can't be decorated.\",\n );\n }\n other.descriptor = element.descriptor;\n } else {\n if (_hasDecorators(element)) {\n if (_hasDecorators(other)) {\n throw new ReferenceError(\n \"Decorators can't be placed on different accessors with for \" +\n \"the same property (\" +\n element.key +\n \").\",\n );\n }\n other.decorators = element.decorators;\n }\n _coalesceGetterSetter(element, other);\n }\n } else {\n newElements.push(element);\n }\n }\n\n return newElements;\n }\n\n function _hasDecorators(element /*: ElementDescriptor */) /*: boolean */ {\n return element.decorators && element.decorators.length;\n }\n\n function _isDataDescriptor(desc /*: PropertyDescriptor */) /*: boolean */ {\n return (\n desc !== undefined &&\n !(desc.value === undefined && desc.writable === undefined)\n );\n }\n\n function _optionalCallableProperty /*::*/(\n obj /*: T */,\n name /*: $Keys */,\n ) /*: ?Function */ {\n var value = obj[name];\n if (value !== undefined && typeof value !== \"function\") {\n throw new TypeError(\"Expected '\" + name + \"' to be a function\");\n }\n return value;\n }\n\n"]); - var optsLoose = { loose: loose }; + _templateObject70 = function _templateObject70() { + return data; + }; - return { - plugins: [[_babelPluginTransformEs2015TemplateLiterals2.default, { loose: loose, spec: spec }], _babelPluginTransformEs2015Literals2.default, _babelPluginTransformEs2015FunctionName2.default, [_babelPluginTransformEs2015ArrowFunctions2.default, { spec: spec }], _babelPluginTransformEs2015BlockScopedFunctions2.default, [_babelPluginTransformEs2015Classes2.default, optsLoose], _babelPluginTransformEs2015ObjectSuper2.default, _babelPluginTransformEs2015ShorthandProperties2.default, _babelPluginTransformEs2015DuplicateKeys2.default, [_babelPluginTransformEs2015ComputedProperties2.default, optsLoose], [_babelPluginTransformEs2015ForOf2.default, optsLoose], _babelPluginTransformEs2015StickyRegex2.default, _babelPluginTransformEs2015UnicodeRegex2.default, _babelPluginCheckEs2015Constants2.default, [_babelPluginTransformEs2015Spread2.default, optsLoose], _babelPluginTransformEs2015Parameters2.default, [_babelPluginTransformEs2015Destructuring2.default, optsLoose], _babelPluginTransformEs2015BlockScoping2.default, _babelPluginTransformEs2015TypeofSymbol2.default, modules === "commonjs" && [_babelPluginTransformEs2015ModulesCommonjs2.default, optsLoose], modules === "systemjs" && [_babelPluginTransformEs2015ModulesSystemjs2.default, optsLoose], modules === "amd" && [_babelPluginTransformEs2015ModulesAmd2.default, optsLoose], modules === "umd" && [_babelPluginTransformEs2015ModulesUmd2.default, optsLoose], [_babelPluginTransformRegenerator2.default, { async: false, asyncGenerators: false }]].filter(Boolean) }; + return data; } -var oldConfig = preset({}); +function _templateObject69() { + var data = _taggedTemplateLiteral(["\n export default function _classStaticPrivateMethodSet() {\n throw new TypeError(\"attempted to set read only static private field\");\n }\n"]); -exports.default = oldConfig; + _templateObject69 = function _templateObject69() { + return data; + }; -Object.defineProperty(oldConfig, "buildPreset", { - configurable: true, - writable: true, - - enumerable: false, - value: preset -}); -module.exports = exports["default"]; -},{"babel-plugin-check-es2015-constants":62,"babel-plugin-transform-es2015-arrow-functions":64,"babel-plugin-transform-es2015-block-scoped-functions":65,"babel-plugin-transform-es2015-block-scoping":66,"babel-plugin-transform-es2015-classes":68,"babel-plugin-transform-es2015-computed-properties":71,"babel-plugin-transform-es2015-destructuring":72,"babel-plugin-transform-es2015-duplicate-keys":73,"babel-plugin-transform-es2015-for-of":74,"babel-plugin-transform-es2015-function-name":75,"babel-plugin-transform-es2015-literals":76,"babel-plugin-transform-es2015-modules-amd":77,"babel-plugin-transform-es2015-modules-commonjs":78,"babel-plugin-transform-es2015-modules-systemjs":79,"babel-plugin-transform-es2015-modules-umd":80,"babel-plugin-transform-es2015-object-super":81,"babel-plugin-transform-es2015-parameters":84,"babel-plugin-transform-es2015-shorthand-properties":86,"babel-plugin-transform-es2015-spread":87,"babel-plugin-transform-es2015-sticky-regex":88,"babel-plugin-transform-es2015-template-literals":89,"babel-plugin-transform-es2015-typeof-symbol":90,"babel-plugin-transform-es2015-unicode-regex":91,"babel-plugin-transform-regenerator":92}],95:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true }; -},{"core-js/library/fn/get-iterator":164}],96:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/json/stringify"), __esModule: true }; -},{"core-js/library/fn/json/stringify":165}],97:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/map"), __esModule: true }; -},{"core-js/library/fn/map":166}],98:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/number/max-safe-integer"), __esModule: true }; -},{"core-js/library/fn/number/max-safe-integer":167}],99:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true }; -},{"core-js/library/fn/object/assign":168}],100:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true }; -},{"core-js/library/fn/object/create":169}],101:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/get-own-property-symbols"), __esModule: true }; -},{"core-js/library/fn/object/get-own-property-symbols":170}],102:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true }; -},{"core-js/library/fn/object/keys":171}],103:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true }; -},{"core-js/library/fn/object/set-prototype-of":172}],104:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true }; -},{"core-js/library/fn/symbol":174}],105:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol/for"), __esModule: true }; -},{"core-js/library/fn/symbol/for":173}],106:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true }; -},{"core-js/library/fn/symbol/iterator":175}],107:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/weak-map"), __esModule: true }; -},{"core-js/library/fn/weak-map":176}],108:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/weak-set"), __esModule: true }; -},{"core-js/library/fn/weak-set":177}],109:[function(require,module,exports){ -"use strict"; + return data; +} -exports.__esModule = true; +function _templateObject68() { + var data = _taggedTemplateLiteral(["\n export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) {\n if (receiver !== classConstructor) {\n throw new TypeError(\"Private static access of wrong provenance\");\n }\n return method;\n }\n"]); -exports.default = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; -},{}],110:[function(require,module,exports){ -"use strict"; + _templateObject68 = function _templateObject68() { + return data; + }; -exports.__esModule = true; + return data; +} -var _setPrototypeOf = require("../core-js/object/set-prototype-of"); +function _templateObject67() { + var data = _taggedTemplateLiteral(["\n export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) {\n if (receiver !== classConstructor) {\n throw new TypeError(\"Private static access of wrong provenance\");\n }\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n // This should only throw in strict mode, but class bodies are\n // always strict and private fields can only be used inside\n // class bodies.\n throw new TypeError(\"attempted to set read only private field\");\n }\n descriptor.value = value;\n }\n\n return value;\n }\n"]); -var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); + _templateObject67 = function _templateObject67() { + return data; + }; -var _create = require("../core-js/object/create"); + return data; +} -var _create2 = _interopRequireDefault(_create); +function _templateObject66() { + var data = _taggedTemplateLiteral(["\n export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) {\n if (receiver !== classConstructor) {\n throw new TypeError(\"Private static access of wrong provenance\");\n }\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n }\n"]); -var _typeof2 = require("../helpers/typeof"); + _templateObject66 = function _templateObject66() { + return data; + }; -var _typeof3 = _interopRequireDefault(_typeof2); + return data; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _templateObject65() { + var data = _taggedTemplateLiteral(["\n export default function _classPrivateFieldDestructureSet(receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n var descriptor = privateMap.get(receiver);\n if (descriptor.set) {\n if (!(\"__destrObj\" in descriptor)) {\n descriptor.__destrObj = {\n set value(v) {\n descriptor.set.call(receiver, v)\n },\n };\n }\n return descriptor.__destrObj;\n } else {\n if (!descriptor.writable) {\n // This should only throw in strict mode, but class bodies are\n // always strict and private fields can only be used inside\n // class bodies.\n throw new TypeError(\"attempted to set read only private field\");\n }\n\n return descriptor;\n }\n }\n"]); -exports.default = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); - } + _templateObject65 = function _templateObject65() { + return data; + }; - subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; -}; -},{"../core-js/object/create":100,"../core-js/object/set-prototype-of":103,"../helpers/typeof":113}],111:[function(require,module,exports){ -"use strict"; + return data; +} -exports.__esModule = true; +function _templateObject64() { + var data = _taggedTemplateLiteral(["\n export default function _classPrivateFieldSet(receiver, privateMap, value) {\n var descriptor = privateMap.get(receiver);\n if (!descriptor) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n // This should only throw in strict mode, but class bodies are\n // always strict and private fields can only be used inside\n // class bodies.\n throw new TypeError(\"attempted to set read only private field\");\n }\n\n descriptor.value = value;\n }\n\n return value;\n }\n"]); -exports.default = function (obj, keys) { - var target = {}; + _templateObject64 = function _templateObject64() { + return data; + }; - for (var i in obj) { - if (keys.indexOf(i) >= 0) continue; - if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; - target[i] = obj[i]; - } + return data; +} - return target; -}; -},{}],112:[function(require,module,exports){ -"use strict"; +function _templateObject63() { + var data = _taggedTemplateLiteral(["\n export default function _classPrivateFieldGet(receiver, privateMap) {\n var descriptor = privateMap.get(receiver);\n if (!descriptor) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n return descriptor.value;\n }\n"]); -exports.__esModule = true; + _templateObject63 = function _templateObject63() { + return data; + }; -var _typeof2 = require("../helpers/typeof"); + return data; +} -var _typeof3 = _interopRequireDefault(_typeof2); +function _templateObject62() { + var data = _taggedTemplateLiteral(["\n export default function _classPrivateFieldBase(receiver, privateKey) {\n if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {\n throw new TypeError(\"attempted to use private field on non-instance\");\n }\n return receiver;\n }\n"]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _templateObject62 = function _templateObject62() { + return data; + }; -exports.default = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } + return data; +} - return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; -}; -},{"../helpers/typeof":113}],113:[function(require,module,exports){ -"use strict"; +function _templateObject61() { + var data = _taggedTemplateLiteral(["\n var id = 0;\n export default function _classPrivateFieldKey(name) {\n return \"__private_\" + (id++) + \"_\" + name;\n }\n"]); -exports.__esModule = true; + _templateObject61 = function _templateObject61() { + return data; + }; -var _iterator = require("../core-js/symbol/iterator"); + return data; +} -var _iterator2 = _interopRequireDefault(_iterator); +function _templateObject60() { + var data = _taggedTemplateLiteral(["\n export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context){\n var desc = {};\n Object.keys(descriptor).forEach(function(key){\n desc[key] = descriptor[key];\n });\n desc.enumerable = !!desc.enumerable;\n desc.configurable = !!desc.configurable;\n if ('value' in desc || desc.initializer){\n desc.writable = true;\n }\n\n desc = decorators.slice().reverse().reduce(function(desc, decorator){\n return decorator(target, property, desc) || desc;\n }, desc);\n\n if (context && desc.initializer !== void 0){\n desc.value = desc.initializer ? desc.initializer.call(context) : void 0;\n desc.initializer = undefined;\n }\n\n if (desc.initializer === void 0){\n // This is a hack to avoid this being processed by 'transform-runtime'.\n // See issue #9.\n Object.defineProperty(target, property, desc);\n desc = null;\n }\n\n return desc;\n }\n"]); -var _symbol = require("../core-js/symbol"); + _templateObject60 = function _templateObject60() { + return data; + }; -var _symbol2 = _interopRequireDefault(_symbol); + return data; +} -var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; +function _templateObject59() { + var data = _taggedTemplateLiteral(["\n export default function _initializerDefineProperty(target, property, descriptor, context){\n if (!descriptor) return;\n\n Object.defineProperty(target, property, {\n enumerable: descriptor.enumerable,\n configurable: descriptor.configurable,\n writable: descriptor.writable,\n value: descriptor.initializer ? descriptor.initializer.call(context) : void 0,\n });\n }\n"]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _templateObject59 = function _templateObject59() { + return data; + }; -exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { - return typeof obj === "undefined" ? "undefined" : _typeof(obj); -} : function (obj) { - return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); -}; -},{"../core-js/symbol":104,"../core-js/symbol/iterator":106}],114:[function(require,module,exports){ -"use strict"; + return data; +} -exports.__esModule = true; +function _templateObject58() { + var data = _taggedTemplateLiteral(["\n export default function _initializerWarningHelper(descriptor, context){\n throw new Error(\n 'Decorating class property failed. Please ensure that ' +\n 'proposal-class-properties is enabled and runs after the decorators transform.'\n );\n }\n"]); -var _symbol = require("babel-runtime/core-js/symbol"); + _templateObject58 = function _templateObject58() { + return data; + }; -var _symbol2 = _interopRequireDefault(_symbol); + return data; +} -exports.default = function (code, opts) { - var stack = void 0; - try { - throw new Error(); - } catch (error) { - if (error.stack) { - stack = error.stack.split("\n").slice(1).join("\n"); - } - } +function _templateObject57() { + var data = _taggedTemplateLiteral(["\n import toPrimitive from \"toPrimitive\";\n\n export default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return typeof key === \"symbol\" ? key : String(key);\n }\n"]); - opts = (0, _assign2.default)({ - allowReturnOutsideFunction: true, - allowSuperOutsideMethod: true, - preserveComments: false - }, opts); + _templateObject57 = function _templateObject57() { + return data; + }; - var _getAst = function getAst() { - var ast = void 0; + return data; +} - try { - ast = babylon.parse(code, opts); +function _templateObject56() { + var data = _taggedTemplateLiteral(["\n export default function _toPrimitive(\n input,\n hint /*: \"default\" | \"string\" | \"number\" | void */\n ) {\n if (typeof input !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (typeof res !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n }\n"]); - ast = _babelTraverse2.default.removeProperties(ast, { preserveComments: opts.preserveComments }); + _templateObject56 = function _templateObject56() { + return data; + }; - _babelTraverse2.default.cheap(ast, function (node) { - node[FROM_TEMPLATE] = true; - }); - } catch (err) { - err.stack = err.stack + "from\n" + stack; - throw err; - } + return data; +} - _getAst = function getAst() { - return ast; - }; +function _templateObject55() { + var data = _taggedTemplateLiteral(["\n export default function _skipFirstGeneratorNext(fn) {\n return function () {\n var it = fn.apply(this, arguments);\n it.next();\n return it;\n }\n }\n"]); - return ast; + _templateObject55 = function _templateObject55() { + return data; }; - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } + return data; +} - return useTemplate(_getAst(), args); +function _templateObject54() { + var data = _taggedTemplateLiteral(["\n export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n"]); + + _templateObject54 = function _templateObject54() { + return data; }; -}; -var _cloneDeep = require("lodash/cloneDeep"); + return data; +} -var _cloneDeep2 = _interopRequireDefault(_cloneDeep); +function _templateObject53() { + var data = _taggedTemplateLiteral(["\n export default function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance\");\n }\n"]); -var _assign = require("lodash/assign"); + _templateObject53 = function _templateObject53() { + return data; + }; -var _assign2 = _interopRequireDefault(_assign); + return data; +} -var _has = require("lodash/has"); +function _templateObject52() { + var data = _taggedTemplateLiteral(["\n export default function _iterableToArrayLimitLoose(arr, i) {\n if (!(\n Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\"\n )) { return }\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n }\n"]); -var _has2 = _interopRequireDefault(_has); + _templateObject52 = function _templateObject52() { + return data; + }; -var _babelTraverse = require("babel-traverse"); + return data; +} -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); +function _templateObject51() { + var data = _taggedTemplateLiteral(["\n export default function _iterableToArrayLimit(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliance is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n if (!(\n Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\"\n )) { return }\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n"], ["\n export default function _iterableToArrayLimit(arr, i) {\n // this is an expanded form of \\`for...of\\` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliance is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n if (!(\n Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\"\n )) { return }\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n"]); -var _babylon = require("babylon"); + _templateObject51 = function _templateObject51() { + return data; + }; -var babylon = _interopRequireWildcard(_babylon); + return data; +} -var _babelTypes = require("babel-types"); +function _templateObject50() { + var data = _taggedTemplateLiteral(["\n export default function _iterableToArray(iter) {\n if (\n Symbol.iterator in Object(iter) ||\n Object.prototype.toString.call(iter) === \"[object Arguments]\"\n ) return Array.from(iter);\n }\n"]); -var t = _interopRequireWildcard(_babelTypes); + _templateObject50 = function _templateObject50() { + return data; + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return data; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _templateObject49() { + var data = _taggedTemplateLiteral(["\n export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n }\n"]); -var FROM_TEMPLATE = "_fromTemplate"; -var TEMPLATE_SKIP = (0, _symbol2.default)(); + _templateObject49 = function _templateObject49() { + return data; + }; -function useTemplate(ast, nodes) { - ast = (0, _cloneDeep2.default)(ast); - var _ast = ast, - program = _ast.program; + return data; +} +function _templateObject48() { + var data = _taggedTemplateLiteral(["\n export default function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n }\n }\n"]); - if (nodes.length) { - (0, _babelTraverse2.default)(ast, templateVisitor, null, nodes); - } + _templateObject48 = function _templateObject48() { + return data; + }; - if (program.body.length > 1) { - return program.body; - } else { - return program.body[0]; - } + return data; } -var templateVisitor = { - noScope: true, - - enter: function enter(path, args) { - var node = path.node; +function _templateObject47() { + var data = _taggedTemplateLiteral(["\n import arrayWithoutHoles from \"arrayWithoutHoles\";\n import iterableToArray from \"iterableToArray\";\n import nonIterableSpread from \"nonIterableSpread\";\n\n export default function _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();\n }\n"]); - if (node[TEMPLATE_SKIP]) return path.skip(); + _templateObject47 = function _templateObject47() { + return data; + }; - if (t.isExpressionStatement(node)) { - node = node.expression; - } + return data; +} - var replacement = void 0; +function _templateObject46() { + var data = _taggedTemplateLiteral(["\n import arrayWithHoles from \"arrayWithHoles\";\n import iterableToArray from \"iterableToArray\";\n import nonIterableRest from \"nonIterableRest\";\n\n export default function _toArray(arr) {\n return arrayWithHoles(arr) || iterableToArray(arr) || nonIterableRest();\n }\n"]); - if (t.isIdentifier(node) && node[FROM_TEMPLATE]) { - if ((0, _has2.default)(args[0], node.name)) { - replacement = args[0][node.name]; - } else if (node.name[0] === "$") { - var i = +node.name.slice(1); - if (args[i]) replacement = args[i]; - } - } + _templateObject46 = function _templateObject46() { + return data; + }; - if (replacement === null) { - path.remove(); - } + return data; +} - if (replacement) { - replacement[TEMPLATE_SKIP] = true; - path.replaceInline(replacement); - } - }, - exit: function exit(_ref) { - var node = _ref.node; +function _templateObject45() { + var data = _taggedTemplateLiteral(["\n import arrayWithHoles from \"arrayWithHoles\";\n import iterableToArrayLimitLoose from \"iterableToArrayLimitLoose\";\n import nonIterableRest from \"nonIterableRest\";\n\n export default function _slicedToArrayLoose(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || nonIterableRest();\n }\n"]); - if (!node.loc) _babelTraverse2.default.clearNode(node); - } -}; -module.exports = exports["default"]; -},{"babel-runtime/core-js/symbol":104,"babel-traverse":118,"babel-types":151,"babylon":155,"lodash/assign":463,"lodash/cloneDeep":467,"lodash/has":479}],115:[function(require,module,exports){ -"use strict"; + _templateObject45 = function _templateObject45() { + return data; + }; -exports.__esModule = true; -exports.scope = exports.path = undefined; + return data; +} -var _weakMap = require("babel-runtime/core-js/weak-map"); +function _templateObject44() { + var data = _taggedTemplateLiteral(["\n import arrayWithHoles from \"arrayWithHoles\";\n import iterableToArrayLimit from \"iterableToArrayLimit\";\n import nonIterableRest from \"nonIterableRest\";\n\n export default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();\n }\n"]); -var _weakMap2 = _interopRequireDefault(_weakMap); + _templateObject44 = function _templateObject44() { + return data; + }; -exports.clear = clear; -exports.clearPath = clearPath; -exports.clearScope = clearScope; + return data; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _templateObject43() { + var data = _taggedTemplateLiteral(["\n import undef from \"temporalUndefined\";\n import err from \"tdz\";\n\n export default function _temporalRef(val, name) {\n return val === undef ? err(name) : val;\n }\n"]); -var path = exports.path = new _weakMap2.default(); -var scope = exports.scope = new _weakMap2.default(); + _templateObject43 = function _templateObject43() { + return data; + }; -function clear() { - clearPath(); - clearScope(); + return data; } -function clearPath() { - exports.path = path = new _weakMap2.default(); -} +function _templateObject42() { + var data = _taggedTemplateLiteral(["\n export default function _tdzError(name) {\n throw new ReferenceError(name + \" is not defined - temporal dead zone\");\n }\n"]); -function clearScope() { - exports.scope = scope = new _weakMap2.default(); + _templateObject42 = function _templateObject42() { + return data; + }; + + return data; } -},{"babel-runtime/core-js/weak-map":107}],116:[function(require,module,exports){ -(function (process){ -"use strict"; -exports.__esModule = true; +function _templateObject41() { + var data = _taggedTemplateLiteral(["\n // This function isn't mean to be called, but to be used as a reference.\n // We can't use a normal object because it isn't hoisted.\n export default function _temporalUndefined() {}\n"]); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + _templateObject41 = function _templateObject41() { + return data; + }; -var _getIterator3 = _interopRequireDefault(_getIterator2); + return data; +} -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +function _templateObject40() { + var data = _taggedTemplateLiteral(["\n export default function _classNameTDZError(name) {\n throw new Error(\"Class \\\"\" + name + \"\\\" cannot be referenced in computed property keys.\");\n }\n"], ["\n export default function _classNameTDZError(name) {\n throw new Error(\"Class \\\\\"\" + name + \"\\\\\" cannot be referenced in computed property keys.\");\n }\n"]); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + _templateObject40 = function _templateObject40() { + return data; + }; -var _path2 = require("./path"); + return data; +} -var _path3 = _interopRequireDefault(_path2); +function _templateObject39() { + var data = _taggedTemplateLiteral(["\n export default function _readOnlyError(name) {\n throw new Error(\"\\\"\" + name + \"\\\" is read-only\");\n }\n"], ["\n export default function _readOnlyError(name) {\n throw new Error(\"\\\\\"\" + name + \"\\\\\" is read-only\");\n }\n"]); -var _babelTypes = require("babel-types"); + _templateObject39 = function _templateObject39() { + return data; + }; -var t = _interopRequireWildcard(_babelTypes); + return data; +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _templateObject38() { + var data = _taggedTemplateLiteral(["\n export default function _taggedTemplateLiteralLoose(strings, raw) {\n if (!raw) { raw = strings.slice(0); }\n strings.raw = raw;\n return strings;\n }\n"]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _templateObject38 = function _templateObject38() { + return data; + }; -var testing = process.env.NODE_ENV === "test"; + return data; +} -var TraversalContext = function () { - function TraversalContext(scope, opts, state, parentPath) { - (0, _classCallCheck3.default)(this, TraversalContext); - this.queue = null; +function _templateObject37() { + var data = _taggedTemplateLiteral(["\n export default function _taggedTemplateLiteral(strings, raw) {\n if (!raw) { raw = strings.slice(0); }\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n }\n"]); - this.parentPath = parentPath; - this.scope = scope; - this.state = state; - this.opts = opts; - } + _templateObject37 = function _templateObject37() { + return data; + }; - TraversalContext.prototype.shouldVisit = function shouldVisit(node) { - var opts = this.opts; - if (opts.enter || opts.exit) return true; + return data; +} - if (opts[node.type]) return true; +function _templateObject36() { + var data = _taggedTemplateLiteral(["\n import superPropBase from \"superPropBase\";\n import defineProperty from \"defineProperty\";\n\n function set(target, property, value, receiver) {\n if (typeof Reflect !== \"undefined\" && Reflect.set) {\n set = Reflect.set;\n } else {\n set = function set(target, property, value, receiver) {\n var base = superPropBase(target, property);\n var desc;\n\n if (base) {\n desc = Object.getOwnPropertyDescriptor(base, property);\n if (desc.set) {\n desc.set.call(receiver, value);\n return true;\n } else if (!desc.writable) {\n // Both getter and non-writable fall into this.\n return false;\n }\n }\n\n // Without a super that defines the property, spec boils down to\n // \"define on receiver\" for some reason.\n desc = Object.getOwnPropertyDescriptor(receiver, property);\n if (desc) {\n if (!desc.writable) {\n // Setter, getter, and non-writable fall into this.\n return false;\n }\n\n desc.value = value;\n Object.defineProperty(receiver, property, desc);\n } else {\n // Avoid setters that may be defined on Sub's prototype, but not on\n // the instance.\n defineProperty(receiver, property, value);\n }\n\n return true;\n };\n }\n\n return set(target, property, value, receiver);\n }\n\n export default function _set(target, property, value, receiver, isStrict) {\n var s = set(target, property, value, receiver || target);\n if (!s && isStrict) {\n throw new Error('failed to set property');\n }\n\n return value;\n }\n"]); - var keys = t.VISITOR_KEYS[node.type]; - if (!keys || !keys.length) return false; + _templateObject36 = function _templateObject36() { + return data; + }; - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + return data; +} - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +function _templateObject35() { + var data = _taggedTemplateLiteral(["\n import superPropBase from \"superPropBase\";\n\n export default function _get(target, property, receiver) {\n if (typeof Reflect !== \"undefined\" && Reflect.get) {\n _get = Reflect.get;\n } else {\n _get = function _get(target, property, receiver) {\n var base = superPropBase(target, property);\n\n if (!base) return;\n\n var desc = Object.getOwnPropertyDescriptor(base, property);\n if (desc.get) {\n return desc.get.call(receiver);\n }\n\n return desc.value;\n };\n }\n return _get(target, property, receiver || target);\n }\n"]); - var key = _ref; + _templateObject35 = function _templateObject35() { + return data; + }; - if (node[key]) return true; - } + return data; +} - return false; - }; +function _templateObject34() { + var data = _taggedTemplateLiteral(["\n import getPrototypeOf from \"getPrototypeOf\";\n\n export default function _superPropBase(object, property) {\n // Yes, this throws if object is null to being with, that's on purpose.\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = getPrototypeOf(object);\n if (object === null) break;\n }\n return object;\n }\n"]); - TraversalContext.prototype.create = function create(node, obj, key, listKey) { - return _path3.default.get({ - parentPath: this.parentPath, - parent: node, - container: obj, - key: key, - listKey: listKey - }); + _templateObject34 = function _templateObject34() { + return data; }; - TraversalContext.prototype.maybeQueue = function maybeQueue(path, notPriority) { - if (this.trap) { - throw new Error("Infinite cycle detected"); - } + return data; +} - if (this.queue) { - if (notPriority) { - this.queue.push(path); - } else { - this.priorityQueue.push(path); - } - } - }; +function _templateObject33() { + var data = _taggedTemplateLiteral(["\n import assertThisInitialized from \"assertThisInitialized\";\n\n export default function _possibleConstructorReturn(self, call) {\n if (call && (typeof call === \"object\" || typeof call === \"function\")) {\n return call;\n }\n return assertThisInitialized(self);\n }\n"]); - TraversalContext.prototype.visitMultiple = function visitMultiple(container, parent, listKey) { - if (container.length === 0) return false; + _templateObject33 = function _templateObject33() { + return data; + }; - var queue = []; + return data; +} - for (var key = 0; key < container.length; key++) { - var node = container[key]; - if (node && this.shouldVisit(node)) { - queue.push(this.create(parent, container, key, listKey)); - } - } +function _templateObject32() { + var data = _taggedTemplateLiteral(["\n export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n }\n"]); - return this.visitQueue(queue); + _templateObject32 = function _templateObject32() { + return data; }; - TraversalContext.prototype.visitSingle = function visitSingle(node, key) { - if (this.shouldVisit(node[key])) { - return this.visitQueue([this.create(node, node, key)]); - } else { - return false; - } + return data; +} + +function _templateObject31() { + var data = _taggedTemplateLiteral(["\n import objectWithoutPropertiesLoose from \"objectWithoutPropertiesLoose\";\n\n export default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n }\n"]); + + _templateObject31 = function _templateObject31() { + return data; }; - TraversalContext.prototype.visitQueue = function visitQueue(queue) { - this.queue = queue; - this.priorityQueue = []; + return data; +} - var visited = []; - var stop = false; +function _templateObject30() { + var data = _taggedTemplateLiteral(["\n export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n }\n"]); - for (var _iterator2 = queue, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + _templateObject30 = function _templateObject30() { + return data; + }; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + return data; +} - var path = _ref2; +function _templateObject29() { + var data = _taggedTemplateLiteral(["\n export default function _objectDestructuringEmpty(obj) {\n if (obj == null) throw new TypeError(\"Cannot destructure undefined\");\n }\n"]); - path.resync(); + _templateObject29 = function _templateObject29() { + return data; + }; - if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) { - path.pushContext(this); - } + return data; +} - if (path.key === null) continue; +function _templateObject28() { + var data = _taggedTemplateLiteral(["\n export default function _newArrowCheck(innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError(\"Cannot instantiate an arrow function\");\n }\n }\n"]); - if (testing && queue.length >= 10000) { - this.trap = true; - } + _templateObject28 = function _templateObject28() { + return data; + }; - if (visited.indexOf(path.node) >= 0) continue; - visited.push(path.node); + return data; +} - if (path.visit()) { - stop = true; - break; - } +function _templateObject27() { + var data = _taggedTemplateLiteral(["\n function _getRequireWildcardCache() {\n if (typeof WeakMap !== \"function\") return null;\n\n var cache = new WeakMap();\n _getRequireWildcardCache = function () { return cache; };\n return cache;\n }\n\n export default function _interopRequireWildcard(obj) {\n if (obj && obj.__esModule) {\n return obj;\n }\n\n if (obj === null || (typeof obj !== \"object\" && typeof obj !== \"function\")) {\n return { default: obj }\n }\n\n var cache = _getRequireWildcardCache();\n if (cache && cache.has(obj)) {\n return cache.get(obj);\n }\n\n var newObj = {};\n var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc = hasPropertyDescriptor\n ? Object.getOwnPropertyDescriptor(obj, key)\n : null;\n if (desc && (desc.get || desc.set)) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n newObj.default = obj;\n if (cache) {\n cache.set(obj, newObj);\n }\n return newObj;\n }\n"]); - if (this.priorityQueue.length) { - stop = this.visitQueue(this.priorityQueue); - this.priorityQueue = []; - this.queue = queue; - if (stop) break; - } - } + _templateObject27 = function _templateObject27() { + return data; + }; - for (var _iterator3 = queue, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + return data; +} - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } +function _templateObject26() { + var data = _taggedTemplateLiteral(["\n export default function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n }\n"]); - var _path = _ref3; + _templateObject26 = function _templateObject26() { + return data; + }; - _path.popContext(); - } + return data; +} - this.queue = null; +function _templateObject25() { + var data = _taggedTemplateLiteral(["\n export default function _instanceof(left, right) {\n if (right != null && typeof Symbol !== \"undefined\" && right[Symbol.hasInstance]) {\n return !!right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n }\n"]); - return stop; + _templateObject25 = function _templateObject25() { + return data; }; - TraversalContext.prototype.visit = function visit(node, key) { - var nodes = node[key]; - if (!nodes) return false; + return data; +} - if (Array.isArray(nodes)) { - return this.visitMultiple(nodes, node, key); - } else { - return this.visitSingle(node, key); - } +function _templateObject24() { + var data = _taggedTemplateLiteral(["\n import getPrototypeOf from \"getPrototypeOf\";\n import setPrototypeOf from \"setPrototypeOf\";\n import isNativeFunction from \"isNativeFunction\";\n import construct from \"construct\";\n\n export default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor)\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true,\n }\n });\n\n return setPrototypeOf(Wrapper, Class);\n }\n\n return _wrapNativeSuper(Class)\n }\n"]); + + _templateObject24 = function _templateObject24() { + return data; }; - return TraversalContext; -}(); + return data; +} -exports.default = TraversalContext; -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./path":125,"_process":525,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-types":151}],117:[function(require,module,exports){ -"use strict"; +function _templateObject23() { + var data = _taggedTemplateLiteral(["\n export default function _isNativeFunction(fn) {\n // Note: This function returns \"true\" for core-js functions.\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n }\n"]); -exports.__esModule = true; + _templateObject23 = function _templateObject23() { + return data; + }; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + return data; +} -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +function _templateObject22() { + var data = _taggedTemplateLiteral(["\n import setPrototypeOf from \"setPrototypeOf\";\n\n function isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n\n // core-js@3\n if (Reflect.construct.sham) return false;\n\n // Proxy can't be polyfilled. Every browser implemented\n // proxies before or at the same time as Reflect.construct,\n // so if they support Proxy they also support Reflect.construct.\n if (typeof Proxy === \"function\") return true;\n\n // Since Reflect.construct can't be properly polyfilled, some\n // implementations (e.g. core-js@2) don't set the correct internal slots.\n // Those polyfills don't allow us to subclass built-ins, so we need to\n // use our fallback implementation.\n try {\n // If the internal slots aren't set, this throws an error similar to\n // TypeError: this is not a Date object.\n Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));\n return true;\n } catch (e) {\n return false;\n }\n }\n\n export default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n // NOTE: If Parent !== Class, the correct __proto__ is set *after*\n // calling the constructor.\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n // Avoid issues with Class being present but undefined when it wasn't\n // present in the original call.\n return _construct.apply(null, arguments);\n }\n"]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _templateObject22 = function _templateObject22() { + return data; + }; -var Hub = function Hub(file, options) { - (0, _classCallCheck3.default)(this, Hub); + return data; +} - this.file = file; - this.options = options; -}; +function _templateObject21() { + var data = _taggedTemplateLiteral(["\n export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n }\n"]); -exports.default = Hub; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109}],118:[function(require,module,exports){ -"use strict"; + _templateObject21 = function _templateObject21() { + return data; + }; -exports.__esModule = true; -exports.visitors = exports.Hub = exports.Scope = exports.NodePath = undefined; + return data; +} -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function _templateObject20() { + var data = _taggedTemplateLiteral(["\n export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf\n ? Object.getPrototypeOf\n : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n }\n"]); -var _getIterator3 = _interopRequireDefault(_getIterator2); + _templateObject20 = function _templateObject20() { + return data; + }; -var _path = require("./path"); + return data; +} -Object.defineProperty(exports, "NodePath", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_path).default; - } -}); +function _templateObject19() { + var data = _taggedTemplateLiteral(["\n export default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n }\n"]); -var _scope = require("./scope"); + _templateObject19 = function _templateObject19() { + return data; + }; -Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_scope).default; - } -}); + return data; +} -var _hub = require("./hub"); +function _templateObject18() { + var data = _taggedTemplateLiteral(["\n import setPrototypeOf from \"setPrototypeOf\";\n\n export default function _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n }\n"]); -Object.defineProperty(exports, "Hub", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_hub).default; - } -}); -exports.default = traverse; + _templateObject18 = function _templateObject18() { + return data; + }; -var _context = require("./context"); + return data; +} -var _context2 = _interopRequireDefault(_context); +function _templateObject17() { + var data = _taggedTemplateLiteral(["\n import defineProperty from \"defineProperty\";\n\n // This function is different to \"Reflect.ownKeys\". The enumerableOnly\n // filters on symbol properties only. Returned string properties are always\n // enumerable. It is good to use in objectSpread.\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n return keys;\n }\n\n export default function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = (arguments[i] != null) ? arguments[i] : {};\n if (i % 2) {\n ownKeys(source, true).forEach(function (key) {\n defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(source).forEach(function (key) {\n Object.defineProperty(\n target,\n key,\n Object.getOwnPropertyDescriptor(source, key)\n );\n });\n }\n }\n return target;\n }\n"]); -var _visitors = require("./visitors"); + _templateObject17 = function _templateObject17() { + return data; + }; -var visitors = _interopRequireWildcard(_visitors); + return data; +} -var _babelMessages = require("babel-messages"); +function _templateObject16() { + var data = _taggedTemplateLiteral(["\n import defineProperty from \"defineProperty\";\n\n export default function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = (arguments[i] != null) ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n ownKeys.forEach(function(key) {\n defineProperty(target, key, source[key]);\n });\n }\n return target;\n }\n"]); -var messages = _interopRequireWildcard(_babelMessages); + _templateObject16 = function _templateObject16() { + return data; + }; -var _includes = require("lodash/includes"); + return data; +} -var _includes2 = _interopRequireDefault(_includes); +function _templateObject15() { + var data = _taggedTemplateLiteral(["\n export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n\n return _extends.apply(this, arguments);\n }\n"]); -var _babelTypes = require("babel-types"); + _templateObject15 = function _templateObject15() { + return data; + }; -var t = _interopRequireWildcard(_babelTypes); + return data; +} -var _cache = require("./cache"); +function _templateObject14() { + var data = _taggedTemplateLiteral(["\n export default function _defineProperty(obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n }\n"]); -var cache = _interopRequireWildcard(_cache); + _templateObject14 = function _templateObject14() { + return data; + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return data; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _templateObject13() { + var data = _taggedTemplateLiteral(["\n export default function _defaults(obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n }\n"]); -exports.visitors = visitors; -function traverse(parent, opts, scope, state, parentPath) { - if (!parent) return; - if (!opts) opts = {}; + _templateObject13 = function _templateObject13() { + return data; + }; - if (!opts.noScope && !scope) { - if (parent.type !== "Program" && parent.type !== "File") { - throw new Error(messages.get("traverseNeedsParent", parent.type)); - } - } + return data; +} - visitors.explode(opts); +function _templateObject12() { + var data = _taggedTemplateLiteral(["\n export default function _defineEnumerableProperties(obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if (\"value\" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n\n // Symbols are not enumerated over by for-in loops. If native\n // Symbols are available, fetch all of the descs object's own\n // symbol properties and define them on our target object too.\n if (Object.getOwnPropertySymbols) {\n var objectSymbols = Object.getOwnPropertySymbols(descs);\n for (var i = 0; i < objectSymbols.length; i++) {\n var sym = objectSymbols[i];\n var desc = descs[sym];\n desc.configurable = desc.enumerable = true;\n if (\"value\" in desc) desc.writable = true;\n Object.defineProperty(obj, sym, desc);\n }\n }\n return obj;\n }\n"]); - traverse.node(parent, opts, scope, state, parentPath); + _templateObject12 = function _templateObject12() { + return data; + }; + + return data; } -traverse.visitors = visitors; -traverse.verify = visitors.verify; -traverse.explode = visitors.explode; +function _templateObject11() { + var data = _taggedTemplateLiteral(["\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n export default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n"]); -traverse.NodePath = require("./path"); -traverse.Scope = require("./scope"); -traverse.Hub = require("./hub"); + _templateObject11 = function _templateObject11() { + return data; + }; -traverse.cheap = function (node, enter) { - return t.traverseFast(node, enter); -}; + return data; +} -traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { - var keys = t.VISITOR_KEYS[node.type]; - if (!keys) return; +function _templateObject10() { + var data = _taggedTemplateLiteral(["\n export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n }\n"]); - var context = new _context2.default(scope, opts, state, parentPath); - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + _templateObject10 = function _templateObject10() { + return data; + }; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + return data; +} - var key = _ref; +function _templateObject9() { + var data = _taggedTemplateLiteral(["\n function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n }\n\n export default function _asyncToGenerator(fn) {\n return function () {\n var self = this, args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\n });\n };\n }\n"]); - if (skipKeys && skipKeys[key]) continue; - if (context.visit(node, key)) return; - } -}; + _templateObject9 = function _templateObject9() { + return data; + }; -traverse.clearNode = function (node, opts) { - t.removeProperties(node, opts); + return data; +} - cache.path.delete(node); -}; +function _templateObject8() { + var data = _taggedTemplateLiteral(["\n export default function _asyncGeneratorDelegate(inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === \"function\" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump(\"next\", value);\n };\n\n if (typeof inner.throw === \"function\") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump(\"throw\", value);\n };\n }\n\n if (typeof inner.return === \"function\") {\n iter.return = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump(\"return\", value);\n };\n }\n\n return iter;\n }\n"]); -traverse.removeProperties = function (tree, opts) { - t.traverseFast(tree, traverse.clearNode, opts); - return tree; -}; + _templateObject8 = function _templateObject8() { + return data; + }; -function hasBlacklistedType(path, state) { - if (path.node.type === state.type) { - state.has = true; - path.stop(); - } + return data; } -traverse.hasType = function (tree, scope, type, blacklistTypes) { - if ((0, _includes2.default)(blacklistTypes, tree.type)) return false; - - if (tree.type === type) return true; +function _templateObject7() { + var data = _taggedTemplateLiteral(["\n import AwaitValue from \"AwaitValue\";\n\n export default function _awaitAsyncGenerator(value) {\n return new AwaitValue(value);\n }\n"]); - var state = { - has: false, - type: type + _templateObject7 = function _templateObject7() { + return data; }; - traverse(tree, { - blacklist: blacklistTypes, - enter: hasBlacklistedType - }, scope, state); + return data; +} - return state.has; -}; +function _templateObject6() { + var data = _taggedTemplateLiteral(["\n import AsyncGenerator from \"AsyncGenerator\";\n\n export default function _wrapAsyncGenerator(fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n }\n"]); -traverse.clearCache = function () { - cache.clear(); -}; + _templateObject6 = function _templateObject6() { + return data; + }; -traverse.clearCache.clearPath = cache.clearPath; -traverse.clearCache.clearScope = cache.clearScope; + return data; +} -traverse.copyCache = function (source, destination) { - if (cache.path.has(source)) { - cache.path.set(destination, cache.path.get(source)); - } -}; -},{"./cache":115,"./context":116,"./hub":117,"./path":125,"./scope":137,"./visitors":139,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-types":151,"lodash/includes":482}],119:[function(require,module,exports){ -"use strict"; +function _templateObject5() { + var data = _taggedTemplateLiteral(["\n import AwaitValue from \"AwaitValue\";\n\n export default function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null,\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n var wrappedAwait = value instanceof AwaitValue;\n\n Promise.resolve(wrappedAwait ? value.wrapped : value).then(\n function (arg) {\n if (wrappedAwait) {\n resume(key === \"return\" ? \"return\" : \"next\", arg);\n return\n }\n\n settle(result.done ? \"return\" : \"normal\", arg);\n },\n function (err) { resume(\"throw\", err); });\n } catch (err) {\n settle(\"throw\", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case \"return\":\n front.resolve({ value: value, done: true });\n break;\n case \"throw\":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide \"return\" method if generator return is not supported\n if (typeof gen.return !== \"function\") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === \"function\" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke(\"next\", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke(\"throw\", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke(\"return\", arg); };\n"]); -exports.__esModule = true; + _templateObject5 = function _templateObject5() { + return data; + }; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + return data; +} -var _getIterator3 = _interopRequireDefault(_getIterator2); +function _templateObject4() { + var data = _taggedTemplateLiteral(["\n export default function _AwaitValue(value) {\n this.wrapped = value;\n }\n"]); -exports.findParent = findParent; -exports.find = find; -exports.getFunctionParent = getFunctionParent; -exports.getStatementParent = getStatementParent; -exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom; -exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom; -exports.getAncestry = getAncestry; -exports.isAncestor = isAncestor; -exports.isDescendant = isDescendant; -exports.inType = inType; -exports.inShadow = inShadow; + _templateObject4 = function _templateObject4() { + return data; + }; -var _babelTypes = require("babel-types"); + return data; +} -var t = _interopRequireWildcard(_babelTypes); +function _templateObject3() { + var data = _taggedTemplateLiteral(["\n export default function _asyncIterator(iterable) {\n var method\n if (typeof Symbol !== \"undefined\") {\n if (Symbol.asyncIterator) {\n method = iterable[Symbol.asyncIterator]\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n method = iterable[Symbol.iterator]\n if (method != null) return method.call(iterable);\n }\n }\n throw new TypeError(\"Object is not async iterable\");\n }\n"]); -var _index = require("./index"); + _templateObject3 = function _templateObject3() { + return data; + }; -var _index2 = _interopRequireDefault(_index); + return data; +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _templateObject2() { + var data = _taggedTemplateLiteral(["\n var REACT_ELEMENT_TYPE;\n\n export default function _createRawReactElement(type, props, key, children) {\n if (!REACT_ELEMENT_TYPE) {\n REACT_ELEMENT_TYPE = (\n typeof Symbol === \"function\" && Symbol[\"for\"] && Symbol[\"for\"](\"react.element\")\n ) || 0xeac7;\n }\n\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we're going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {\n children: void 0,\n };\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = new Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n }\n"]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _templateObject2 = function _templateObject2() { + return data; + }; -function findParent(callback) { - var path = this; - while (path = path.parentPath) { - if (callback(path)) return path; - } - return null; + return data; } -function find(callback) { - var path = this; - do { - if (callback(path)) return path; - } while (path = path.parentPath); - return null; -} +function _templateObject() { + var data = _taggedTemplateLiteral(["\n export default function _typeof(obj) {\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) { return typeof obj; };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? \"symbol\"\n : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n"]); -function getFunctionParent() { - return this.findParent(function (path) { - return path.isFunction() || path.isProgram(); - }); -} + _templateObject = function _templateObject() { + return data; + }; -function getStatementParent() { - var path = this; - do { - if (Array.isArray(path.container)) { - return path; - } - } while (path = path.parentPath); + return data; } -function getEarliestCommonAncestorFrom(paths) { - return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) { - var earliest = void 0; - var keys = t.VISITOR_KEYS[deepest.type]; +function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } - for (var _iterator = ancestries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +var _template = _interopRequireDefault(require("@babel/template")); - var ancestry = _ref; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - var path = ancestry[i + 1]; +var helpers = Object.create(null); +var _default = helpers; +exports.default = _default; - if (!earliest) { - earliest = path; - continue; +var helper = function helper(minVersion) { + return function (tpl) { + return { + minVersion: minVersion, + ast: function ast() { + return _template.default.program.ast(tpl); } + }; + }; +}; - if (path.listKey && earliest.listKey === path.listKey) { - if (path.key < earliest.key) { - earliest = path; - continue; - } - } +helpers.typeof = helper("7.0.0-beta.0")(_templateObject()); +helpers.jsx = helper("7.0.0-beta.0")(_templateObject2()); +helpers.asyncIterator = helper("7.0.0-beta.0")(_templateObject3()); +helpers.AwaitValue = helper("7.0.0-beta.0")(_templateObject4()); +helpers.AsyncGenerator = helper("7.0.0-beta.0")(_templateObject5()); +helpers.wrapAsyncGenerator = helper("7.0.0-beta.0")(_templateObject6()); +helpers.awaitAsyncGenerator = helper("7.0.0-beta.0")(_templateObject7()); +helpers.asyncGeneratorDelegate = helper("7.0.0-beta.0")(_templateObject8()); +helpers.asyncToGenerator = helper("7.0.0-beta.0")(_templateObject9()); +helpers.classCallCheck = helper("7.0.0-beta.0")(_templateObject10()); +helpers.createClass = helper("7.0.0-beta.0")(_templateObject11()); +helpers.defineEnumerableProperties = helper("7.0.0-beta.0")(_templateObject12()); +helpers.defaults = helper("7.0.0-beta.0")(_templateObject13()); +helpers.defineProperty = helper("7.0.0-beta.0")(_templateObject14()); +helpers.extends = helper("7.0.0-beta.0")(_templateObject15()); +helpers.objectSpread = helper("7.0.0-beta.0")(_templateObject16()); +helpers.objectSpread2 = helper("7.5.0")(_templateObject17()); +helpers.inherits = helper("7.0.0-beta.0")(_templateObject18()); +helpers.inheritsLoose = helper("7.0.0-beta.0")(_templateObject19()); +helpers.getPrototypeOf = helper("7.0.0-beta.0")(_templateObject20()); +helpers.setPrototypeOf = helper("7.0.0-beta.0")(_templateObject21()); +helpers.construct = helper("7.0.0-beta.0")(_templateObject22()); +helpers.isNativeFunction = helper("7.0.0-beta.0")(_templateObject23()); +helpers.wrapNativeSuper = helper("7.0.0-beta.0")(_templateObject24()); +helpers.instanceof = helper("7.0.0-beta.0")(_templateObject25()); +helpers.interopRequireDefault = helper("7.0.0-beta.0")(_templateObject26()); +helpers.interopRequireWildcard = helper("7.0.0-beta.0")(_templateObject27()); +helpers.newArrowCheck = helper("7.0.0-beta.0")(_templateObject28()); +helpers.objectDestructuringEmpty = helper("7.0.0-beta.0")(_templateObject29()); +helpers.objectWithoutPropertiesLoose = helper("7.0.0-beta.0")(_templateObject30()); +helpers.objectWithoutProperties = helper("7.0.0-beta.0")(_templateObject31()); +helpers.assertThisInitialized = helper("7.0.0-beta.0")(_templateObject32()); +helpers.possibleConstructorReturn = helper("7.0.0-beta.0")(_templateObject33()); +helpers.superPropBase = helper("7.0.0-beta.0")(_templateObject34()); +helpers.get = helper("7.0.0-beta.0")(_templateObject35()); +helpers.set = helper("7.0.0-beta.0")(_templateObject36()); +helpers.taggedTemplateLiteral = helper("7.0.0-beta.0")(_templateObject37()); +helpers.taggedTemplateLiteralLoose = helper("7.0.0-beta.0")(_templateObject38()); +helpers.readOnlyError = helper("7.0.0-beta.0")(_templateObject39()); +helpers.classNameTDZError = helper("7.0.0-beta.0")(_templateObject40()); +helpers.temporalUndefined = helper("7.0.0-beta.0")(_templateObject41()); +helpers.tdz = helper("7.5.5")(_templateObject42()); +helpers.temporalRef = helper("7.0.0-beta.0")(_templateObject43()); +helpers.slicedToArray = helper("7.0.0-beta.0")(_templateObject44()); +helpers.slicedToArrayLoose = helper("7.0.0-beta.0")(_templateObject45()); +helpers.toArray = helper("7.0.0-beta.0")(_templateObject46()); +helpers.toConsumableArray = helper("7.0.0-beta.0")(_templateObject47()); +helpers.arrayWithoutHoles = helper("7.0.0-beta.0")(_templateObject48()); +helpers.arrayWithHoles = helper("7.0.0-beta.0")(_templateObject49()); +helpers.iterableToArray = helper("7.0.0-beta.0")(_templateObject50()); +helpers.iterableToArrayLimit = helper("7.0.0-beta.0")(_templateObject51()); +helpers.iterableToArrayLimitLoose = helper("7.0.0-beta.0")(_templateObject52()); +helpers.nonIterableSpread = helper("7.0.0-beta.0")(_templateObject53()); +helpers.nonIterableRest = helper("7.0.0-beta.0")(_templateObject54()); +helpers.skipFirstGeneratorNext = helper("7.0.0-beta.0")(_templateObject55()); +helpers.toPrimitive = helper("7.1.5")(_templateObject56()); +helpers.toPropertyKey = helper("7.1.5")(_templateObject57()); +helpers.initializerWarningHelper = helper("7.0.0-beta.0")(_templateObject58()); +helpers.initializerDefineProperty = helper("7.0.0-beta.0")(_templateObject59()); +helpers.applyDecoratedDescriptor = helper("7.0.0-beta.0")(_templateObject60()); +helpers.classPrivateFieldLooseKey = helper("7.0.0-beta.0")(_templateObject61()); +helpers.classPrivateFieldLooseBase = helper("7.0.0-beta.0")(_templateObject62()); +helpers.classPrivateFieldGet = helper("7.0.0-beta.0")(_templateObject63()); +helpers.classPrivateFieldSet = helper("7.0.0-beta.0")(_templateObject64()); +helpers.classPrivateFieldDestructureSet = helper("7.4.4")(_templateObject65()); +helpers.classStaticPrivateFieldSpecGet = helper("7.0.2")(_templateObject66()); +helpers.classStaticPrivateFieldSpecSet = helper("7.0.2")(_templateObject67()); +helpers.classStaticPrivateMethodGet = helper("7.3.2")(_templateObject68()); +helpers.classStaticPrivateMethodSet = helper("7.3.2")(_templateObject69()); +helpers.decorate = helper("7.1.5")(_templateObject70()); +helpers.classPrivateMethodGet = helper("7.1.6")(_templateObject71()); +helpers.classPrivateMethodSet = helper("7.1.6")(_templateObject72()); +helpers.wrapRegExp = helper("7.2.6")(_templateObject73()); + +},{"@babel/template":167}],87:[function(require,module,exports){ +"use strict"; - var earliestKeyIndex = keys.indexOf(earliest.parentKey); - var currentKeyIndex = keys.indexOf(path.parentKey); - if (earliestKeyIndex > currentKeyIndex) { - earliest = path; - } - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.get = get; +exports.minVersion = minVersion; +exports.getDependencies = getDependencies; +exports.ensure = ensure; +exports.default = exports.list = void 0; - return earliest; - }); +var _traverse = _interopRequireDefault(require("@babel/traverse")); + +var t = _interopRequireWildcard(require("@babel/types")); + +var _helpers = _interopRequireDefault(require("./helpers")); + +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); + + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + + return cache; } -function getDeepestCommonAncestorFrom(paths, filter) { - var _this = this; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } - if (!paths.length) { - return this; + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); } - if (paths.length === 1) { - return paths[0]; + var newObj = {}; + + if (obj != null) { + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } } - var minDepth = Infinity; + newObj.default = obj; - var lastCommonIndex = void 0, - lastCommon = void 0; + if (cache) { + cache.set(obj, newObj); + } - var ancestries = paths.map(function (path) { - var ancestry = []; + return newObj; +} - do { - ancestry.unshift(path); - } while ((path = path.parentPath) && path !== _this); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - if (ancestry.length < minDepth) { - minDepth = ancestry.length; - } +function makePath(path) { + var parts = []; - return ancestry; - }); + for (; path.parentPath; path = path.parentPath) { + parts.push(path.key); + if (path.inList) parts.push(path.listKey); + } - var first = ancestries[0]; + return parts.reverse().join("."); +} - depthLoop: for (var i = 0; i < minDepth; i++) { - var shouldMatch = first[i]; +function getHelperMetadata(file) { + var globals = new Set(); + var localBindingNames = new Set(); + var dependencies = new Map(); + var exportName; + var exportPath; + var exportBindingAssignments = []; + var importPaths = []; + var importBindingsReferences = []; + (0, _traverse.default)(file, { + ImportDeclaration: function ImportDeclaration(child) { + var name = child.node.source.value; - for (var _iterator2 = ancestries, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + if (!_helpers.default[name]) { + throw child.buildCodeFrameError("Unknown helper ".concat(name)); + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + if (child.get("specifiers").length !== 1 || !child.get("specifiers.0").isImportDefaultSpecifier()) { + throw child.buildCodeFrameError("Helpers can only import a default value"); } - var ancestry = _ref2; + var bindingIdentifier = child.node.specifiers[0].local; + dependencies.set(bindingIdentifier, name); + importPaths.push(makePath(child)); + }, + ExportDefaultDeclaration: function ExportDefaultDeclaration(child) { + var decl = child.get("declaration"); + + if (decl.isFunctionDeclaration()) { + if (!decl.node.id) { + throw decl.buildCodeFrameError("Helpers should give names to their exported func declaration"); + } - if (ancestry[i] !== shouldMatch) { - break depthLoop; + exportName = decl.node.id.name; } + + exportPath = makePath(child); + }, + ExportAllDeclaration: function ExportAllDeclaration(child) { + throw child.buildCodeFrameError("Helpers can only export default"); + }, + ExportNamedDeclaration: function ExportNamedDeclaration(child) { + throw child.buildCodeFrameError("Helpers can only export default"); + }, + Statement: function Statement(child) { + if (child.isModuleDeclaration()) return; + child.skip(); } + }); + (0, _traverse.default)(file, { + Program: function Program(path) { + var bindings = path.scope.getAllBindings(); + Object.keys(bindings).forEach(function (name) { + if (name === exportName) return; + if (dependencies.has(bindings[name].identifier)) return; + localBindingNames.add(name); + }); + }, + ReferencedIdentifier: function ReferencedIdentifier(child) { + var name = child.node.name; + var binding = child.scope.getBinding(name, true); - lastCommonIndex = i; - lastCommon = shouldMatch; - } + if (!binding) { + globals.add(name); + } else if (dependencies.has(binding.identifier)) { + importBindingsReferences.push(makePath(child)); + } + }, + AssignmentExpression: function AssignmentExpression(child) { + var left = child.get("left"); + if (!(exportName in left.getBindingIdentifiers())) return; - if (lastCommon) { - if (filter) { - return filter(lastCommon, lastCommonIndex, ancestries); - } else { - return lastCommon; + if (!left.isIdentifier()) { + throw left.buildCodeFrameError("Only simple assignments to exports are allowed in helpers"); + } + + var binding = child.scope.getBinding(exportName); + + if (binding && binding.scope.path.isProgram()) { + exportBindingAssignments.push(makePath(child)); + } } - } else { - throw new Error("Couldn't find intersection"); - } + }); + if (!exportPath) throw new Error("Helpers must default-export something."); + exportBindingAssignments.reverse(); + return { + globals: Array.from(globals), + localBindingNames: Array.from(localBindingNames), + dependencies: dependencies, + exportBindingAssignments: exportBindingAssignments, + exportPath: exportPath, + exportName: exportName, + importBindingsReferences: importBindingsReferences, + importPaths: importPaths + }; } -function getAncestry() { - var path = this; - var paths = []; - do { - paths.push(path); - } while (path = path.parentPath); - return paths; -} +function permuteHelperAST(file, metadata, id, localBindings, getDependency) { + if (localBindings && !id) { + throw new Error("Unexpected local bindings for module-based helpers."); + } -function isAncestor(maybeDescendant) { - return maybeDescendant.isDescendant(this); -} + if (!id) return; + var localBindingNames = metadata.localBindingNames, + dependencies = metadata.dependencies, + exportBindingAssignments = metadata.exportBindingAssignments, + exportPath = metadata.exportPath, + exportName = metadata.exportName, + importBindingsReferences = metadata.importBindingsReferences, + importPaths = metadata.importPaths; + var dependenciesRefs = {}; + dependencies.forEach(function (name, id) { + dependenciesRefs[id.name] = typeof getDependency === "function" && getDependency(name) || id; + }); + var toRename = {}; + var bindings = new Set(localBindings || []); + localBindingNames.forEach(function (name) { + var newName = name; -function isDescendant(maybeAncestor) { - return !!this.findParent(function (parent) { - return parent === maybeAncestor; + while (bindings.has(newName)) { + newName = "_" + newName; + } + + if (newName !== name) toRename[name] = newName; }); -} -function inType() { - var path = this; - while (path) { - for (var _iterator3 = arguments, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + if (id.type === "Identifier" && exportName !== id.name) { + toRename[exportName] = id.name; + } - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; + (0, _traverse.default)(file, { + Program: function Program(path) { + var exp = path.get(exportPath); + var imps = importPaths.map(function (p) { + return path.get(p); + }); + var impsBindingRefs = importBindingsReferences.map(function (p) { + return path.get(p); + }); + var decl = exp.get("declaration"); + + if (id.type === "Identifier") { + if (decl.isFunctionDeclaration()) { + exp.replaceWith(decl); + } else { + exp.replaceWith(t.variableDeclaration("var", [t.variableDeclarator(id, decl.node)])); + } + } else if (id.type === "MemberExpression") { + if (decl.isFunctionDeclaration()) { + exportBindingAssignments.forEach(function (assignPath) { + var assign = path.get(assignPath); + assign.replaceWith(t.assignmentExpression("=", id, assign.node)); + }); + exp.replaceWith(decl); + path.pushContainer("body", t.expressionStatement(t.assignmentExpression("=", id, t.identifier(exportName)))); + } else { + exp.replaceWith(t.expressionStatement(t.assignmentExpression("=", id, decl.node))); + } } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; + throw new Error("Unexpected helper format."); } - var type = _ref3; + Object.keys(toRename).forEach(function (name) { + path.scope.rename(name, toRename[name]); + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (path.node.type === type) return true; - } - path = path.parentPath; - } + try { + for (var _iterator = imps[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _path = _step.value; - return false; -} + _path.remove(); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } -function inShadow(key) { - var parentFn = this.isFunction() ? this : this.findParent(function (p) { - return p.isFunction(); - }); - if (!parentFn) return; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = impsBindingRefs[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _path2 = _step2.value; + var node = t.cloneNode(dependenciesRefs[_path2.node.name]); - if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) { - var shadow = parentFn.node.shadow; + _path2.replaceWith(node); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } - if (shadow && (!key || shadow[key] !== false)) { - return parentFn; + path.stop(); } - } else if (parentFn.isArrowFunctionExpression()) { - return parentFn; - } - - return null; + }); } -},{"./index":125,"babel-runtime/core-js/get-iterator":95,"babel-types":151}],120:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.shareCommentsWithSiblings = shareCommentsWithSiblings; -exports.addComment = addComment; -exports.addComments = addComments; -function shareCommentsWithSiblings() { - if (typeof this.key === "string") return; +var helperData = Object.create(null); - var node = this.node; - if (!node) return; +function loadHelper(name) { + if (!helperData[name]) { + var helper = _helpers.default[name]; - var trailing = node.trailingComments; - var leading = node.leadingComments; - if (!trailing && !leading) return; + if (!helper) { + throw Object.assign(new ReferenceError("Unknown helper ".concat(name)), { + code: "BABEL_HELPER_UNKNOWN", + helper: name + }); + } - var prev = this.getSibling(this.key - 1); - var next = this.getSibling(this.key + 1); + var fn = function fn() { + return t.file(helper.ast()); + }; - if (!prev.node) prev = next; - if (!next.node) next = prev; + var metadata = getHelperMetadata(fn()); + helperData[name] = { + build: function build(getDependency, id, localBindings) { + var file = fn(); + permuteHelperAST(file, metadata, id, localBindings, getDependency); + return { + nodes: file.program.body, + globals: metadata.globals + }; + }, + minVersion: function minVersion() { + return helper.minVersion; + }, + dependencies: metadata.dependencies + }; + } - prev.addComments("trailing", leading); - next.addComments("leading", trailing); + return helperData[name]; } -function addComment(type, content, line) { - this.addComments(type, [{ - type: line ? "CommentLine" : "CommentBlock", - value: content - }]); +function get(name, getDependency, id, localBindings) { + return loadHelper(name).build(getDependency, id, localBindings); } -function addComments(type, comments) { - if (!comments) return; - - var node = this.node; - if (!node) return; +function minVersion(name) { + return loadHelper(name).minVersion(); +} - var key = type + "Comments"; +function getDependencies(name) { + return Array.from(loadHelper(name).dependencies.values()); +} - if (node[key]) { - node[key] = node[key].concat(comments); - } else { - node[key] = comments; - } +function ensure(name) { + loadHelper(name); } -},{}],121:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; +var list = Object.keys(_helpers.default).map(function (name) { + return name.replace(/^_/, ""); +}).filter(function (name) { + return name !== "__esModule"; +}); +exports.list = list; +var _default = get; +exports.default = _default; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +},{"./helpers":86,"@babel/traverse":176,"@babel/types":242}],88:[function(require,module,exports){ +"use strict"; -var _getIterator3 = _interopRequireDefault(_getIterator2); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -exports.call = call; -exports._call = _call; -exports.isBlacklisted = isBlacklisted; -exports.visit = visit; -exports.skip = skip; -exports.skipKey = skipKey; -exports.stop = stop; -exports.setScope = setScope; -exports.setContext = setContext; -exports.resync = resync; -exports._resyncParent = _resyncParent; -exports._resyncKey = _resyncKey; -exports._resyncList = _resyncList; -exports._resyncRemoved = _resyncRemoved; -exports.popContext = popContext; -exports.pushContext = pushContext; -exports.setup = setup; -exports.setKey = setKey; -exports.requeue = requeue; -exports._getQueueContexts = _getQueueContexts; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -var _index = require("../index"); +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -var _index2 = _interopRequireDefault(_index); +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.shouldHighlight = shouldHighlight; +exports.getChalk = getChalk; +exports.default = highlight; -function call(key) { - var opts = this.opts; +function _jsTokens() { + var data = _interopRequireWildcard(require("js-tokens")); - this.debug(function () { - return key; - }); + _jsTokens = function _jsTokens() { + return data; + }; - if (this.node) { - if (this._call(opts[key])) return true; - } + return data; +} - if (this.node) { - return this._call(opts[this.node.type] && opts[this.node.type][key]); - } +function _esutils() { + var data = _interopRequireDefault(require("esutils")); - return false; -} + _esutils = function _esutils() { + return data; + }; -function _call(fns) { - if (!fns) return false; + return data; +} - for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +function _chalk() { + var data = _interopRequireDefault(require("chalk")); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + _chalk = function _chalk() { + return data; + }; - var fn = _ref; + return data; +} - if (!fn) continue; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - var node = this.node; - if (!node) return true; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; - var ret = fn.call(this.state, this, this.state); - if (ret) throw new Error("Unexpected return value from visitor method " + fn); + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; - if (this.node !== node) return true; + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } - if (this.shouldStop || this.shouldSkip || this.removed) return true; + newObj.default = obj; + return newObj; } - - return false; } -function isBlacklisted() { - var blacklist = this.opts.blacklist; - return blacklist && blacklist.indexOf(this.node.type) > -1; +function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsx_tag: chalk.yellow, + punctuator: chalk.yellow, + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold + }; } -function visit() { - if (!this.node) { - return false; - } +var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; +var JSX_TAG = /^[a-z][\w-]*$/i; +var BRACKET = /^[()[\]{}]$/; - if (this.isBlacklisted()) { - return false; +function getTokenType(match) { + var _match$slice = match.slice(-2), + _match$slice2 = _slicedToArray(_match$slice, 2), + offset = _match$slice2[0], + text = _match$slice2[1]; + + var token = (0, _jsTokens().matchToToken)(match); + + if (token.type === "name") { + if (_esutils().default.keyword.isReservedWordES6(token.value)) { + return "keyword"; + } + + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " 1 && arguments[1] !== undefined ? arguments[1] : {}; - target = path.scope; - path = path.parentPath; - } + if (shouldHighlight(options)) { + var chalk = getChalk(options); + var defs = getDefs(chalk); + return highlightTokens(defs, code); + } else { + return code; } - - this.scope = this.getScope(target); - if (this.scope) this.scope.init(); } -function setContext(context) { - this.shouldSkip = false; - this.shouldStop = false; - this.removed = false; - this.skipKeys = {}; +},{"chalk":296,"esutils":836,"js-tokens":843}],89:[function(require,module,exports){ +'use strict'; - if (context) { - this.context = context; - this.state = context.state; - this.opts = context.opts; - } +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - this.setScope(); +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } - return this; -} +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } -function resync() { - if (this.removed) return; +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } - this._resyncParent(); - this._resyncList(); - this._resyncKey(); -} +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } -function _resyncParent() { - if (this.parentPath) { - this.parent = this.parentPath.node; - } -} +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -function _resyncKey() { - if (!this.container) return; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - if (this.node === this.container[this.key]) return; +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - if (Array.isArray(this.container)) { - for (var i = 0; i < this.container.length; i++) { - if (this.container[i] === this.node) { - return this.setKey(i); - } - } - } else { - for (var key in this.container) { - if (this.container[key] === this.node) { - return this.setKey(key); - } - } - } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - this.key = null; -} +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } -function _resyncList() { - if (!this.parent || !this.inList) return; +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - var newContainer = this.parent[this.listKey]; - if (this.container === newContainer) return; +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - this.container = newContainer || null; -} +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _resyncRemoved() { - if (this.key == null || !this.container || this.container[this.key] !== this.node) { - this._markRemoved(); - } -} +function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } -function popContext() { - this.contexts.pop(); - this.setContext(this.contexts[this.contexts.length - 1]); -} +function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } -function pushContext(context) { - this.contexts.push(context); - this.setContext(context); -} +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -function setup(parentPath, container, listKey, key) { - this.inList = !!listKey; - this.listKey = listKey; - this.parentKey = listKey || key; - this.container = container; +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - this.parentPath = parentPath || this.parentPath; - this.setKey(key); -} +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function setKey(key) { - this.key = key; - this.node = this.container[this.key]; - this.type = this.node && this.node.type; -} +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function requeue() { - var pathToQueue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this; +Object.defineProperty(exports, '__esModule', { + value: true +}); +var beforeExpr = true; +var startsExpr = true; +var isLoop = true; +var isAssign = true; +var prefix = true; +var postfix = true; - if (pathToQueue.removed) return; +var TokenType = function TokenType(label) { + var conf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var contexts = this.contexts; + _classCallCheck(this, TokenType); - for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.rightAssociative = !!conf.rightAssociative; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop != null ? conf.binop : null; + this.updateContext = null; +}; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +var keywords = new Map(); - var context = _ref2; +function createKeyword(name) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + options.keyword = name; + var token = new TokenType(name, options); + keywords.set(name, token); + return token; +} - context.maybeQueue(pathToQueue); - } +function createBinop(name, binop) { + return new TokenType(name, { + beforeExpr: beforeExpr, + binop: binop + }); } -function _getQueueContexts() { - var path = this; - var contexts = this.contexts; - while (!contexts.length) { - path = path.parentPath; - contexts = path.contexts; - } - return contexts; +var types = { + num: new TokenType("num", { + startsExpr: startsExpr + }), + bigint: new TokenType("bigint", { + startsExpr: startsExpr + }), + regexp: new TokenType("regexp", { + startsExpr: startsExpr + }), + string: new TokenType("string", { + startsExpr: startsExpr + }), + name: new TokenType("name", { + startsExpr: startsExpr + }), + eof: new TokenType("eof"), + bracketL: new TokenType("[", { + beforeExpr: beforeExpr, + startsExpr: startsExpr + }), + bracketR: new TokenType("]"), + braceL: new TokenType("{", { + beforeExpr: beforeExpr, + startsExpr: startsExpr + }), + braceBarL: new TokenType("{|", { + beforeExpr: beforeExpr, + startsExpr: startsExpr + }), + braceR: new TokenType("}"), + braceBarR: new TokenType("|}"), + parenL: new TokenType("(", { + beforeExpr: beforeExpr, + startsExpr: startsExpr + }), + parenR: new TokenType(")"), + comma: new TokenType(",", { + beforeExpr: beforeExpr + }), + semi: new TokenType(";", { + beforeExpr: beforeExpr + }), + colon: new TokenType(":", { + beforeExpr: beforeExpr + }), + doubleColon: new TokenType("::", { + beforeExpr: beforeExpr + }), + dot: new TokenType("."), + question: new TokenType("?", { + beforeExpr: beforeExpr + }), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", { + beforeExpr: beforeExpr + }), + template: new TokenType("template"), + ellipsis: new TokenType("...", { + beforeExpr: beforeExpr + }), + backQuote: new TokenType("`", { + startsExpr: startsExpr + }), + dollarBraceL: new TokenType("${", { + beforeExpr: beforeExpr, + startsExpr: startsExpr + }), + at: new TokenType("@"), + hash: new TokenType("#", { + startsExpr: startsExpr + }), + interpreterDirective: new TokenType("#!..."), + eq: new TokenType("=", { + beforeExpr: beforeExpr, + isAssign: isAssign + }), + assign: new TokenType("_=", { + beforeExpr: beforeExpr, + isAssign: isAssign + }), + incDec: new TokenType("++/--", { + prefix: prefix, + postfix: postfix, + startsExpr: startsExpr + }), + bang: new TokenType("!", { + beforeExpr: beforeExpr, + prefix: prefix, + startsExpr: startsExpr + }), + tilde: new TokenType("~", { + beforeExpr: beforeExpr, + prefix: prefix, + startsExpr: startsExpr + }), + pipeline: createBinop("|>", 0), + nullishCoalescing: createBinop("??", 1), + logicalOR: createBinop("||", 2), + logicalAND: createBinop("&&", 3), + bitwiseOR: createBinop("|", 4), + bitwiseXOR: createBinop("^", 5), + bitwiseAND: createBinop("&", 6), + equality: createBinop("==/!=/===/!==", 7), + relational: createBinop("/<=/>=", 8), + bitShift: createBinop("<>/>>>", 9), + plusMin: new TokenType("+/-", { + beforeExpr: beforeExpr, + binop: 10, + prefix: prefix, + startsExpr: startsExpr + }), + modulo: new TokenType("%", { + beforeExpr: beforeExpr, + binop: 11, + startsExpr: startsExpr + }), + star: createBinop("*", 11), + slash: createBinop("/", 11), + exponent: new TokenType("**", { + beforeExpr: beforeExpr, + binop: 12, + rightAssociative: true + }), + _break: createKeyword("break"), + _case: createKeyword("case", { + beforeExpr: beforeExpr + }), + _catch: createKeyword("catch"), + _continue: createKeyword("continue"), + _debugger: createKeyword("debugger"), + _default: createKeyword("default", { + beforeExpr: beforeExpr + }), + _do: createKeyword("do", { + isLoop: isLoop, + beforeExpr: beforeExpr + }), + _else: createKeyword("else", { + beforeExpr: beforeExpr + }), + _finally: createKeyword("finally"), + _for: createKeyword("for", { + isLoop: isLoop + }), + _function: createKeyword("function", { + startsExpr: startsExpr + }), + _if: createKeyword("if"), + _return: createKeyword("return", { + beforeExpr: beforeExpr + }), + _switch: createKeyword("switch"), + _throw: createKeyword("throw", { + beforeExpr: beforeExpr, + prefix: prefix, + startsExpr: startsExpr + }), + _try: createKeyword("try"), + _var: createKeyword("var"), + _const: createKeyword("const"), + _while: createKeyword("while", { + isLoop: isLoop + }), + _with: createKeyword("with"), + _new: createKeyword("new", { + beforeExpr: beforeExpr, + startsExpr: startsExpr + }), + _this: createKeyword("this", { + startsExpr: startsExpr + }), + _super: createKeyword("super", { + startsExpr: startsExpr + }), + _class: createKeyword("class", { + startsExpr: startsExpr + }), + _extends: createKeyword("extends", { + beforeExpr: beforeExpr + }), + _export: createKeyword("export"), + _import: createKeyword("import", { + startsExpr: startsExpr + }), + _null: createKeyword("null", { + startsExpr: startsExpr + }), + _true: createKeyword("true", { + startsExpr: startsExpr + }), + _false: createKeyword("false", { + startsExpr: startsExpr + }), + _in: createKeyword("in", { + beforeExpr: beforeExpr, + binop: 8 + }), + _instanceof: createKeyword("instanceof", { + beforeExpr: beforeExpr, + binop: 8 + }), + _typeof: createKeyword("typeof", { + beforeExpr: beforeExpr, + prefix: prefix, + startsExpr: startsExpr + }), + _void: createKeyword("void", { + beforeExpr: beforeExpr, + prefix: prefix, + startsExpr: startsExpr + }), + _delete: createKeyword("delete", { + beforeExpr: beforeExpr, + prefix: prefix, + startsExpr: startsExpr + }) +}; +var SCOPE_OTHER = 0, + SCOPE_PROGRAM = 1, + SCOPE_FUNCTION = 2, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128, + SCOPE_CLASS = 256, + SCOPE_TS_MODULE = 512, + SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE; + +function functionFlags(isAsync, isGenerator) { + return SCOPE_FUNCTION | (isAsync ? SCOPE_ASYNC : 0) | (isGenerator ? SCOPE_GENERATOR : 0); +} + +var BIND_KIND_VALUE = 1, + BIND_KIND_TYPE = 2, + BIND_SCOPE_VAR = 4, + BIND_SCOPE_LEXICAL = 8, + BIND_SCOPE_FUNCTION = 16, + BIND_FLAGS_NONE = 64, + BIND_FLAGS_CLASS = 128, + BIND_FLAGS_TS_ENUM = 256, + BIND_FLAGS_TS_CONST_ENUM = 512, + BIND_FLAGS_TS_EXPORT_ONLY = 1024; +var BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS, + BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0, + BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0, + BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0, + BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS, + BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0, + BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM, + BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY, + BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE, + BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE, + BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM, + BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY; + +function isSimpleProperty(node) { + return node != null && node.type === "Property" && node.kind === "init" && node.method === false; } -},{"../index":118,"babel-runtime/core-js/get-iterator":95}],122:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.toComputedKey = toComputedKey; -exports.ensureBlock = ensureBlock; -exports.arrowFunctionToShadowed = arrowFunctionToShadowed; +var estree = function estree(superClass) { + return ( + /*#__PURE__*/ + function (_superClass) { + _inherits(_class, _superClass); -var _babelTypes = require("babel-types"); + function _class() { + _classCallCheck(this, _class); -var t = _interopRequireWildcard(_babelTypes); + return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments)); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + _createClass(_class, [{ + key: "estreeParseRegExpLiteral", + value: function estreeParseRegExpLiteral(_ref) { + var pattern = _ref.pattern, + flags = _ref.flags; + var regex = null; -function toComputedKey() { - var node = this.node; + try { + regex = new RegExp(pattern, flags); + } catch (e) {} - var key = void 0; - if (this.isMemberExpression()) { - key = node.property; - } else if (this.isProperty() || this.isMethod()) { - key = node.key; - } else { - throw new ReferenceError("todo"); - } + var node = this.estreeParseLiteral(regex); + node.regex = { + pattern: pattern, + flags: flags + }; + return node; + } + }, { + key: "estreeParseLiteral", + value: function estreeParseLiteral(value) { + return this.parseLiteral(value, "Literal"); + } + }, { + key: "directiveToStmt", + value: function directiveToStmt(directive) { + var directiveLiteral = directive.value; + var stmt = this.startNodeAt(directive.start, directive.loc.start); + var expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start); + expression.value = directiveLiteral.value; + expression.raw = directiveLiteral.extra.raw; + stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end); + stmt.directive = directiveLiteral.extra.raw.slice(1, -1); + return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end); + } + }, { + key: "initFunction", + value: function initFunction(node, isAsync) { + _get(_getPrototypeOf(_class.prototype), "initFunction", this).call(this, node, isAsync); - if (!node.computed) { - if (t.isIdentifier(key)) key = t.stringLiteral(key.name); - } + node.expression = false; + } + }, { + key: "checkDeclaration", + value: function checkDeclaration(node) { + if (isSimpleProperty(node)) { + this.checkDeclaration(node.value); + } else { + _get(_getPrototypeOf(_class.prototype), "checkDeclaration", this).call(this, node); + } + } + }, { + key: "checkGetterSetterParams", + value: function checkGetterSetterParams(method) { + var prop = method; + var paramCount = prop.kind === "get" ? 0 : 1; + var start = prop.start; + + if (prop.value.params.length !== paramCount) { + if (prop.kind === "get") { + this.raise(start, "getter must not have any formal parameters"); + } else { + this.raise(start, "setter must have exactly one formal parameter"); + } + } else if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { + this.raise(start, "setter function argument must not be a rest parameter"); + } + } + }, { + key: "checkLVal", + value: function checkLVal(expr) { + var _this = this; - return key; -} + var bindingType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : BIND_NONE; + var checkClashes = arguments.length > 2 ? arguments[2] : undefined; + var contextDescription = arguments.length > 3 ? arguments[3] : undefined; + var disallowLetBinding = arguments.length > 4 ? arguments[4] : undefined; -function ensureBlock() { - return t.ensureBlock(this.node); -} + switch (expr.type) { + case "ObjectPattern": + expr.properties.forEach(function (prop) { + _this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding); + }); + break; -function arrowFunctionToShadowed() { - if (!this.isArrowFunctionExpression()) return; + default: + _get(_getPrototypeOf(_class.prototype), "checkLVal", this).call(this, expr, bindingType, checkClashes, contextDescription, disallowLetBinding); - this.ensureBlock(); + } + } + }, { + key: "checkDuplicatedProto", + value: function checkDuplicatedProto(prop, protoRef) { + if (prop.type === "SpreadElement" || prop.computed || prop.method || prop.shorthand) { + return; + } - var node = this.node; + var key = prop.key; + var name = key.type === "Identifier" ? key.name : String(key.value); - node.expression = false; - node.type = "FunctionExpression"; - node.shadow = node.shadow || true; -} -},{"babel-types":151}],123:[function(require,module,exports){ -(function (global){ -"use strict"; + if (name === "__proto__" && prop.kind === "init") { + if (protoRef.used && !protoRef.start) { + protoRef.start = key.start; + } -exports.__esModule = true; + protoRef.used = true; + } + } + }, { + key: "isStrictBody", + value: function isStrictBody(node) { + var isBlockStatement = node.body.type === "BlockStatement"; + + if (isBlockStatement && node.body.body.length > 0) { + for (var _i = 0, _node$body$body = node.body.body; _i < _node$body$body.length; _i++) { + var directive = _node$body$body[_i]; + + if (directive.type === "ExpressionStatement" && directive.expression.type === "Literal") { + if (directive.expression.value === "use strict") return true; + } else { + break; + } + } + } -var _typeof2 = require("babel-runtime/helpers/typeof"); + return false; + } + }, { + key: "isValidDirective", + value: function isValidDirective(stmt) { + return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized); + } + }, { + key: "stmtToDirective", + value: function stmtToDirective(stmt) { + var directive = _get(_getPrototypeOf(_class.prototype), "stmtToDirective", this).call(this, stmt); + + var value = stmt.expression.value; + directive.value.value = value; + return directive; + } + }, { + key: "parseBlockBody", + value: function parseBlockBody(node, allowDirectives, topLevel, end) { + var _this2 = this; -var _typeof3 = _interopRequireDefault(_typeof2); + _get(_getPrototypeOf(_class.prototype), "parseBlockBody", this).call(this, node, allowDirectives, topLevel, end); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + var directiveStatements = node.directives.map(function (d) { + return _this2.directiveToStmt(d); + }); + node.body = directiveStatements.concat(node.body); + delete node.directives; + } + }, { + key: "pushClassMethod", + value: function pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true); + + if (method.typeParameters) { + method.value.typeParameters = method.typeParameters; + delete method.typeParameters; + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + classBody.body.push(method); + } + }, { + key: "parseExprAtom", + value: function parseExprAtom(refShorthandDefaultPos) { + switch (this.state.type) { + case types.regexp: + return this.estreeParseRegExpLiteral(this.state.value); -var _map = require("babel-runtime/core-js/map"); + case types.num: + case types.string: + return this.estreeParseLiteral(this.state.value); -var _map2 = _interopRequireDefault(_map); + case types._null: + return this.estreeParseLiteral(null); -exports.evaluateTruthy = evaluateTruthy; -exports.evaluate = evaluate; + case types._true: + return this.estreeParseLiteral(true); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case types._false: + return this.estreeParseLiteral(false); -var VALID_CALLEES = ["String", "Number", "Math"]; -var INVALID_METHODS = ["random"]; + default: + return _get(_getPrototypeOf(_class.prototype), "parseExprAtom", this).call(this, refShorthandDefaultPos); + } + } + }, { + key: "parseLiteral", + value: function parseLiteral(value, type, startPos, startLoc) { + var node = _get(_getPrototypeOf(_class.prototype), "parseLiteral", this).call(this, value, type, startPos, startLoc); + + node.raw = node.extra.raw; + delete node.extra; + return node; + } + }, { + key: "parseFunctionBody", + value: function parseFunctionBody(node, allowExpression) { + var isMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; -function evaluateTruthy() { - var res = this.evaluate(); - if (res.confident) return !!res.value; + _get(_getPrototypeOf(_class.prototype), "parseFunctionBody", this).call(this, node, allowExpression, isMethod); + + node.expression = node.body.type !== "BlockStatement"; + } + }, { + key: "parseMethod", + value: function parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type) { + var inClassScope = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; + var funcNode = this.startNode(); + funcNode.kind = node.kind; + funcNode = _get(_getPrototypeOf(_class.prototype), "parseMethod", this).call(this, funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + funcNode.type = "FunctionExpression"; + delete funcNode.kind; + node.value = funcNode; + type = type === "ClassMethod" ? "MethodDefinition" : type; + return this.finishNode(node, type); + } + }, { + key: "parseObjectMethod", + value: function parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) { + var node = _get(_getPrototypeOf(_class.prototype), "parseObjectMethod", this).call(this, prop, isGenerator, isAsync, isPattern, containsEsc); + + if (node) { + node.type = "Property"; + if (node.kind === "method") node.kind = "init"; + node.shorthand = false; + } + + return node; + } + }, { + key: "parseObjectProperty", + value: function parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos) { + var node = _get(_getPrototypeOf(_class.prototype), "parseObjectProperty", this).call(this, prop, startPos, startLoc, isPattern, refShorthandDefaultPos); + + if (node) { + node.kind = "init"; + node.type = "Property"; + } + + return node; + } + }, { + key: "toAssignable", + value: function toAssignable(node, isBinding, contextDescription) { + if (isSimpleProperty(node)) { + this.toAssignable(node.value, isBinding, contextDescription); + return node; + } + + return _get(_getPrototypeOf(_class.prototype), "toAssignable", this).call(this, node, isBinding, contextDescription); + } + }, { + key: "toAssignableObjectExpressionProp", + value: function toAssignableObjectExpressionProp(prop, isBinding, isLast) { + if (prop.kind === "get" || prop.kind === "set") { + throw this.raise(prop.key.start, "Object pattern can't contain getter or setter"); + } else if (prop.method) { + throw this.raise(prop.key.start, "Object pattern can't contain methods"); + } else { + _get(_getPrototypeOf(_class.prototype), "toAssignableObjectExpressionProp", this).call(this, prop, isBinding, isLast); + } + } + }]); + + return _class; + }(superClass) + ); +}; + +var lineBreak = /\r\n?|[\n\u2028\u2029]/; +var lineBreakG = new RegExp(lineBreak.source, "g"); + +function isNewLine(code) { + switch (code) { + case 10: + case 13: + case 8232: + case 8233: + return true; + + default: + return false; + } } -function evaluate() { - var confident = true; - var deoptPath = void 0; - var seen = new _map2.default(); +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + +function isWhitespace(code) { + switch (code) { + case 0x0009: + case 0x000b: + case 0x000c: + case 32: + case 160: + case 5760: + case 0x2000: + case 0x2001: + case 0x2002: + case 0x2003: + case 0x2004: + case 0x2005: + case 0x2006: + case 0x2007: + case 0x2008: + case 0x2009: + case 0x200a: + case 0x202f: + case 0x205f: + case 0x3000: + case 0xfeff: + return true; - function deopt(path) { - if (!confident) return; - deoptPath = path; - confident = false; + default: + return false; } +} - var value = evaluate(this); - if (!confident) value = undefined; - return { - confident: confident, - deopt: deoptPath, - value: value - }; +var TokContext = function TokContext(token, isExpr, preserveSpace, override) { + _classCallCheck(this, TokContext); - function evaluate(path) { - var node = path.node; + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; +}; +var types$1 = { + braceStatement: new TokContext("{", false), + braceExpression: new TokContext("{", true), + templateQuasi: new TokContext("${", false), + parenStatement: new TokContext("(", false), + parenExpression: new TokContext("(", true), + template: new TokContext("`", true, true, function (p) { + return p.readTmplToken(); + }), + functionExpression: new TokContext("function", true), + functionStatement: new TokContext("function", false) +}; - if (seen.has(node)) { - var existing = seen.get(node); - if (existing.resolved) { - return existing.value; - } else { - deopt(path); - return; - } - } else { - var item = { resolved: false }; - seen.set(node, item); +types.parenR.updateContext = types.braceR.updateContext = function () { + if (this.state.context.length === 1) { + this.state.exprAllowed = true; + return; + } - var val = _evaluate(path); - if (confident) { - item.resolved = true; - item.value = val; - } - return val; + var out = this.state.context.pop(); + + if (out === types$1.braceStatement && this.curContext().token === "function") { + out = this.state.context.pop(); + } + + this.state.exprAllowed = !out.isExpr; +}; + +types.name.updateContext = function (prevType) { + var allowed = false; + + if (prevType !== types.dot) { + if (this.state.value === "of" && !this.state.exprAllowed || this.state.value === "yield" && this.scope.inGenerator) { + allowed = true; } } - function _evaluate(path) { - if (!confident) return; + this.state.exprAllowed = allowed; - var node = path.node; + if (this.state.isIterator) { + this.state.isIterator = false; + } +}; +types.braceL.updateContext = function (prevType) { + this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression); + this.state.exprAllowed = true; +}; - if (path.isSequenceExpression()) { - var exprs = path.get("expressions"); - return evaluate(exprs[exprs.length - 1]); - } +types.dollarBraceL.updateContext = function () { + this.state.context.push(types$1.templateQuasi); + this.state.exprAllowed = true; +}; - if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) { - return node.value; - } +types.parenL.updateContext = function (prevType) { + var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; + this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression); + this.state.exprAllowed = true; +}; - if (path.isNullLiteral()) { - return null; - } +types.incDec.updateContext = function () {}; - if (path.isTemplateLiteral()) { - var str = ""; +types._function.updateContext = types._class.updateContext = function (prevType) { + if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) { + this.state.context.push(types$1.functionExpression); + } else { + this.state.context.push(types$1.functionStatement); + } - var i = 0; - var _exprs = path.get("expressions"); + this.state.exprAllowed = false; +}; - for (var _iterator = node.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +types.backQuote.updateContext = function () { + if (this.curContext() === types$1.template) { + this.state.context.pop(); + } else { + this.state.context.push(types$1.template); + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + this.state.exprAllowed = false; +}; - var elem = _ref; +var reservedWords = { + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +var reservedWordsStrictSet = new Set(reservedWords.strict); +var reservedWordsStrictBindSet = new Set(reservedWords.strictBind); - if (!confident) break; +var isReservedWord = function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +}; - str += elem.value.cooked; +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} - var expr = _exprs[i++]; - if (expr) str += String(evaluate(expr)); - } +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} - if (!confident) return; - return str; - } +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} - if (path.isConditionalExpression()) { - var testResult = evaluate(path.get("test")); - if (!confident) return; - if (testResult) { - return evaluate(path.get("consequent")); - } else { - return evaluate(path.get("alternate")); - } - } +function isKeyword(word) { + return keywords.has(word); +} - if (path.isExpressionWrapper()) { - return evaluate(path.get("expression")); - } +var keywordRelationalOperator = /^in(stanceof)?$/; +var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7C6\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB67\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; +var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F"; +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 477, 28, 11, 0, 9, 21, 155, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 12, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 0, 33, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 0, 161, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 270, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 754, 9486, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541]; +var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 525, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 232, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 792487, 239]; - if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) { - var property = path.get("property"); - var object = path.get("object"); +function isInAstralSet(code, set) { + var pos = 0x10000; - if (object.isLiteral() && property.isIdentifier()) { - var _value = object.node.value; - var type = typeof _value === "undefined" ? "undefined" : (0, _typeof3.default)(_value); - if (type === "number" || type === "string") { - return _value[property.node.name]; - } - } - } + for (var i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + + return false; +} - if (path.isReferencedIdentifier()) { - var binding = path.scope.getBinding(node.name); +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; - if (binding && binding.constantViolations.length > 0) { - return deopt(binding.path); - } + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } - if (binding && path.node.start < binding.path.node.end) { - return deopt(binding.path); - } + return isInAstralSet(code, astralIdentifierStartCodes); +} - if (binding && binding.hasValue) { - return binding.value; - } else { - if (node.name === "undefined") { - return binding ? deopt(binding.path) : undefined; - } else if (node.name === "Infinity") { - return binding ? deopt(binding.path) : Infinity; - } else if (node.name === "NaN") { - return binding ? deopt(binding.path) : NaN; - } +function isIteratorStart(current, next) { + return current === 64 && next === 64; +} - var resolved = path.resolve(); - if (resolved === path) { - return deopt(path); - } else { - return evaluate(resolved); - } - } - } +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; - if (path.isUnaryExpression({ prefix: true })) { - if (node.operator === "void") { - return undefined; - } + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } - var argument = path.get("argument"); - if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) { - return "function"; - } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} - var arg = evaluate(argument); - if (!confident) return; - switch (node.operator) { - case "!": - return !arg; - case "+": - return +arg; - case "-": - return -arg; - case "~": - return ~arg; - case "typeof": - return typeof arg === "undefined" ? "undefined" : (0, _typeof3.default)(arg); - } - } +var reservedTypes = ["any", "bool", "boolean", "empty", "false", "mixed", "null", "number", "static", "string", "true", "typeof", "void", "interface", "extends", "_"]; - if (path.isArrayExpression()) { - var arr = []; - var elems = path.get("elements"); - for (var _iterator2 = elems, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; +function isEsModuleType(bodyElement) { + return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); +} - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +function hasTypeImportKind(node) { + return node.importKind === "type" || node.importKind === "typeof"; +} - var _elem = _ref2; +function isMaybeDefaultImport(state) { + return (state.type === types.name || !!state.type.keyword) && state.value !== "from"; +} - _elem = _elem.evaluate(); +var exportSuggestions = { + const: "declare export var", + let: "declare export var", + type: "export type", + interface: "export interface" +}; - if (_elem.confident) { - arr.push(_elem.value); - } else { - return deopt(_elem); - } +function partition(list, test) { + var list1 = []; + var list2 = []; + + for (var i = 0; i < list.length; i++) { + (test(list[i], i, list) ? list1 : list2).push(list[i]); + } + + return [list1, list2]; +} + +var FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; + +var flow = function flow(superClass) { + return ( + /*#__PURE__*/ + function (_superClass2) { + _inherits(_class2, _superClass2); + + function _class2(options, input) { + var _this3; + + _classCallCheck(this, _class2); + + _this3 = _possibleConstructorReturn(this, _getPrototypeOf(_class2).call(this, options, input)); + _this3.flowPragma = undefined; + return _this3; } - return arr; - } - if (path.isObjectExpression()) { - var obj = {}; - var props = path.get("properties"); - for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + _createClass(_class2, [{ + key: "shouldParseTypes", + value: function shouldParseTypes() { + return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; + } + }, { + key: "shouldParseEnums", + value: function shouldParseEnums() { + return !!this.getPluginOption("flow", "enums"); + } + }, { + key: "finishToken", + value: function finishToken(type, val) { + if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) { + if (this.flowPragma === undefined) { + this.flowPragma = null; + } + } - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; + return _get(_getPrototypeOf(_class2.prototype), "finishToken", this).call(this, type, val); } + }, { + key: "addComment", + value: function addComment(comment) { + if (this.flowPragma === undefined) { + var matches = FLOW_PRAGMA_REGEX.exec(comment.value); + if (!matches) ;else if (matches[1] === "flow") { + this.flowPragma = "flow"; + } else if (matches[1] === "noflow") { + this.flowPragma = "noflow"; + } else { + throw new Error("Unexpected flow pragma"); + } + } - var prop = _ref3; + return _get(_getPrototypeOf(_class2.prototype), "addComment", this).call(this, comment); + } + }, { + key: "flowParseTypeInitialiser", + value: function flowParseTypeInitialiser(tok) { + var oldInType = this.state.inType; + this.state.inType = true; + this.expect(tok || types.colon); + var type = this.flowParseType(); + this.state.inType = oldInType; + return type; + } + }, { + key: "flowParsePredicate", + value: function flowParsePredicate() { + var node = this.startNode(); + var moduloLoc = this.state.startLoc; + var moduloPos = this.state.start; + this.expect(types.modulo); + var checksLoc = this.state.startLoc; + this.expectContextual("checks"); + + if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) { + this.raise(moduloPos, "Spaces between ´%´ and ´checks´ are not allowed here."); + } - if (prop.isObjectMethod() || prop.isSpreadProperty()) { - return deopt(prop); + if (this.eat(types.parenL)) { + node.value = this.parseExpression(); + this.expect(types.parenR); + return this.finishNode(node, "DeclaredPredicate"); + } else { + return this.finishNode(node, "InferredPredicate"); + } } - var keyPath = prop.get("key"); - var key = keyPath; - if (prop.node.computed) { - key = key.evaluate(); - if (!key.confident) { - return deopt(keyPath); + }, { + key: "flowParseTypeAndPredicateInitialiser", + value: function flowParseTypeAndPredicateInitialiser() { + var oldInType = this.state.inType; + this.state.inType = true; + this.expect(types.colon); + var type = null; + var predicate = null; + + if (this.match(types.modulo)) { + this.state.inType = oldInType; + predicate = this.flowParsePredicate(); + } else { + type = this.flowParseType(); + this.state.inType = oldInType; + + if (this.match(types.modulo)) { + predicate = this.flowParsePredicate(); + } } - key = key.value; - } else if (key.isIdentifier()) { - key = key.node.name; - } else { - key = key.node.value; + + return [type, predicate]; } - var valuePath = prop.get("value"); - var _value2 = valuePath.evaluate(); - if (!_value2.confident) { - return deopt(valuePath); + }, { + key: "flowParseDeclareClass", + value: function flowParseDeclareClass(node) { + this.next(); + this.flowParseInterfaceish(node, true); + return this.finishNode(node, "DeclareClass"); } - _value2 = _value2.value; - obj[key] = _value2; - } - return obj; - } + }, { + key: "flowParseDeclareFunction", + value: function flowParseDeclareFunction(node) { + this.next(); + var id = node.id = this.parseIdentifier(); + var typeNode = this.startNode(); + var typeContainer = this.startNode(); + + if (this.isRelational("<")) { + typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + typeNode.typeParameters = null; + } + + this.expect(types.parenL); + var tmp = this.flowParseFunctionTypeParams(); + typeNode.params = tmp.params; + typeNode.rest = tmp.rest; + this.expect(types.parenR); - if (path.isLogicalExpression()) { - var wasConfident = confident; - var left = evaluate(path.get("left")); - var leftConfident = confident; - confident = wasConfident; - var right = evaluate(path.get("right")); - var rightConfident = confident; - confident = leftConfident && rightConfident; + var _this$flowParseTypeAn = this.flowParseTypeAndPredicateInitialiser(); - switch (node.operator) { - case "||": - if (left && leftConfident) { - confident = true; - return left; + var _this$flowParseTypeAn2 = _slicedToArray(_this$flowParseTypeAn, 2); + + typeNode.returnType = _this$flowParseTypeAn2[0]; + node.predicate = _this$flowParseTypeAn2[1]; + typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); + id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); + this.resetEndLocation(id); + this.semicolon(); + return this.finishNode(node, "DeclareFunction"); + } + }, { + key: "flowParseDeclare", + value: function flowParseDeclare(node, insideModule) { + if (this.match(types._class)) { + return this.flowParseDeclareClass(node); + } else if (this.match(types._function)) { + return this.flowParseDeclareFunction(node); + } else if (this.match(types._var)) { + return this.flowParseDeclareVariable(node); + } else if (this.eatContextual("module")) { + if (this.match(types.dot)) { + return this.flowParseDeclareModuleExports(node); + } else { + if (insideModule) { + this.raise(this.state.lastTokStart, "`declare module` cannot be used inside another `declare module`"); + } + + return this.flowParseDeclareModule(node); + } + } else if (this.isContextual("type")) { + return this.flowParseDeclareTypeAlias(node); + } else if (this.isContextual("opaque")) { + return this.flowParseDeclareOpaqueType(node); + } else if (this.isContextual("interface")) { + return this.flowParseDeclareInterface(node); + } else if (this.match(types._export)) { + return this.flowParseDeclareExportDeclaration(node, insideModule); + } else { + throw this.unexpected(); } + } + }, { + key: "flowParseDeclareVariable", + value: function flowParseDeclareVariable(node) { + this.next(); + node.id = this.flowParseTypeAnnotatableIdentifier(true); + this.scope.declareName(node.id.name, BIND_VAR, node.id.start); + this.semicolon(); + return this.finishNode(node, "DeclareVariable"); + } + }, { + key: "flowParseDeclareModule", + value: function flowParseDeclareModule(node) { + var _this4 = this; - if (!confident) return; + this.scope.enter(SCOPE_OTHER); - return left || right; - case "&&": - if (!left && leftConfident || !right && rightConfident) { - confident = true; + if (this.match(types.string)) { + node.id = this.parseExprAtom(); + } else { + node.id = this.parseIdentifier(); } - if (!confident) return; + var bodyNode = node.body = this.startNode(); + var body = bodyNode.body = []; + this.expect(types.braceL); - return left && right; - } - } + while (!this.match(types.braceR)) { + var _bodyNode = this.startNode(); - if (path.isBinaryExpression()) { - var _left = evaluate(path.get("left")); - if (!confident) return; - var _right = evaluate(path.get("right")); - if (!confident) return; + if (this.match(types._import)) { + this.next(); - switch (node.operator) { - case "-": - return _left - _right; - case "+": - return _left + _right; - case "/": - return _left / _right; - case "*": - return _left * _right; - case "%": - return _left % _right; - case "**": - return Math.pow(_left, _right); - case "<": - return _left < _right; - case ">": - return _left > _right; - case "<=": - return _left <= _right; - case ">=": - return _left >= _right; - case "==": - return _left == _right; - case "!=": - return _left != _right; - case "===": - return _left === _right; - case "!==": - return _left !== _right; - case "|": - return _left | _right; - case "&": - return _left & _right; - case "^": - return _left ^ _right; - case "<<": - return _left << _right; - case ">>": - return _left >> _right; - case ">>>": - return _left >>> _right; - } - } + if (!this.isContextual("type") && !this.match(types._typeof)) { + this.raise(this.state.lastTokStart, "Imports within a `declare module` body must always be `import type` or `import typeof`"); + } + + this.parseImport(_bodyNode); + } else { + this.expectContextual("declare", "Only declares and type imports are allowed inside declare module"); + _bodyNode = this.flowParseDeclare(_bodyNode, true); + } - if (path.isCallExpression()) { - var callee = path.get("callee"); - var context = void 0; - var func = void 0; + body.push(_bodyNode); + } - if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) { - func = global[node.callee.name]; - } + this.scope.exit(); + this.expect(types.braceR); + this.finishNode(bodyNode, "BlockStatement"); + var kind = null; + var hasModuleExport = false; + var errorMessage = "Found both `declare module.exports` and `declare export` in the same module. " + "Modules can only have 1 since they are either an ES module or they are a CommonJS module"; + body.forEach(function (bodyElement) { + if (isEsModuleType(bodyElement)) { + if (kind === "CommonJS") { + _this4.raise(bodyElement.start, errorMessage); + } - if (callee.isMemberExpression()) { - var _object = callee.get("object"); - var _property = callee.get("property"); + kind = "ES"; + } else if (bodyElement.type === "DeclareModuleExports") { + if (hasModuleExport) { + _this4.raise(bodyElement.start, "Duplicate `declare module.exports` statement"); + } - if (_object.isIdentifier() && _property.isIdentifier() && VALID_CALLEES.indexOf(_object.node.name) >= 0 && INVALID_METHODS.indexOf(_property.node.name) < 0) { - context = global[_object.node.name]; - func = context[_property.node.name]; + if (kind === "ES") _this4.raise(bodyElement.start, errorMessage); + kind = "CommonJS"; + hasModuleExport = true; + } + }); + node.kind = kind || "CommonJS"; + return this.finishNode(node, "DeclareModule"); } + }, { + key: "flowParseDeclareExportDeclaration", + value: function flowParseDeclareExportDeclaration(node, insideModule) { + this.expect(types._export); + + if (this.eat(types._default)) { + if (this.match(types._function) || this.match(types._class)) { + node.declaration = this.flowParseDeclare(this.startNode()); + } else { + node.declaration = this.flowParseType(); + this.semicolon(); + } + + node.default = true; + return this.finishNode(node, "DeclareExportDeclaration"); + } else { + if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) { + var label = this.state.value; + var suggestion = exportSuggestions[label]; + this.unexpected(this.state.start, "`declare export ".concat(label, "` is not supported. Use `").concat(suggestion, "` instead")); + } - if (_object.isLiteral() && _property.isIdentifier()) { - var _type = (0, _typeof3.default)(_object.node.value); - if (_type === "string" || _type === "number") { - context = _object.node.value; - func = context[_property.node.name]; + if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) { + node.declaration = this.flowParseDeclare(this.startNode()); + node.default = false; + return this.finishNode(node, "DeclareExportDeclaration"); + } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) { + node = this.parseExport(node); + + if (node.type === "ExportNamedDeclaration") { + node.type = "ExportDeclaration"; + node.default = false; + delete node.exportKind; + } + + node.type = "Declare" + node.type; + return node; + } } + + throw this.unexpected(); } - } + }, { + key: "flowParseDeclareModuleExports", + value: function flowParseDeclareModuleExports(node) { + this.next(); + this.expectContextual("exports"); + node.typeAnnotation = this.flowParseTypeAnnotation(); + this.semicolon(); + return this.finishNode(node, "DeclareModuleExports"); + } + }, { + key: "flowParseDeclareTypeAlias", + value: function flowParseDeclareTypeAlias(node) { + this.next(); + this.flowParseTypeAlias(node); + node.type = "DeclareTypeAlias"; + return node; + } + }, { + key: "flowParseDeclareOpaqueType", + value: function flowParseDeclareOpaqueType(node) { + this.next(); + this.flowParseOpaqueType(node, true); + node.type = "DeclareOpaqueType"; + return node; + } + }, { + key: "flowParseDeclareInterface", + value: function flowParseDeclareInterface(node) { + this.next(); + this.flowParseInterfaceish(node); + return this.finishNode(node, "DeclareInterface"); + } + }, { + key: "flowParseInterfaceish", + value: function flowParseInterfaceish(node) { + var isClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + node.id = this.flowParseRestrictedIdentifier(!isClass); + this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start); - if (func) { - var args = path.get("arguments").map(evaluate); - if (!confident) return; + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } - return func.apply(context, args); - } - } + node.extends = []; + node.implements = []; + node.mixins = []; - deopt(path); - } -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/map":97,"babel-runtime/helpers/typeof":113}],124:[function(require,module,exports){ -"use strict"; + if (this.eat(types._extends)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (!isClass && this.eat(types.comma)); + } -exports.__esModule = true; + if (this.isContextual("mixins")) { + this.next(); -var _create = require("babel-runtime/core-js/object/create"); + do { + node.mixins.push(this.flowParseInterfaceExtends()); + } while (this.eat(types.comma)); + } -var _create2 = _interopRequireDefault(_create); + if (this.isContextual("implements")) { + this.next(); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + do { + node.implements.push(this.flowParseInterfaceExtends()); + } while (this.eat(types.comma)); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + node.body = this.flowParseObjectType({ + allowStatic: isClass, + allowExact: false, + allowSpread: false, + allowProto: isClass, + allowInexact: false + }); + } + }, { + key: "flowParseInterfaceExtends", + value: function flowParseInterfaceExtends() { + var node = this.startNode(); + node.id = this.flowParseQualifiedTypeIdentifier(); -exports.getStatementParent = getStatementParent; -exports.getOpposite = getOpposite; -exports.getCompletionRecords = getCompletionRecords; -exports.getSibling = getSibling; -exports.getPrevSibling = getPrevSibling; -exports.getNextSibling = getNextSibling; -exports.getAllNextSiblings = getAllNextSiblings; -exports.getAllPrevSiblings = getAllPrevSiblings; -exports.get = get; -exports._getKey = _getKey; -exports._getPattern = _getPattern; -exports.getBindingIdentifiers = getBindingIdentifiers; -exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; -exports.getBindingIdentifierPaths = getBindingIdentifierPaths; -exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths; + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } -var _index = require("./index"); + return this.finishNode(node, "InterfaceExtends"); + } + }, { + key: "flowParseInterface", + value: function flowParseInterface(node) { + this.flowParseInterfaceish(node); + return this.finishNode(node, "InterfaceDeclaration"); + } + }, { + key: "checkNotUnderscore", + value: function checkNotUnderscore(word) { + if (word === "_") { + this.raise(this.state.start, "`_` is only allowed as a type argument to call or new"); + } + } + }, { + key: "checkReservedType", + value: function checkReservedType(word, startLoc) { + if (reservedTypes.indexOf(word) > -1) { + this.raise(startLoc, "Cannot overwrite reserved type ".concat(word)); + } + } + }, { + key: "flowParseRestrictedIdentifier", + value: function flowParseRestrictedIdentifier(liberal) { + this.checkReservedType(this.state.value, this.state.start); + return this.parseIdentifier(liberal); + } + }, { + key: "flowParseTypeAlias", + value: function flowParseTypeAlias(node) { + node.id = this.flowParseRestrictedIdentifier(); + this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start); -var _index2 = _interopRequireDefault(_index); + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } -var _babelTypes = require("babel-types"); + node.right = this.flowParseTypeInitialiser(types.eq); + this.semicolon(); + return this.finishNode(node, "TypeAlias"); + } + }, { + key: "flowParseOpaqueType", + value: function flowParseOpaqueType(node, declare) { + this.expectContextual("type"); + node.id = this.flowParseRestrictedIdentifier(true); + this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start); -var t = _interopRequireWildcard(_babelTypes); + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + node.supertype = null; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this.match(types.colon)) { + node.supertype = this.flowParseTypeInitialiser(types.colon); + } -function getStatementParent() { - var path = this; + node.impltype = null; - do { - if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) { - break; - } else { - path = path.parentPath; - } - } while (path); + if (!declare) { + node.impltype = this.flowParseTypeInitialiser(types.eq); + } - if (path && (path.isProgram() || path.isFile())) { - throw new Error("File/Program node, we can't possibly find a statement parent to this"); - } + this.semicolon(); + return this.finishNode(node, "OpaqueType"); + } + }, { + key: "flowParseTypeParameter", + value: function flowParseTypeParameter() { + var requireDefault = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var nodeStart = this.state.start; + var node = this.startNode(); + var variance = this.flowParseVariance(); + var ident = this.flowParseTypeAnnotatableIdentifier(); + node.name = ident.name; + node.variance = variance; + node.bound = ident.typeAnnotation; - return path; -} + if (this.match(types.eq)) { + this.eat(types.eq); + node.default = this.flowParseType(); + } else { + if (requireDefault) { + this.raise(nodeStart, "Type parameter declaration needs a default, since a preceding type parameter declaration has a default."); + } + } -function getOpposite() { - if (this.key === "left") { - return this.getSibling("right"); - } else if (this.key === "right") { - return this.getSibling("left"); - } -} + return this.finishNode(node, "TypeParameter"); + } + }, { + key: "flowParseTypeParameterDeclaration", + value: function flowParseTypeParameterDeclaration() { + var oldInType = this.state.inType; + var node = this.startNode(); + node.params = []; + this.state.inType = true; + + if (this.isRelational("<") || this.match(types.jsxTagStart)) { + this.next(); + } else { + this.unexpected(); + } -function getCompletionRecords() { - var paths = []; + var defaultRequired = false; - var add = function add(path) { - if (path) paths = paths.concat(path.getCompletionRecords()); - }; + do { + var typeParameter = this.flowParseTypeParameter(defaultRequired); + node.params.push(typeParameter); - if (this.isIfStatement()) { - add(this.get("consequent")); - add(this.get("alternate")); - } else if (this.isDoExpression() || this.isFor() || this.isWhile()) { - add(this.get("body")); - } else if (this.isProgram() || this.isBlockStatement()) { - add(this.get("body").pop()); - } else if (this.isFunction()) { - return this.get("body").getCompletionRecords(); - } else if (this.isTryStatement()) { - add(this.get("block")); - add(this.get("handler")); - add(this.get("finalizer")); - } else { - paths.push(this); - } + if (typeParameter.default) { + defaultRequired = true; + } - return paths; -} + if (!this.isRelational(">")) { + this.expect(types.comma); + } + } while (!this.isRelational(">")); -function getSibling(key) { - return _index2.default.get({ - parentPath: this.parentPath, - parent: this.parent, - container: this.container, - listKey: this.listKey, - key: key - }); -} + this.expectRelational(">"); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterDeclaration"); + } + }, { + key: "flowParseTypeParameterInstantiation", + value: function flowParseTypeParameterInstantiation() { + var node = this.startNode(); + var oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expectRelational("<"); + var oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = false; -function getPrevSibling() { - return this.getSibling(this.key - 1); -} + while (!this.isRelational(">")) { + node.params.push(this.flowParseType()); -function getNextSibling() { - return this.getSibling(this.key + 1); -} + if (!this.isRelational(">")) { + this.expect(types.comma); + } + } -function getAllNextSiblings() { - var _key = this.key; - var sibling = this.getSibling(++_key); - var siblings = []; - while (sibling.node) { - siblings.push(sibling); - sibling = this.getSibling(++_key); - } - return siblings; -} + this.state.noAnonFunctionType = oldNoAnonFunctionType; + this.expectRelational(">"); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + }, { + key: "flowParseTypeParameterInstantiationCallOrNew", + value: function flowParseTypeParameterInstantiationCallOrNew() { + var node = this.startNode(); + var oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expectRelational("<"); + + while (!this.isRelational(">")) { + node.params.push(this.flowParseTypeOrImplicitInstantiation()); + + if (!this.isRelational(">")) { + this.expect(types.comma); + } + } -function getAllPrevSiblings() { - var _key = this.key; - var sibling = this.getSibling(--_key); - var siblings = []; - while (sibling.node) { - siblings.push(sibling); - sibling = this.getSibling(--_key); - } - return siblings; -} + this.expectRelational(">"); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + }, { + key: "flowParseInterfaceType", + value: function flowParseInterfaceType() { + var node = this.startNode(); + this.expectContextual("interface"); + node.extends = []; + + if (this.eat(types._extends)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (this.eat(types.comma)); + } -function get(key, context) { - if (context === true) context = this.context; - var parts = key.split("."); - if (parts.length === 1) { - return this._getKey(key, context); - } else { - return this._getPattern(parts, context); - } -} + node.body = this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: false, + allowProto: false, + allowInexact: false + }); + return this.finishNode(node, "InterfaceTypeAnnotation"); + } + }, { + key: "flowParseObjectPropertyKey", + value: function flowParseObjectPropertyKey() { + return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true); + } + }, { + key: "flowParseObjectTypeIndexer", + value: function flowParseObjectTypeIndexer(node, isStatic, variance) { + node.static = isStatic; -function _getKey(key, context) { - var _this = this; + if (this.lookahead().type === types.colon) { + node.id = this.flowParseObjectPropertyKey(); + node.key = this.flowParseTypeInitialiser(); + } else { + node.id = null; + node.key = this.flowParseType(); + } - var node = this.node; - var container = node[key]; + this.expect(types.bracketR); + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + return this.finishNode(node, "ObjectTypeIndexer"); + } + }, { + key: "flowParseObjectTypeInternalSlot", + value: function flowParseObjectTypeInternalSlot(node, isStatic) { + node.static = isStatic; + node.id = this.flowParseObjectPropertyKey(); + this.expect(types.bracketR); + this.expect(types.bracketR); + + if (this.isRelational("<") || this.match(types.parenL)) { + node.method = true; + node.optional = false; + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start)); + } else { + node.method = false; - if (Array.isArray(container)) { - return container.map(function (_, i) { - return _index2.default.get({ - listKey: key, - parentPath: _this, - parent: node, - container: container, - key: i - }).setContext(context); - }); - } else { - return _index2.default.get({ - parentPath: this, - parent: node, - container: node, - key: key - }).setContext(context); - } -} + if (this.eat(types.question)) { + node.optional = true; + } -function _getPattern(parts, context) { - var path = this; - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + node.value = this.flowParseTypeInitialiser(); + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + return this.finishNode(node, "ObjectTypeInternalSlot"); + } + }, { + key: "flowParseObjectTypeMethodish", + value: function flowParseObjectTypeMethodish(node) { + node.params = []; + node.rest = null; + node.typeParameters = null; - var part = _ref; + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } - if (part === ".") { - path = path.parentPath; - } else { - if (Array.isArray(path)) { - path = path[part]; - } else { - path = path.get(part, context); - } - } - } - return path; -} + this.expect(types.parenL); -function getBindingIdentifiers(duplicates) { - return t.getBindingIdentifiers(this.node, duplicates); -} + while (!this.match(types.parenR) && !this.match(types.ellipsis)) { + node.params.push(this.flowParseFunctionTypeParam()); -function getOuterBindingIdentifiers(duplicates) { - return t.getOuterBindingIdentifiers(this.node, duplicates); -} + if (!this.match(types.parenR)) { + this.expect(types.comma); + } + } -function getBindingIdentifierPaths() { - var duplicates = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var outerOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (this.eat(types.ellipsis)) { + node.rest = this.flowParseFunctionTypeParam(); + } - var path = this; - var search = [].concat(path); - var ids = (0, _create2.default)(null); + this.expect(types.parenR); + node.returnType = this.flowParseTypeInitialiser(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + }, { + key: "flowParseObjectTypeCallProperty", + value: function flowParseObjectTypeCallProperty(node, isStatic) { + var valueNode = this.startNode(); + node.static = isStatic; + node.value = this.flowParseObjectTypeMethodish(valueNode); + return this.finishNode(node, "ObjectTypeCallProperty"); + } + }, { + key: "flowParseObjectType", + value: function flowParseObjectType(_ref2) { + var allowStatic = _ref2.allowStatic, + allowExact = _ref2.allowExact, + allowSpread = _ref2.allowSpread, + allowProto = _ref2.allowProto, + allowInexact = _ref2.allowInexact; + var oldInType = this.state.inType; + this.state.inType = true; + var nodeStart = this.startNode(); + nodeStart.callProperties = []; + nodeStart.properties = []; + nodeStart.indexers = []; + nodeStart.internalSlots = []; + var endDelim; + var exact; + var inexact = false; + + if (allowExact && this.match(types.braceBarL)) { + this.expect(types.braceBarL); + endDelim = types.braceBarR; + exact = true; + } else { + this.expect(types.braceL); + endDelim = types.braceR; + exact = false; + } - while (search.length) { - var id = search.shift(); - if (!id) continue; - if (!id.node) continue; + nodeStart.exact = exact; - var keys = t.getBindingIdentifiers.keys[id.node.type]; + while (!this.match(endDelim)) { + var isStatic = false; + var protoStart = null; + var inexactStart = null; + var node = this.startNode(); - if (id.isIdentifier()) { - if (duplicates) { - var _ids = ids[id.node.name] = ids[id.node.name] || []; - _ids.push(id); - } else { - ids[id.node.name] = id; - } - continue; - } + if (allowProto && this.isContextual("proto")) { + var lookahead = this.lookahead(); - if (id.isExportDeclaration()) { - var declaration = id.get("declaration"); - if (declaration.isDeclaration()) { - search.push(declaration); - } - continue; - } + if (lookahead.type !== types.colon && lookahead.type !== types.question) { + this.next(); + protoStart = this.state.start; + allowStatic = false; + } + } - if (outerOnly) { - if (id.isFunctionDeclaration()) { - search.push(id.get("id")); - continue; - } - if (id.isFunctionExpression()) { - continue; - } - } + if (allowStatic && this.isContextual("static")) { + var _lookahead = this.lookahead(); - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var child = id.get(key); - if (Array.isArray(child) || child.node) { - search = search.concat(child); - } - } - } - } + if (_lookahead.type !== types.colon && _lookahead.type !== types.question) { + this.next(); + isStatic = true; + } + } - return ids; -} + var variance = this.flowParseVariance(); -function getOuterBindingIdentifierPaths(duplicates) { - return this.getBindingIdentifierPaths(duplicates, true); -} -},{"./index":125,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/create":100,"babel-types":151}],125:[function(require,module,exports){ -"use strict"; + if (this.eat(types.bracketL)) { + if (protoStart != null) { + this.unexpected(protoStart); + } -exports.__esModule = true; + if (this.eat(types.bracketL)) { + if (variance) { + this.unexpected(variance.start); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); + } else { + nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); + } + } else if (this.match(types.parenL) || this.isRelational("<")) { + if (protoStart != null) { + this.unexpected(protoStart); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (variance) { + this.unexpected(variance.start); + } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); + } else { + var _allowInexact; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + var kind = "init"; -var _virtualTypes = require("./lib/virtual-types"); + if (this.isContextual("get") || this.isContextual("set")) { + var _lookahead2 = this.lookahead(); -var virtualTypes = _interopRequireWildcard(_virtualTypes); + if (_lookahead2.type === types.name || _lookahead2.type === types.string || _lookahead2.type === types.num) { + kind = this.state.value; + this.next(); + } + } -var _debug2 = require("debug"); + var propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, (_allowInexact = allowInexact) !== null && _allowInexact !== void 0 ? _allowInexact : !exact); -var _debug3 = _interopRequireDefault(_debug2); + if (propOrInexact === null) { + inexact = true; + inexactStart = this.state.lastTokStart; + } else { + nodeStart.properties.push(propOrInexact); + } + } -var _invariant = require("invariant"); + this.flowObjectTypeSemicolon(); -var _invariant2 = _interopRequireDefault(_invariant); + if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) { + this.raise(inexactStart, "Explicit inexact syntax must appear at the end of an inexact object"); + } + } -var _index = require("../index"); + this.expect(endDelim); -var _index2 = _interopRequireDefault(_index); + if (allowSpread) { + nodeStart.inexact = inexact; + } -var _assign = require("lodash/assign"); + var out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); + this.state.inType = oldInType; + return out; + } + }, { + key: "flowParseObjectTypeProperty", + value: function flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) { + if (this.eat(types.ellipsis)) { + var isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR); + + if (isInexactToken) { + if (!allowSpread) { + this.raise(this.state.lastTokStart, "Explicit inexact syntax cannot appear in class or interface definitions"); + } else if (!allowInexact) { + this.raise(this.state.lastTokStart, "Explicit inexact syntax cannot appear inside an explicit exact object type"); + } -var _assign2 = _interopRequireDefault(_assign); + if (variance) { + this.raise(variance.start, "Explicit inexact syntax cannot have variance"); + } -var _scope = require("../scope"); + return null; + } -var _scope2 = _interopRequireDefault(_scope); + if (!allowSpread) { + this.raise(this.state.lastTokStart, "Spread operator cannot appear in class or interface definitions"); + } -var _babelTypes = require("babel-types"); + if (protoStart != null) { + this.unexpected(protoStart); + } -var t = _interopRequireWildcard(_babelTypes); + if (variance) { + this.raise(variance.start, "Spread properties cannot have variance"); + } -var _cache = require("../cache"); + node.argument = this.flowParseType(); + return this.finishNode(node, "ObjectTypeSpreadProperty"); + } else { + node.key = this.flowParseObjectPropertyKey(); + node.static = isStatic; + node.proto = protoStart != null; + node.kind = kind; + var optional = false; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (this.isRelational("<") || this.match(types.parenL)) { + node.method = true; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (protoStart != null) { + this.unexpected(protoStart); + } -var _debug = (0, _debug3.default)("babel"); + if (variance) { + this.unexpected(variance.start); + } -var NodePath = function () { - function NodePath(hub, parent) { - (0, _classCallCheck3.default)(this, NodePath); + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start)); - this.parent = parent; - this.hub = hub; - this.contexts = []; - this.data = {}; - this.shouldSkip = false; - this.shouldStop = false; - this.removed = false; - this.state = null; - this.opts = null; - this.skipKeys = null; - this.parentPath = null; - this.context = null; - this.container = null; - this.listKey = null; - this.inList = false; - this.parentKey = null; - this.key = null; - this.node = null; - this.scope = null; - this.type = null; - this.typeAnnotation = null; - } + if (kind === "get" || kind === "set") { + this.flowCheckGetterSetterParams(node); + } + } else { + if (kind !== "init") this.unexpected(); + node.method = false; - NodePath.get = function get(_ref) { - var hub = _ref.hub, - parentPath = _ref.parentPath, - parent = _ref.parent, - container = _ref.container, - listKey = _ref.listKey, - key = _ref.key; + if (this.eat(types.question)) { + optional = true; + } - if (!hub && parentPath) { - hub = parentPath.hub; - } + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + } - (0, _invariant2.default)(parent, "To get a node path the parent needs to exist"); + node.optional = optional; + return this.finishNode(node, "ObjectTypeProperty"); + } + } + }, { + key: "flowCheckGetterSetterParams", + value: function flowCheckGetterSetterParams(property) { + var paramCount = property.kind === "get" ? 0 : 1; + var start = property.start; + var length = property.value.params.length + (property.value.rest ? 1 : 0); + + if (length !== paramCount) { + if (property.kind === "get") { + this.raise(start, "getter must not have any formal parameters"); + } else { + this.raise(start, "setter must have exactly one formal parameter"); + } + } - var targetNode = container[key]; + if (property.kind === "set" && property.value.rest) { + this.raise(start, "setter function argument must not be a rest parameter"); + } + } + }, { + key: "flowObjectTypeSemicolon", + value: function flowObjectTypeSemicolon() { + if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) { + this.unexpected(); + } + } + }, { + key: "flowParseQualifiedTypeIdentifier", + value: function flowParseQualifiedTypeIdentifier(startPos, startLoc, id) { + startPos = startPos || this.state.start; + startLoc = startLoc || this.state.startLoc; + var node = id || this.parseIdentifier(); + + while (this.eat(types.dot)) { + var node2 = this.startNodeAt(startPos, startLoc); + node2.qualification = node; + node2.id = this.parseIdentifier(); + node = this.finishNode(node2, "QualifiedTypeIdentifier"); + } - var paths = _cache.path.get(parent) || []; - if (!_cache.path.has(parent)) { - _cache.path.set(parent, paths); - } + return node; + } + }, { + key: "flowParseGenericType", + value: function flowParseGenericType(startPos, startLoc, id) { + var node = this.startNodeAt(startPos, startLoc); + node.typeParameters = null; + node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id); - var path = void 0; + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } - for (var i = 0; i < paths.length; i++) { - var pathCheck = paths[i]; - if (pathCheck.node === targetNode) { - path = pathCheck; - break; - } - } + return this.finishNode(node, "GenericTypeAnnotation"); + } + }, { + key: "flowParseTypeofType", + value: function flowParseTypeofType() { + var node = this.startNode(); + this.expect(types._typeof); + node.argument = this.flowParsePrimaryType(); + return this.finishNode(node, "TypeofTypeAnnotation"); + } + }, { + key: "flowParseTupleType", + value: function flowParseTupleType() { + var node = this.startNode(); + node.types = []; + this.expect(types.bracketL); + + while (this.state.pos < this.length && !this.match(types.bracketR)) { + node.types.push(this.flowParseType()); + if (this.match(types.bracketR)) break; + this.expect(types.comma); + } - if (!path) { - path = new NodePath(hub, parent); - paths.push(path); - } + this.expect(types.bracketR); + return this.finishNode(node, "TupleTypeAnnotation"); + } + }, { + key: "flowParseFunctionTypeParam", + value: function flowParseFunctionTypeParam() { + var name = null; + var optional = false; + var typeAnnotation = null; + var node = this.startNode(); + var lh = this.lookahead(); + + if (lh.type === types.colon || lh.type === types.question) { + name = this.parseIdentifier(); + + if (this.eat(types.question)) { + optional = true; + } - path.setup(parentPath, container, listKey, key); + typeAnnotation = this.flowParseTypeInitialiser(); + } else { + typeAnnotation = this.flowParseType(); + } - return path; - }; + node.name = name; + node.optional = optional; + node.typeAnnotation = typeAnnotation; + return this.finishNode(node, "FunctionTypeParam"); + } + }, { + key: "reinterpretTypeAsFunctionTypeParam", + value: function reinterpretTypeAsFunctionTypeParam(type) { + var node = this.startNodeAt(type.start, type.loc.start); + node.name = null; + node.optional = false; + node.typeAnnotation = type; + return this.finishNode(node, "FunctionTypeParam"); + } + }, { + key: "flowParseFunctionTypeParams", + value: function flowParseFunctionTypeParams() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var rest = null; - NodePath.prototype.getScope = function getScope(scope) { - var ourScope = scope; + while (!this.match(types.parenR) && !this.match(types.ellipsis)) { + params.push(this.flowParseFunctionTypeParam()); - if (this.isScope()) { - ourScope = new _scope2.default(this, scope); - } + if (!this.match(types.parenR)) { + this.expect(types.comma); + } + } - return ourScope; - }; + if (this.eat(types.ellipsis)) { + rest = this.flowParseFunctionTypeParam(); + } - NodePath.prototype.setData = function setData(key, val) { - return this.data[key] = val; - }; + return { + params: params, + rest: rest + }; + } + }, { + key: "flowIdentToTypeAnnotation", + value: function flowIdentToTypeAnnotation(startPos, startLoc, node, id) { + switch (id.name) { + case "any": + return this.finishNode(node, "AnyTypeAnnotation"); + + case "bool": + case "boolean": + return this.finishNode(node, "BooleanTypeAnnotation"); - NodePath.prototype.getData = function getData(key, def) { - var val = this.data[key]; - if (!val && def) val = this.data[key] = def; - return val; - }; + case "mixed": + return this.finishNode(node, "MixedTypeAnnotation"); - NodePath.prototype.buildCodeFrameError = function buildCodeFrameError(msg) { - var Error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SyntaxError; + case "empty": + return this.finishNode(node, "EmptyTypeAnnotation"); - return this.hub.file.buildCodeFrameError(this.node, msg, Error); - }; + case "number": + return this.finishNode(node, "NumberTypeAnnotation"); - NodePath.prototype.traverse = function traverse(visitor, state) { - (0, _index2.default)(this.node, visitor, this.scope, state, this); - }; + case "string": + return this.finishNode(node, "StringTypeAnnotation"); - NodePath.prototype.mark = function mark(type, message) { - this.hub.file.metadata.marked.push({ - type: type, - message: message, - loc: this.node.loc - }); - }; + default: + this.checkNotUnderscore(id.name); + return this.flowParseGenericType(startPos, startLoc, id); + } + } + }, { + key: "flowParsePrimaryType", + value: function flowParsePrimaryType() { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var node = this.startNode(); + var tmp; + var type; + var isGroupedType = false; + var oldNoAnonFunctionType = this.state.noAnonFunctionType; - NodePath.prototype.set = function set(key, node) { - t.validate(this.node, key, node); - this.node[key] = node; - }; + switch (this.state.type) { + case types.name: + if (this.isContextual("interface")) { + return this.flowParseInterfaceType(); + } - NodePath.prototype.getPathLocation = function getPathLocation() { - var parts = []; - var path = this; - do { - var key = path.key; - if (path.inList) key = path.listKey + "[" + key + "]"; - parts.unshift(key); - } while (path = path.parentPath); - return parts.join("."); - }; + return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier()); - NodePath.prototype.debug = function debug(buildMessage) { - if (!_debug.enabled) return; - _debug(this.getPathLocation() + " " + this.type + ": " + buildMessage()); - }; + case types.braceL: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: true, + allowProto: false, + allowInexact: true + }); - return NodePath; -}(); + case types.braceBarL: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: true, + allowSpread: true, + allowProto: false, + allowInexact: false + }); -exports.default = NodePath; + case types.bracketL: + this.state.noAnonFunctionType = false; + type = this.flowParseTupleType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + return type; + + case types.relational: + if (this.state.value === "<") { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + this.expect(types.parenL); + tmp = this.flowParseFunctionTypeParams(); + node.params = tmp.params; + node.rest = tmp.rest; + this.expect(types.parenR); + this.expect(types.arrow); + node.returnType = this.flowParseType(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + break; -(0, _assign2.default)(NodePath.prototype, require("./ancestry")); -(0, _assign2.default)(NodePath.prototype, require("./inference")); -(0, _assign2.default)(NodePath.prototype, require("./replacement")); -(0, _assign2.default)(NodePath.prototype, require("./evaluation")); -(0, _assign2.default)(NodePath.prototype, require("./conversion")); -(0, _assign2.default)(NodePath.prototype, require("./introspection")); -(0, _assign2.default)(NodePath.prototype, require("./context")); -(0, _assign2.default)(NodePath.prototype, require("./removal")); -(0, _assign2.default)(NodePath.prototype, require("./modification")); -(0, _assign2.default)(NodePath.prototype, require("./family")); -(0, _assign2.default)(NodePath.prototype, require("./comments")); + case types.parenL: + this.next(); -var _loop2 = function _loop2() { - if (_isArray) { - if (_i >= _iterator.length) return "break"; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) return "break"; - _ref2 = _i.value; - } + if (!this.match(types.parenR) && !this.match(types.ellipsis)) { + if (this.match(types.name)) { + var token = this.lookahead().type; + isGroupedType = token !== types.question && token !== types.colon; + } else { + isGroupedType = true; + } + } - var type = _ref2; + if (isGroupedType) { + this.state.noAnonFunctionType = false; + type = this.flowParseType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; - var typeKey = "is" + type; - NodePath.prototype[typeKey] = function (opts) { - return t[typeKey](this.node, opts); - }; + if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) { + this.expect(types.parenR); + return type; + } else { + this.eat(types.comma); + } + } - NodePath.prototype["assert" + type] = function (opts) { - if (!this[typeKey](opts)) { - throw new TypeError("Expected node path of type " + type); - } - }; -}; + if (type) { + tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]); + } else { + tmp = this.flowParseFunctionTypeParams(); + } -for (var _iterator = t.TYPES, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; + node.params = tmp.params; + node.rest = tmp.rest; + this.expect(types.parenR); + this.expect(types.arrow); + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + + case types.string: + return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); + + case types._true: + case types._false: + node.value = this.match(types._true); + this.next(); + return this.finishNode(node, "BooleanLiteralTypeAnnotation"); + + case types.plusMin: + if (this.state.value === "-") { + this.next(); + + if (this.match(types.num)) { + return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start); + } - var _ret2 = _loop2(); + if (this.match(types.bigint)) { + return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start); + } - if (_ret2 === "break") break; -} + throw this.raise(this.state.start, "Unexpected token, expected \"number\" or \"bigint\""); + } -var _loop = function _loop(type) { - if (type[0] === "_") return "continue"; - if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); + this.unexpected(); - var virtualType = virtualTypes[type]; + case types.num: + return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); - NodePath.prototype["is" + type] = function (opts) { - return virtualType.checkPath(this, opts); - }; -}; + case types.bigint: + return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); -for (var type in virtualTypes) { - var _ret = _loop(type); + case types._void: + this.next(); + return this.finishNode(node, "VoidTypeAnnotation"); - if (_ret === "continue") continue; -} -module.exports = exports["default"]; -},{"../cache":115,"../index":118,"../scope":137,"./ancestry":119,"./comments":120,"./context":121,"./conversion":122,"./evaluation":123,"./family":124,"./inference":126,"./introspection":129,"./lib/virtual-types":132,"./modification":133,"./removal":134,"./replacement":135,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-types":151,"debug":279,"invariant":292,"lodash/assign":463}],126:[function(require,module,exports){ -"use strict"; + case types._null: + this.next(); + return this.finishNode(node, "NullLiteralTypeAnnotation"); -exports.__esModule = true; + case types._this: + this.next(); + return this.finishNode(node, "ThisTypeAnnotation"); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + case types.star: + this.next(); + return this.finishNode(node, "ExistsTypeAnnotation"); -var _getIterator3 = _interopRequireDefault(_getIterator2); + default: + if (this.state.type.keyword === "typeof") { + return this.flowParseTypeofType(); + } else if (this.state.type.keyword) { + var label = this.state.type.label; + this.next(); + return _get(_getPrototypeOf(_class2.prototype), "createIdentifier", this).call(this, node, label); + } -exports.getTypeAnnotation = getTypeAnnotation; -exports._getTypeAnnotation = _getTypeAnnotation; -exports.isBaseType = isBaseType; -exports.couldBeBaseType = couldBeBaseType; -exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches; -exports.isGenericType = isGenericType; + } -var _inferers = require("./inferers"); + throw this.unexpected(); + } + }, { + key: "flowParsePostfixType", + value: function flowParsePostfixType() { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var type = this.flowParsePrimaryType(); + + while (this.match(types.bracketL) && !this.canInsertSemicolon()) { + var node = this.startNodeAt(startPos, startLoc); + node.elementType = type; + this.expect(types.bracketL); + this.expect(types.bracketR); + type = this.finishNode(node, "ArrayTypeAnnotation"); + } -var inferers = _interopRequireWildcard(_inferers); + return type; + } + }, { + key: "flowParsePrefixType", + value: function flowParsePrefixType() { + var node = this.startNode(); -var _babelTypes = require("babel-types"); + if (this.eat(types.question)) { + node.typeAnnotation = this.flowParsePrefixType(); + return this.finishNode(node, "NullableTypeAnnotation"); + } else { + return this.flowParsePostfixType(); + } + } + }, { + key: "flowParseAnonFunctionWithoutParens", + value: function flowParseAnonFunctionWithoutParens() { + var param = this.flowParsePrefixType(); + + if (!this.state.noAnonFunctionType && this.eat(types.arrow)) { + var node = this.startNodeAt(param.start, param.loc.start); + node.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; + node.rest = null; + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } -var t = _interopRequireWildcard(_babelTypes); + return param; + } + }, { + key: "flowParseIntersectionType", + value: function flowParseIntersectionType() { + var node = this.startNode(); + this.eat(types.bitwiseAND); + var type = this.flowParseAnonFunctionWithoutParens(); + node.types = [type]; + + while (this.eat(types.bitwiseAND)) { + node.types.push(this.flowParseAnonFunctionWithoutParens()); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); + } + }, { + key: "flowParseUnionType", + value: function flowParseUnionType() { + var node = this.startNode(); + this.eat(types.bitwiseOR); + var type = this.flowParseIntersectionType(); + node.types = [type]; + + while (this.eat(types.bitwiseOR)) { + node.types.push(this.flowParseIntersectionType()); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); + } + }, { + key: "flowParseType", + value: function flowParseType() { + var oldInType = this.state.inType; + this.state.inType = true; + var type = this.flowParseUnionType(); + this.state.inType = oldInType; + this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType; + return type; + } + }, { + key: "flowParseTypeOrImplicitInstantiation", + value: function flowParseTypeOrImplicitInstantiation() { + if (this.state.type === types.name && this.state.value === "_") { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var node = this.parseIdentifier(); + return this.flowParseGenericType(startPos, startLoc, node); + } else { + return this.flowParseType(); + } + } + }, { + key: "flowParseTypeAnnotation", + value: function flowParseTypeAnnotation() { + var node = this.startNode(); + node.typeAnnotation = this.flowParseTypeInitialiser(); + return this.finishNode(node, "TypeAnnotation"); + } + }, { + key: "flowParseTypeAnnotatableIdentifier", + value: function flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { + var ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); + + if (this.match(types.colon)) { + ident.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(ident); + } -function getTypeAnnotation() { - if (this.typeAnnotation) return this.typeAnnotation; + return ident; + } + }, { + key: "typeCastToParameter", + value: function typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); + return node.expression; + } + }, { + key: "flowParseVariance", + value: function flowParseVariance() { + var variance = null; - var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); - if (t.isTypeAnnotation(type)) type = type.typeAnnotation; - return this.typeAnnotation = type; -} + if (this.match(types.plusMin)) { + variance = this.startNode(); -function _getTypeAnnotation() { - var node = this.node; + if (this.state.value === "+") { + variance.kind = "plus"; + } else { + variance.kind = "minus"; + } - if (!node) { - if (this.key === "init" && this.parentPath.isVariableDeclarator()) { - var declar = this.parentPath.parentPath; - var declarParent = declar.parentPath; + this.next(); + this.finishNode(variance, "Variance"); + } - if (declar.key === "left" && declarParent.isForInStatement()) { - return t.stringTypeAnnotation(); - } + return variance; + } + }, { + key: "parseFunctionBody", + value: function parseFunctionBody(node, allowExpressionBody) { + var _this5 = this; - if (declar.key === "left" && declarParent.isForOfStatement()) { - return t.anyTypeAnnotation(); - } + var isMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - return t.voidTypeAnnotation(); - } else { - return; - } - } + if (allowExpressionBody) { + return this.forwardNoArrowParamsConversionAt(node, function () { + return _get(_getPrototypeOf(_class2.prototype), "parseFunctionBody", _this5).call(_this5, node, true, isMethod); + }); + } - if (node.typeAnnotation) { - return node.typeAnnotation; - } + return _get(_getPrototypeOf(_class2.prototype), "parseFunctionBody", this).call(this, node, false, isMethod); + } + }, { + key: "parseFunctionBodyAndFinish", + value: function parseFunctionBodyAndFinish(node, type) { + var isMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var inferer = inferers[node.type]; - if (inferer) { - return inferer.call(this, node); - } + if (this.match(types.colon)) { + var typeNode = this.startNode(); - inferer = inferers[this.parentPath.type]; - if (inferer && inferer.validParent) { - return this.parentPath.getTypeAnnotation(); - } -} + var _this$flowParseTypeAn3 = this.flowParseTypeAndPredicateInitialiser(); -function isBaseType(baseName, soft) { - return _isBaseType(baseName, this.getTypeAnnotation(), soft); -} + var _this$flowParseTypeAn4 = _slicedToArray(_this$flowParseTypeAn3, 2); -function _isBaseType(baseName, type, soft) { - if (baseName === "string") { - return t.isStringTypeAnnotation(type); - } else if (baseName === "number") { - return t.isNumberTypeAnnotation(type); - } else if (baseName === "boolean") { - return t.isBooleanTypeAnnotation(type); - } else if (baseName === "any") { - return t.isAnyTypeAnnotation(type); - } else if (baseName === "mixed") { - return t.isMixedTypeAnnotation(type); - } else if (baseName === "empty") { - return t.isEmptyTypeAnnotation(type); - } else if (baseName === "void") { - return t.isVoidTypeAnnotation(type); - } else { - if (soft) { - return false; - } else { - throw new Error("Unknown base type " + baseName); - } - } -} + typeNode.typeAnnotation = _this$flowParseTypeAn4[0]; + node.predicate = _this$flowParseTypeAn4[1]; + node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; + } -function couldBeBaseType(name) { - var type = this.getTypeAnnotation(); - if (t.isAnyTypeAnnotation(type)) return true; + _get(_getPrototypeOf(_class2.prototype), "parseFunctionBodyAndFinish", this).call(this, node, type, isMethod); + } + }, { + key: "parseStatement", + value: function parseStatement(context, topLevel) { + if (this.state.strict && this.match(types.name) && this.state.value === "interface") { + var node = this.startNode(); + this.next(); + return this.flowParseInterface(node); + } else if (this.shouldParseEnums() && this.isContextual("enum")) { + var _node = this.startNode(); - if (t.isUnionTypeAnnotation(type)) { - for (var _iterator = type.types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + this.next(); + return this.flowParseEnumDeclaration(_node); + } else { + var stmt = _get(_getPrototypeOf(_class2.prototype), "parseStatement", this).call(this, context, topLevel); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (this.flowPragma === undefined && !this.isValidDirective(stmt)) { + this.flowPragma = null; + } - var type2 = _ref; + return stmt; + } + } + }, { + key: "parseExpressionStatement", + value: function parseExpressionStatement(node, expr) { + if (expr.type === "Identifier") { + if (expr.name === "declare") { + if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) { + return this.flowParseDeclare(node); + } + } else if (this.match(types.name)) { + if (expr.name === "interface") { + return this.flowParseInterface(node); + } else if (expr.name === "type") { + return this.flowParseTypeAlias(node); + } else if (expr.name === "opaque") { + return this.flowParseOpaqueType(node, false); + } + } + } - if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { - return true; - } - } - return false; - } else { - return _isBaseType(name, type, true); - } -} + return _get(_getPrototypeOf(_class2.prototype), "parseExpressionStatement", this).call(this, node, expr); + } + }, { + key: "shouldParseExportDeclaration", + value: function shouldParseExportDeclaration() { + return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || _get(_getPrototypeOf(_class2.prototype), "shouldParseExportDeclaration", this).call(this); + } + }, { + key: "isExportDefaultSpecifier", + value: function isExportDefaultSpecifier() { + if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) { + return false; + } -function baseTypeStrictlyMatches(right) { - var left = this.getTypeAnnotation(); - right = right.getTypeAnnotation(); + return _get(_getPrototypeOf(_class2.prototype), "isExportDefaultSpecifier", this).call(this); + } + }, { + key: "parseExportDefaultExpression", + value: function parseExportDefaultExpression() { + if (this.shouldParseEnums() && this.isContextual("enum")) { + var node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } - if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { - return right.type === left.type; - } -} + return _get(_getPrototypeOf(_class2.prototype), "parseExportDefaultExpression", this).call(this); + } + }, { + key: "parseConditional", + value: function parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) { + var _this6 = this; -function isGenericType(genericName) { - var type = this.getTypeAnnotation(); - return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); -} -},{"./inferers":128,"babel-runtime/core-js/get-iterator":95,"babel-types":151}],127:[function(require,module,exports){ -"use strict"; + if (!this.match(types.question)) return expr; -exports.__esModule = true; + if (refNeedsArrowPos) { + var result = this.tryParse(function () { + return _get(_getPrototypeOf(_class2.prototype), "parseConditional", _this6).call(_this6, expr, noIn, startPos, startLoc); + }); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (!result.node) { + refNeedsArrowPos.start = result.error.pos || this.state.start; + return expr; + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (result.error) this.state = result.failState; + return result.node; + } -exports.default = function (node) { - if (!this.isReferenced()) return; + this.expect(types.question); + var state = this.state.clone(); + var originalNoArrowAt = this.state.noArrowAt; + var node = this.startNodeAt(startPos, startLoc); - var binding = this.scope.getBinding(node.name); - if (binding) { - if (binding.identifier.typeAnnotation) { - return binding.identifier.typeAnnotation; - } else { - return getTypeAnnotationBindingConstantViolations(this, node.name); - } - } + var _this$tryParseConditi = this.tryParseConditionalConsequent(), + consequent = _this$tryParseConditi.consequent, + failed = _this$tryParseConditi.failed; - if (node.name === "undefined") { - return t.voidTypeAnnotation(); - } else if (node.name === "NaN" || node.name === "Infinity") { - return t.numberTypeAnnotation(); - } else if (node.name === "arguments") {} -}; + var _this$getArrowLikeExp = this.getArrowLikeExpressions(consequent), + _this$getArrowLikeExp2 = _slicedToArray(_this$getArrowLikeExp, 2), + valid = _this$getArrowLikeExp2[0], + invalid = _this$getArrowLikeExp2[1]; -var _babelTypes = require("babel-types"); + if (failed || invalid.length > 0) { + var noArrowAt = _toConsumableArray(originalNoArrowAt); -var t = _interopRequireWildcard(_babelTypes); + if (invalid.length > 0) { + this.state = state; + this.state.noArrowAt = noArrowAt; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + for (var i = 0; i < invalid.length; i++) { + noArrowAt.push(invalid[i].start); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _this$tryParseConditi2 = this.tryParseConditionalConsequent(); -function getTypeAnnotationBindingConstantViolations(path, name) { - var binding = path.scope.getBinding(name); + consequent = _this$tryParseConditi2.consequent; + failed = _this$tryParseConditi2.failed; - var types = []; - path.typeAnnotation = t.unionTypeAnnotation(types); + var _this$getArrowLikeExp3 = this.getArrowLikeExpressions(consequent); - var functionConstantViolations = []; - var constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations); + var _this$getArrowLikeExp4 = _slicedToArray(_this$getArrowLikeExp3, 2); - var testType = getConditionalAnnotation(path, name); - if (testType) { - var testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); + valid = _this$getArrowLikeExp4[0]; + invalid = _this$getArrowLikeExp4[1]; + } - constantViolations = constantViolations.filter(function (path) { - return testConstantViolations.indexOf(path) < 0; - }); + if (failed && valid.length > 1) { + this.raise(state.start, "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate."); + } - types.push(testType.typeAnnotation); - } + if (failed && valid.length === 1) { + this.state = state; + this.state.noArrowAt = noArrowAt.concat(valid[0].start); - if (constantViolations.length) { - constantViolations = constantViolations.concat(functionConstantViolations); + var _this$tryParseConditi3 = this.tryParseConditionalConsequent(); - for (var _iterator = constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + consequent = _this$tryParseConditi3.consequent; + failed = _this$tryParseConditi3.failed; + } + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + this.getArrowLikeExpressions(consequent, true); + this.state.noArrowAt = originalNoArrowAt; + this.expect(types.colon); + node.test = expr; + node.consequent = consequent; + node.alternate = this.forwardNoArrowParamsConversionAt(node, function () { + return _this6.parseMaybeAssign(noIn, undefined, undefined, undefined); + }); + return this.finishNode(node, "ConditionalExpression"); + } + }, { + key: "tryParseConditionalConsequent", + value: function tryParseConditionalConsequent() { + this.state.noArrowParamsConversionAt.push(this.state.start); + var consequent = this.parseMaybeAssign(); + var failed = !this.match(types.colon); + this.state.noArrowParamsConversionAt.pop(); + return { + consequent: consequent, + failed: failed + }; + } + }, { + key: "getArrowLikeExpressions", + value: function getArrowLikeExpressions(node, disallowInvalid) { + var _this7 = this; - var violation = _ref; + var stack = [node]; + var arrows = []; - types.push(violation.getTypeAnnotation()); - } - } + while (stack.length !== 0) { + var _node2 = stack.pop(); - if (types.length) { - return t.createUnionTypeAnnotation(types); - } -} + if (_node2.type === "ArrowFunctionExpression") { + if (_node2.typeParameters || !_node2.returnType) { + this.finishArrowValidation(_node2); + } else { + arrows.push(_node2); + } -function getConstantViolationsBefore(binding, path, functions) { - var violations = binding.constantViolations.slice(); - violations.unshift(binding.path); - return violations.filter(function (violation) { - violation = violation.resolve(); - var status = violation._guessExecutionStatusRelativeTo(path); - if (functions && status === "function") functions.push(violation); - return status === "before"; - }); -} + stack.push(_node2.body); + } else if (_node2.type === "ConditionalExpression") { + stack.push(_node2.consequent); + stack.push(_node2.alternate); + } + } -function inferAnnotationFromBinaryExpression(name, path) { - var operator = path.node.operator; + if (disallowInvalid) { + arrows.forEach(function (node) { + return _this7.finishArrowValidation(node); + }); + return [arrows, []]; + } - var right = path.get("right").resolve(); - var left = path.get("left").resolve(); + return partition(arrows, function (node) { + return node.params.every(function (param) { + return _this7.isAssignable(param, true); + }); + }); + } + }, { + key: "finishArrowValidation", + value: function finishArrowValidation(node) { + var _node$extra; - var target = void 0; - if (left.isIdentifier({ name: name })) { - target = right; - } else if (right.isIdentifier({ name: name })) { - target = left; - } - if (target) { - if (operator === "===") { - return target.getTypeAnnotation(); - } else if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else { - return; - } - } else { - if (operator !== "===") return; - } + this.toAssignableList(node.params, true, "arrow function parameters", (_node$extra = node.extra) === null || _node$extra === void 0 ? void 0 : _node$extra.trailingComma); + this.scope.enter(functionFlags(false, false) | SCOPE_ARROW); - var typeofPath = void 0; - var typePath = void 0; - if (left.isUnaryExpression({ operator: "typeof" })) { - typeofPath = left; - typePath = right; - } else if (right.isUnaryExpression({ operator: "typeof" })) { - typeofPath = right; - typePath = left; - } - if (!typePath && !typeofPath) return; + _get(_getPrototypeOf(_class2.prototype), "checkParams", this).call(this, node, false, true); - typePath = typePath.resolve(); - if (!typePath.isLiteral()) return; + this.scope.exit(); + } + }, { + key: "forwardNoArrowParamsConversionAt", + value: function forwardNoArrowParamsConversionAt(node, parse) { + var result; + + if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + this.state.noArrowParamsConversionAt.push(this.state.start); + result = parse(); + this.state.noArrowParamsConversionAt.pop(); + } else { + result = parse(); + } - var typeValue = typePath.node.value; - if (typeof typeValue !== "string") return; + return result; + } + }, { + key: "parseParenItem", + value: function parseParenItem(node, startPos, startLoc) { + node = _get(_getPrototypeOf(_class2.prototype), "parseParenItem", this).call(this, node, startPos, startLoc); - if (!typeofPath.get("argument").isIdentifier({ name: name })) return; + if (this.eat(types.question)) { + node.optional = true; + this.resetEndLocation(node); + } - return t.createTypeAnnotationBasedOnTypeof(typePath.node.value); -} + if (this.match(types.colon)) { + var typeCastNode = this.startNodeAt(startPos, startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TypeCastExpression"); + } -function getParentConditionalPath(path) { - var parentPath = void 0; - while (parentPath = path.parentPath) { - if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) { - if (path.key === "test") { - return; - } else { - return parentPath; - } - } else { - path = parentPath; - } - } -} + return node; + } + }, { + key: "assertModuleNodeAllowed", + value: function assertModuleNodeAllowed(node) { + if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") { + return; + } -function getConditionalAnnotation(path, name) { - var ifStatement = getParentConditionalPath(path); - if (!ifStatement) return; + _get(_getPrototypeOf(_class2.prototype), "assertModuleNodeAllowed", this).call(this, node); + } + }, { + key: "parseExport", + value: function parseExport(node) { + var decl = _get(_getPrototypeOf(_class2.prototype), "parseExport", this).call(this, node); - var test = ifStatement.get("test"); - var paths = [test]; - var types = []; + if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") { + decl.exportKind = decl.exportKind || "value"; + } - do { - var _path = paths.shift().resolve(); + return decl; + } + }, { + key: "parseExportDeclaration", + value: function parseExportDeclaration(node) { + if (this.isContextual("type")) { + node.exportKind = "type"; + var declarationNode = this.startNode(); + this.next(); + + if (this.match(types.braceL)) { + node.specifiers = this.parseExportSpecifiers(); + this.parseExportFrom(node); + return null; + } else { + return this.flowParseTypeAlias(declarationNode); + } + } else if (this.isContextual("opaque")) { + node.exportKind = "type"; - if (_path.isLogicalExpression()) { - paths.push(_path.get("left")); - paths.push(_path.get("right")); - } + var _declarationNode = this.startNode(); - if (_path.isBinaryExpression()) { - var type = inferAnnotationFromBinaryExpression(name, _path); - if (type) types.push(type); - } - } while (paths.length); + this.next(); + return this.flowParseOpaqueType(_declarationNode, false); + } else if (this.isContextual("interface")) { + node.exportKind = "type"; - if (types.length) { - return { - typeAnnotation: t.createUnionTypeAnnotation(types), - ifStatement: ifStatement - }; - } else { - return getConditionalAnnotation(ifStatement, name); - } -} -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151}],128:[function(require,module,exports){ -"use strict"; + var _declarationNode2 = this.startNode(); -exports.__esModule = true; -exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = exports.Identifier = undefined; + this.next(); + return this.flowParseInterface(_declarationNode2); + } else if (this.shouldParseEnums() && this.isContextual("enum")) { + node.exportKind = "value"; -var _infererReference = require("./inferer-reference"); + var _declarationNode3 = this.startNode(); -Object.defineProperty(exports, "Identifier", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_infererReference).default; - } -}); -exports.VariableDeclarator = VariableDeclarator; -exports.TypeCastExpression = TypeCastExpression; -exports.NewExpression = NewExpression; -exports.TemplateLiteral = TemplateLiteral; -exports.UnaryExpression = UnaryExpression; -exports.BinaryExpression = BinaryExpression; -exports.LogicalExpression = LogicalExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.SequenceExpression = SequenceExpression; -exports.AssignmentExpression = AssignmentExpression; -exports.UpdateExpression = UpdateExpression; -exports.StringLiteral = StringLiteral; -exports.NumericLiteral = NumericLiteral; -exports.BooleanLiteral = BooleanLiteral; -exports.NullLiteral = NullLiteral; -exports.RegExpLiteral = RegExpLiteral; -exports.ObjectExpression = ObjectExpression; -exports.ArrayExpression = ArrayExpression; -exports.RestElement = RestElement; -exports.CallExpression = CallExpression; -exports.TaggedTemplateExpression = TaggedTemplateExpression; + this.next(); + return this.flowParseEnumDeclaration(_declarationNode3); + } else { + return _get(_getPrototypeOf(_class2.prototype), "parseExportDeclaration", this).call(this, node); + } + } + }, { + key: "eatExportStar", + value: function eatExportStar(node) { + if (_get(_getPrototypeOf(_class2.prototype), "eatExportStar", this).apply(this, arguments)) return true; + + if (this.isContextual("type") && this.lookahead().type === types.star) { + node.exportKind = "type"; + this.next(); + this.next(); + return true; + } -var _babelTypes = require("babel-types"); + return false; + } + }, { + key: "maybeParseExportNamespaceSpecifier", + value: function maybeParseExportNamespaceSpecifier(node) { + var pos = this.state.start; -var t = _interopRequireWildcard(_babelTypes); + var hasNamespace = _get(_getPrototypeOf(_class2.prototype), "maybeParseExportNamespaceSpecifier", this).call(this, node); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (hasNamespace && node.exportKind === "type") { + this.unexpected(pos); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return hasNamespace; + } + }, { + key: "parseClassId", + value: function parseClassId(node, isStatement, optionalId) { + _get(_getPrototypeOf(_class2.prototype), "parseClassId", this).call(this, node, isStatement, optionalId); -function VariableDeclarator() { - var id = this.get("id"); + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + } + }, { + key: "getTokenFromCode", + value: function getTokenFromCode(code) { + var next = this.input.charCodeAt(this.state.pos + 1); + + if (code === 123 && next === 124) { + return this.finishOp(types.braceBarL, 2); + } else if (this.state.inType && (code === 62 || code === 60)) { + return this.finishOp(types.relational, 1); + } else if (isIteratorStart(code, next)) { + this.state.isIterator = true; + return _get(_getPrototypeOf(_class2.prototype), "readWord", this).call(this); + } else { + return _get(_getPrototypeOf(_class2.prototype), "getTokenFromCode", this).call(this, code); + } + } + }, { + key: "isAssignable", + value: function isAssignable(node, isBinding) { + var _this8 = this; + + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + return true; + + case "ObjectExpression": + { + var _last = node.properties.length - 1; + + return node.properties.every(function (prop, i) { + return prop.type !== "ObjectMethod" && (i === _last || prop.type === "SpreadElement") && _this8.isAssignable(prop); + }); + } - if (id.isIdentifier()) { - return this.get("init").getTypeAnnotation(); - } else { - return; - } -} + case "ObjectProperty": + return this.isAssignable(node.value); -function TypeCastExpression(node) { - return node.typeAnnotation; -} + case "SpreadElement": + return this.isAssignable(node.argument); -TypeCastExpression.validParent = true; + case "ArrayExpression": + return node.elements.every(function (element) { + return _this8.isAssignable(element); + }); -function NewExpression(node) { - if (this.get("callee").isIdentifier()) { - return t.genericTypeAnnotation(node.callee); - } -} + case "AssignmentExpression": + return node.operator === "="; -function TemplateLiteral() { - return t.stringTypeAnnotation(); -} + case "ParenthesizedExpression": + case "TypeCastExpression": + return this.isAssignable(node.expression); -function UnaryExpression(node) { - var operator = node.operator; + case "MemberExpression": + case "OptionalMemberExpression": + return !isBinding; - if (operator === "void") { - return t.voidTypeAnnotation(); - } else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.stringTypeAnnotation(); - } else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.booleanTypeAnnotation(); - } -} + default: + return false; + } + } + }, { + key: "toAssignable", + value: function toAssignable(node, isBinding, contextDescription) { + if (node.type === "TypeCastExpression") { + return _get(_getPrototypeOf(_class2.prototype), "toAssignable", this).call(this, this.typeCastToParameter(node), isBinding, contextDescription); + } else { + return _get(_getPrototypeOf(_class2.prototype), "toAssignable", this).call(this, node, isBinding, contextDescription); + } + } + }, { + key: "toAssignableList", + value: function toAssignableList(exprList, isBinding, contextDescription, trailingCommaPos) { + for (var i = 0; i < exprList.length; i++) { + var expr = exprList[i]; + + if (expr && expr.type === "TypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } -function BinaryExpression(node) { - var operator = node.operator; + return _get(_getPrototypeOf(_class2.prototype), "toAssignableList", this).call(this, exprList, isBinding, contextDescription, trailingCommaPos); + } + }, { + key: "toReferencedList", + value: function toReferencedList(exprList, isParenthesizedExpr) { + for (var i = 0; i < exprList.length; i++) { + var expr = exprList[i]; + + if (expr && expr.type === "TypeCastExpression" && (!expr.extra || !expr.extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { + this.raise(expr.typeAnnotation.start, "The type cast expression is expected to be wrapped with parenthesis"); + } + } - if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.booleanTypeAnnotation(); - } else if (operator === "+") { - var right = this.get("right"); - var left = this.get("left"); + return exprList; + } + }, { + key: "checkLVal", + value: function checkLVal(expr) { + var bindingType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : BIND_NONE; + var checkClashes = arguments.length > 2 ? arguments[2] : undefined; + var contextDescription = arguments.length > 3 ? arguments[3] : undefined; + + if (expr.type !== "TypeCastExpression") { + return _get(_getPrototypeOf(_class2.prototype), "checkLVal", this).call(this, expr, bindingType, checkClashes, contextDescription); + } + } + }, { + key: "parseClassProperty", + value: function parseClassProperty(node) { + if (this.match(types.colon)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } - if (left.isBaseType("number") && right.isBaseType("number")) { - return t.numberTypeAnnotation(); - } else if (left.isBaseType("string") || right.isBaseType("string")) { - return t.stringTypeAnnotation(); - } + return _get(_getPrototypeOf(_class2.prototype), "parseClassProperty", this).call(this, node); + } + }, { + key: "parseClassPrivateProperty", + value: function parseClassPrivateProperty(node) { + if (this.match(types.colon)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } - return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]); - } -} + return _get(_getPrototypeOf(_class2.prototype), "parseClassPrivateProperty", this).call(this, node); + } + }, { + key: "isClassMethod", + value: function isClassMethod() { + return this.isRelational("<") || _get(_getPrototypeOf(_class2.prototype), "isClassMethod", this).call(this); + } + }, { + key: "isClassProperty", + value: function isClassProperty() { + return this.match(types.colon) || _get(_getPrototypeOf(_class2.prototype), "isClassProperty", this).call(this); + } + }, { + key: "isNonstaticConstructor", + value: function isNonstaticConstructor(method) { + return !this.match(types.colon) && _get(_getPrototypeOf(_class2.prototype), "isNonstaticConstructor", this).call(this, method); + } + }, { + key: "pushClassMethod", + value: function pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + if (method.variance) { + this.unexpected(method.variance.start); + } -function LogicalExpression() { - return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]); -} + delete method.variance; -function ConditionalExpression() { - return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]); -} + if (this.isRelational("<")) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } -function SequenceExpression() { - return this.get("expressions").pop().getTypeAnnotation(); -} + _get(_getPrototypeOf(_class2.prototype), "pushClassMethod", this).call(this, classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + } + }, { + key: "pushClassPrivateMethod", + value: function pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + if (method.variance) { + this.unexpected(method.variance.start); + } -function AssignmentExpression() { - return this.get("right").getTypeAnnotation(); -} + delete method.variance; -function UpdateExpression(node) { - var operator = node.operator; - if (operator === "++" || operator === "--") { - return t.numberTypeAnnotation(); - } -} + if (this.isRelational("<")) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } -function StringLiteral() { - return t.stringTypeAnnotation(); -} + _get(_getPrototypeOf(_class2.prototype), "pushClassPrivateMethod", this).call(this, classBody, method, isGenerator, isAsync); + } + }, { + key: "parseClassSuper", + value: function parseClassSuper(node) { + _get(_getPrototypeOf(_class2.prototype), "parseClassSuper", this).call(this, node); -function NumericLiteral() { - return t.numberTypeAnnotation(); -} + if (node.superClass && this.isRelational("<")) { + node.superTypeParameters = this.flowParseTypeParameterInstantiation(); + } -function BooleanLiteral() { - return t.booleanTypeAnnotation(); -} + if (this.isContextual("implements")) { + this.next(); + var implemented = node.implements = []; -function NullLiteral() { - return t.nullLiteralTypeAnnotation(); -} + do { + var _node3 = this.startNode(); -function RegExpLiteral() { - return t.genericTypeAnnotation(t.identifier("RegExp")); -} + _node3.id = this.flowParseRestrictedIdentifier(true); -function ObjectExpression() { - return t.genericTypeAnnotation(t.identifier("Object")); -} + if (this.isRelational("<")) { + _node3.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + _node3.typeParameters = null; + } -function ArrayExpression() { - return t.genericTypeAnnotation(t.identifier("Array")); -} + implemented.push(this.finishNode(_node3, "ClassImplements")); + } while (this.eat(types.comma)); + } + } + }, { + key: "parsePropertyName", + value: function parsePropertyName(node) { + var variance = this.flowParseVariance(); -function RestElement() { - return ArrayExpression(); -} + var key = _get(_getPrototypeOf(_class2.prototype), "parsePropertyName", this).call(this, node); -RestElement.validParent = true; + node.variance = variance; + return key; + } + }, { + key: "parseObjPropValue", + value: function parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc) { + if (prop.variance) { + this.unexpected(prop.variance.start); + } -function Func() { - return t.genericTypeAnnotation(t.identifier("Function")); -} + delete prop.variance; + var typeParameters; -exports.FunctionExpression = Func; -exports.ArrowFunctionExpression = Func; -exports.FunctionDeclaration = Func; -exports.ClassExpression = Func; -exports.ClassDeclaration = Func; -function CallExpression() { - return resolveCall(this.get("callee")); -} + if (this.isRelational("<")) { + typeParameters = this.flowParseTypeParameterDeclaration(); + if (!this.match(types.parenL)) this.unexpected(); + } -function TaggedTemplateExpression() { - return resolveCall(this.get("tag")); -} + _get(_getPrototypeOf(_class2.prototype), "parseObjPropValue", this).call(this, prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc); -function resolveCall(callee) { - callee = callee.resolve(); + if (typeParameters) { + (prop.value || prop).typeParameters = typeParameters; + } + } + }, { + key: "parseAssignableListItemTypes", + value: function parseAssignableListItemTypes(param) { + if (this.eat(types.question)) { + if (param.type !== "Identifier") { + this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature."); + } - if (callee.isFunction()) { - if (callee.is("async")) { - if (callee.is("generator")) { - return t.genericTypeAnnotation(t.identifier("AsyncIterator")); - } else { - return t.genericTypeAnnotation(t.identifier("Promise")); - } - } else { - if (callee.node.returnType) { - return callee.node.returnType; - } else {} - } - } -} -},{"./inferer-reference":127,"babel-types":151}],129:[function(require,module,exports){ -"use strict"; + param.optional = true; + } -exports.__esModule = true; -exports.is = undefined; + if (this.match(types.colon)) { + param.typeAnnotation = this.flowParseTypeAnnotation(); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + this.resetEndLocation(param); + return param; + } + }, { + key: "parseMaybeDefault", + value: function parseMaybeDefault(startPos, startLoc, left) { + var node = _get(_getPrototypeOf(_class2.prototype), "parseMaybeDefault", this).call(this, startPos, startLoc, left); -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`"); + } -exports.matchesPattern = matchesPattern; -exports.has = has; -exports.isStatic = isStatic; -exports.isnt = isnt; -exports.equals = equals; -exports.isNodeType = isNodeType; -exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression; -exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement; -exports.isCompletionRecord = isCompletionRecord; -exports.isStatementOrBlock = isStatementOrBlock; -exports.referencesImport = referencesImport; -exports.getSource = getSource; -exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore; -exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo; -exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions; -exports.resolve = resolve; -exports._resolve = _resolve; + return node; + } + }, { + key: "shouldParseDefaultImport", + value: function shouldParseDefaultImport(node) { + if (!hasTypeImportKind(node)) { + return _get(_getPrototypeOf(_class2.prototype), "shouldParseDefaultImport", this).call(this, node); + } -var _includes = require("lodash/includes"); + return isMaybeDefaultImport(this.state); + } + }, { + key: "parseImportSpecifierLocal", + value: function parseImportSpecifierLocal(node, specifier, type, contextDescription) { + specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true) : this.parseIdentifier(); + this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription); + node.specifiers.push(this.finishNode(specifier, type)); + } + }, { + key: "maybeParseDefaultImportSpecifier", + value: function maybeParseDefaultImportSpecifier(node) { + node.importKind = "value"; + var kind = null; + + if (this.match(types._typeof)) { + kind = "typeof"; + } else if (this.isContextual("type")) { + kind = "type"; + } -var _includes2 = _interopRequireDefault(_includes); + if (kind) { + var lh = this.lookahead(); -var _babelTypes = require("babel-types"); + if (kind === "type" && lh.type === types.star) { + this.unexpected(lh.start); + } -var t = _interopRequireWildcard(_babelTypes); + if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) { + this.next(); + node.importKind = kind; + } + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return _get(_getPrototypeOf(_class2.prototype), "maybeParseDefaultImportSpecifier", this).call(this, node); + } + }, { + key: "parseImportSpecifier", + value: function parseImportSpecifier(node) { + var specifier = this.startNode(); + var firstIdentLoc = this.state.start; + var firstIdent = this.parseIdentifier(true); + var specifierTypeKind = null; + + if (firstIdent.name === "type") { + specifierTypeKind = "type"; + } else if (firstIdent.name === "typeof") { + specifierTypeKind = "typeof"; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var isBinding = false; -function matchesPattern(pattern, allowPartial) { - if (!this.isMemberExpression()) return false; + if (this.isContextual("as") && !this.isLookaheadContextual("as")) { + var as_ident = this.parseIdentifier(true); - var parts = pattern.split("."); - var search = [this.node]; - var i = 0; + if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) { + specifier.imported = as_ident; + specifier.importKind = specifierTypeKind; + specifier.local = as_ident.__clone(); + } else { + specifier.imported = firstIdent; + specifier.importKind = null; + specifier.local = this.parseIdentifier(); + } + } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) { + specifier.imported = this.parseIdentifier(true); + specifier.importKind = specifierTypeKind; - function matches(name) { - var part = parts[i]; - return part === "*" || name === part; - } + if (this.eatContextual("as")) { + specifier.local = this.parseIdentifier(); + } else { + isBinding = true; + specifier.local = specifier.imported.__clone(); + } + } else { + isBinding = true; + specifier.imported = firstIdent; + specifier.importKind = null; + specifier.local = specifier.imported.__clone(); + } - while (search.length) { - var node = search.shift(); + var nodeIsTypeImport = hasTypeImportKind(node); + var specifierIsTypeImport = hasTypeImportKind(specifier); - if (allowPartial && i === parts.length) { - return true; - } + if (nodeIsTypeImport && specifierIsTypeImport) { + this.raise(firstIdentLoc, "The `type` and `typeof` keywords on named imports can only be used on regular " + "`import` statements. It cannot be used with `import type` or `import typeof` statements"); + } - if (t.isIdentifier(node)) { - if (!matches(node.name)) return false; - } else if (t.isLiteral(node)) { - if (!matches(node.value)) return false; - } else if (t.isMemberExpression(node)) { - if (node.computed && !t.isLiteral(node.property)) { - return false; - } else { - search.unshift(node.property); - search.unshift(node.object); - continue; - } - } else if (t.isThisExpression(node)) { - if (!matches("this")) return false; - } else { - return false; - } + if (nodeIsTypeImport || specifierIsTypeImport) { + this.checkReservedType(specifier.local.name, specifier.local.start); + } - if (++i > parts.length) { - return false; - } - } + if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) { + this.checkReservedWord(specifier.local.name, specifier.start, true, true); + } - return i === parts.length; -} + this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier"); + node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); + } + }, { + key: "parseFunctionParams", + value: function parseFunctionParams(node, allowModifiers) { + var kind = node.kind; -function has(key) { - var val = this.node && this.node[key]; - if (val && Array.isArray(val)) { - return !!val.length; - } else { - return !!val; - } -} + if (kind !== "get" && kind !== "set" && this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } -function isStatic() { - return this.scope.isStatic(this.node); -} + _get(_getPrototypeOf(_class2.prototype), "parseFunctionParams", this).call(this, node, allowModifiers); + } + }, { + key: "parseVarId", + value: function parseVarId(decl, kind) { + _get(_getPrototypeOf(_class2.prototype), "parseVarId", this).call(this, decl, kind); + + if (this.match(types.colon)) { + decl.id.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(decl.id); + } + } + }, { + key: "parseAsyncArrowFromCallExpression", + value: function parseAsyncArrowFromCallExpression(node, call) { + if (this.match(types.colon)) { + var oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + node.returnType = this.flowParseTypeAnnotation(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + } -var is = exports.is = has; + return _get(_getPrototypeOf(_class2.prototype), "parseAsyncArrowFromCallExpression", this).call(this, node, call); + } + }, { + key: "shouldParseAsyncArrow", + value: function shouldParseAsyncArrow() { + return this.match(types.colon) || _get(_getPrototypeOf(_class2.prototype), "shouldParseAsyncArrow", this).call(this); + } + }, { + key: "parseMaybeAssign", + value: function parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) { + var _this9 = this; + + var state = null; + var jsx; + + if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) { + state = this.state.clone(); + jsx = this.tryParse(function () { + return _get(_getPrototypeOf(_class2.prototype), "parseMaybeAssign", _this9).call(_this9, noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos); + }, state); + if (!jsx.error) return jsx.node; + var context = this.state.context; + + if (context[context.length - 1] === types$1.j_oTag) { + context.length -= 2; + } else if (context[context.length - 1] === types$1.j_expr) { + context.length -= 1; + } + } -function isnt(key) { - return !this.has(key); -} + if (jsx && jsx.error || this.isRelational("<")) { + state = state || this.state.clone(); + var typeParameters; + var arrow = this.tryParse(function () { + typeParameters = _this9.flowParseTypeParameterDeclaration(); -function equals(key, value) { - return this.node[key] === value; -} + var arrowExpression = _this9.forwardNoArrowParamsConversionAt(typeParameters, function () { + return _get(_getPrototypeOf(_class2.prototype), "parseMaybeAssign", _this9).call(_this9, noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos); + }); -function isNodeType(type) { - return t.isType(this.type, type); -} + arrowExpression.typeParameters = typeParameters; -function canHaveVariableDeclarationOrExpression() { - return (this.key === "init" || this.key === "left") && this.parentPath.isFor(); -} + _this9.resetStartLocationFromNode(arrowExpression, typeParameters); -function canSwapBetweenExpressionAndStatement(replacement) { - if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) { - return false; - } + return arrowExpression; + }, state); + var arrowExpression = arrow.node && arrow.node.type === "ArrowFunctionExpression" ? arrow.node : null; + if (!arrow.error && arrowExpression) return arrowExpression; - if (this.isExpression()) { - return t.isBlockStatement(replacement); - } else if (this.isBlockStatement()) { - return t.isExpression(replacement); - } + if (jsx && jsx.node) { + this.state = jsx.failState; + return jsx.node; + } - return false; -} + if (arrowExpression) { + this.state = arrow.failState; + return arrowExpression; + } -function isCompletionRecord(allowInsideFunction) { - var path = this; - var first = true; + if (jsx && jsx.thrown) throw jsx.error; + if (arrow.thrown) throw arrow.error; + throw this.raise(typeParameters.start, "Expected an arrow function after this type parameter declaration"); + } - do { - var container = path.container; + return _get(_getPrototypeOf(_class2.prototype), "parseMaybeAssign", this).call(this, noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos); + } + }, { + key: "parseArrow", + value: function parseArrow(node) { + var _this10 = this; - if (path.isFunction() && !first) { - return !!allowInsideFunction; - } + if (this.match(types.colon)) { + var result = this.tryParse(function () { + var oldNoAnonFunctionType = _this10.state.noAnonFunctionType; + _this10.state.noAnonFunctionType = true; - first = false; + var typeNode = _this10.startNode(); - if (Array.isArray(container) && path.key !== container.length - 1) { - return false; - } - } while ((path = path.parentPath) && !path.isProgram()); + var _this10$flowParseType = _this10.flowParseTypeAndPredicateInitialiser(); - return true; -} + var _this10$flowParseType2 = _slicedToArray(_this10$flowParseType, 2); -function isStatementOrBlock() { - if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) { - return false; - } else { - return (0, _includes2.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key); - } -} + typeNode.typeAnnotation = _this10$flowParseType2[0]; + node.predicate = _this10$flowParseType2[1]; + _this10.state.noAnonFunctionType = oldNoAnonFunctionType; + if (_this10.canInsertSemicolon()) _this10.unexpected(); + if (!_this10.match(types.arrow)) _this10.unexpected(); + return typeNode; + }); + if (result.thrown) return null; + if (result.error) this.state = result.failState; + node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; + } -function referencesImport(moduleSource, importName) { - if (!this.isReferencedIdentifier()) return false; + return _get(_getPrototypeOf(_class2.prototype), "parseArrow", this).call(this, node); + } + }, { + key: "shouldParseArrow", + value: function shouldParseArrow() { + return this.match(types.colon) || _get(_getPrototypeOf(_class2.prototype), "shouldParseArrow", this).call(this); + } + }, { + key: "setArrowFunctionParameters", + value: function setArrowFunctionParameters(node, params) { + if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + node.params = params; + } else { + _get(_getPrototypeOf(_class2.prototype), "setArrowFunctionParameters", this).call(this, node, params); + } + } + }, { + key: "checkParams", + value: function checkParams(node, allowDuplicates, isArrowFunction) { + if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + return; + } - var binding = this.scope.getBinding(this.node.name); - if (!binding || binding.kind !== "module") return false; + return _get(_getPrototypeOf(_class2.prototype), "checkParams", this).apply(this, arguments); + } + }, { + key: "parseParenAndDistinguishExpression", + value: function parseParenAndDistinguishExpression(canBeArrow) { + return _get(_getPrototypeOf(_class2.prototype), "parseParenAndDistinguishExpression", this).call(this, canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1); + } + }, { + key: "parseSubscripts", + value: function parseSubscripts(base, startPos, startLoc, noCalls) { + var _this11 = this; + + if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) { + this.next(); + var node = this.startNodeAt(startPos, startLoc); + node.callee = base; + node.arguments = this.parseCallExpressionArguments(types.parenR, false); + base = this.finishNode(node, "CallExpression"); + } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) { + var state = this.state.clone(); + var arrow = this.tryParse(function (abort) { + return _this11.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(); + }, state); + if (!arrow.error && !arrow.aborted) return arrow.node; + var result = this.tryParse(function () { + return _get(_getPrototypeOf(_class2.prototype), "parseSubscripts", _this11).call(_this11, base, startPos, startLoc, noCalls); + }, state); + if (result.node && !result.error) return result.node; + + if (arrow.node) { + this.state = arrow.failState; + return arrow.node; + } - var path = binding.path; - var parent = path.parentPath; - if (!parent.isImportDeclaration()) return false; + if (result.node) { + this.state = result.failState; + return result.node; + } - if (parent.node.source.value === moduleSource) { - if (!importName) return true; - } else { - return false; - } + throw arrow.error || result.error; + } - if (path.isImportDefaultSpecifier() && importName === "default") { - return true; - } + return _get(_getPrototypeOf(_class2.prototype), "parseSubscripts", this).call(this, base, startPos, startLoc, noCalls); + } + }, { + key: "parseSubscript", + value: function parseSubscript(base, startPos, startLoc, noCalls, subscriptState) { + var _this12 = this; + + if (this.match(types.questionDot) && this.isLookaheadRelational("<")) { + this.expectPlugin("optionalChaining"); + subscriptState.optionalChainMember = true; + + if (noCalls) { + subscriptState.stop = true; + return base; + } - if (path.isImportNamespaceSpecifier() && importName === "*") { - return true; - } + this.next(); + var node = this.startNodeAt(startPos, startLoc); + node.callee = base; + node.typeArguments = this.flowParseTypeParameterInstantiation(); + this.expect(types.parenL); + node.arguments = this.parseCallExpressionArguments(types.parenR, false); + node.optional = true; + return this.finishCallExpression(node, true); + } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) { + var _node4 = this.startNodeAt(startPos, startLoc); + + _node4.callee = base; + var result = this.tryParse(function () { + _node4.typeArguments = _this12.flowParseTypeParameterInstantiationCallOrNew(); + + _this12.expect(types.parenL); + + _node4.arguments = _this12.parseCallExpressionArguments(types.parenR, false); + if (subscriptState.optionalChainMember) _node4.optional = false; + return _this12.finishCallExpression(_node4, subscriptState.optionalChainMember); + }); - if (path.isImportSpecifier() && path.node.imported.name === importName) { - return true; - } + if (result.node) { + if (result.error) this.state = result.failState; + return result.node; + } + } - return false; -} + return _get(_getPrototypeOf(_class2.prototype), "parseSubscript", this).call(this, base, startPos, startLoc, noCalls, subscriptState); + } + }, { + key: "parseNewArguments", + value: function parseNewArguments(node) { + var _this13 = this; -function getSource() { - var node = this.node; - if (node.end) { - return this.hub.file.code.slice(node.start, node.end); - } else { - return ""; - } -} + var targs = null; -function willIMaybeExecuteBefore(target) { - return this._guessExecutionStatusRelativeTo(target) !== "after"; -} + if (this.shouldParseTypes() && this.isRelational("<")) { + targs = this.tryParse(function () { + return _this13.flowParseTypeParameterInstantiationCallOrNew(); + }).node; + } -function _guessExecutionStatusRelativeTo(target) { - var targetFuncParent = target.scope.getFunctionParent(); - var selfFuncParent = this.scope.getFunctionParent(); + node.typeArguments = targs; - if (targetFuncParent.node !== selfFuncParent.node) { - var status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); - if (status) { - return status; - } else { - target = targetFuncParent.path; - } - } + _get(_getPrototypeOf(_class2.prototype), "parseNewArguments", this).call(this, node); + } + }, { + key: "parseAsyncArrowWithTypeParameters", + value: function parseAsyncArrowWithTypeParameters(startPos, startLoc) { + var node = this.startNodeAt(startPos, startLoc); + this.parseFunctionParams(node); + if (!this.parseArrow(node)) return; + return this.parseArrowExpression(node, undefined, true); + } + }, { + key: "readToken_mult_modulo", + value: function readToken_mult_modulo(code) { + var next = this.input.charCodeAt(this.state.pos + 1); - var targetPaths = target.getAncestry(); - if (targetPaths.indexOf(this) >= 0) return "after"; + if (code === 42 && next === 47 && this.state.hasFlowComment) { + this.state.hasFlowComment = false; + this.state.pos += 2; + this.nextToken(); + return; + } - var selfPaths = this.getAncestry(); + _get(_getPrototypeOf(_class2.prototype), "readToken_mult_modulo", this).call(this, code); + } + }, { + key: "readToken_pipe_amp", + value: function readToken_pipe_amp(code) { + var next = this.input.charCodeAt(this.state.pos + 1); - var commonPath = void 0; - var targetIndex = void 0; - var selfIndex = void 0; - for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { - var selfPath = selfPaths[selfIndex]; - targetIndex = targetPaths.indexOf(selfPath); - if (targetIndex >= 0) { - commonPath = selfPath; - break; - } - } - if (!commonPath) { - return "before"; - } + if (code === 124 && next === 125) { + this.finishOp(types.braceBarR, 2); + return; + } - var targetRelationship = targetPaths[targetIndex - 1]; - var selfRelationship = selfPaths[selfIndex - 1]; - if (!targetRelationship || !selfRelationship) { - return "before"; - } + _get(_getPrototypeOf(_class2.prototype), "readToken_pipe_amp", this).call(this, code); + } + }, { + key: "parseTopLevel", + value: function parseTopLevel(file, program) { + var fileNode = _get(_getPrototypeOf(_class2.prototype), "parseTopLevel", this).call(this, file, program); - if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { - return targetRelationship.key > selfRelationship.key ? "before" : "after"; - } + if (this.state.hasFlowComment) { + this.raise(this.state.pos, "Unterminated flow-comment"); + } - var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); - var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); - return targetKeyPosition > selfKeyPosition ? "before" : "after"; -} + return fileNode; + } + }, { + key: "skipBlockComment", + value: function skipBlockComment() { + if (this.hasPlugin("flowComments") && this.skipFlowComment()) { + if (this.state.hasFlowComment) { + this.unexpected(null, "Cannot have a flow comment inside another flow comment"); + } -function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) { - var targetFuncPath = targetFuncParent.path; - if (!targetFuncPath.isFunctionDeclaration()) return; + this.hasFlowCommentCompletion(); + this.state.pos += this.skipFlowComment(); + this.state.hasFlowComment = true; + return; + } - var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); + if (this.state.hasFlowComment) { + var end = this.input.indexOf("*-/", this.state.pos += 2); - if (!binding.references) return "before"; + if (end === -1) { + throw this.raise(this.state.pos - 2, "Unterminated comment"); + } - var referencePaths = binding.referencePaths; + this.state.pos = end + 3; + return; + } - for (var _iterator = referencePaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + _get(_getPrototypeOf(_class2.prototype), "skipBlockComment", this).call(this); + } + }, { + key: "skipFlowComment", + value: function skipFlowComment() { + var pos = this.state.pos; + var shiftToFirstNonWhiteSpace = 2; + + while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { + shiftToFirstNonWhiteSpace++; + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + var ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); + var ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); - var path = _ref; + if (ch2 === 58 && ch3 === 58) { + return shiftToFirstNonWhiteSpace + 2; + } - if (path.key !== "callee" || !path.parentPath.isCallExpression()) { - return; - } - } + if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { + return shiftToFirstNonWhiteSpace + 12; + } - var allStatus = void 0; + if (ch2 === 58 && ch3 !== 58) { + return shiftToFirstNonWhiteSpace; + } - for (var _iterator2 = referencePaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + return false; + } + }, { + key: "hasFlowCommentCompletion", + value: function hasFlowCommentCompletion() { + var end = this.input.indexOf("*/", this.state.pos); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + if (end === -1) { + throw this.raise(this.state.pos, "Unterminated comment"); + } + } + }, { + key: "flowEnumErrorBooleanMemberNotInitialized", + value: function flowEnumErrorBooleanMemberNotInitialized(pos, _ref3) { + var enumName = _ref3.enumName, + memberName = _ref3.memberName; + this.raise(pos, "Boolean enum members need to be initialized. Use either `".concat(memberName, " = true,` ") + "or `".concat(memberName, " = false,` in enum `").concat(enumName, "`.")); + } + }, { + key: "flowEnumErrorInvalidMemberName", + value: function flowEnumErrorInvalidMemberName(pos, _ref4) { + var enumName = _ref4.enumName, + memberName = _ref4.memberName; + var suggestion = memberName[0].toUpperCase() + memberName.slice(1); + this.raise(pos, "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using " + "`".concat(memberName, "`, consider using `").concat(suggestion, "`, in enum `").concat(enumName, "`.")); + } + }, { + key: "flowEnumErrorDuplicateMemberName", + value: function flowEnumErrorDuplicateMemberName(pos, _ref5) { + var enumName = _ref5.enumName, + memberName = _ref5.memberName; + this.raise(pos, "Enum member names need to be unique, but the name `".concat(memberName, "` has already been used ") + "before in enum `".concat(enumName, "`.")); + } + }, { + key: "flowEnumErrorInconsistentMemberValues", + value: function flowEnumErrorInconsistentMemberValues(pos, _ref6) { + var enumName = _ref6.enumName; + this.raise(pos, "Enum `".concat(enumName, "` has inconsistent member initializers. Either use no initializers, or ") + "consistently use literals (either booleans, numbers, or strings) for all member initializers."); + } + }, { + key: "flowEnumErrorInvalidExplicitType", + value: function flowEnumErrorInvalidExplicitType(pos, _ref7) { + var enumName = _ref7.enumName, + suppliedType = _ref7.suppliedType; + var suggestion = "Use one of `boolean`, `number`, `string`, or `symbol` in " + "enum `".concat(enumName, "`."); + var message = suppliedType === null ? "Supplied enum type is not valid. ".concat(suggestion) : "Enum type `".concat(suppliedType, "` is not valid. ").concat(suggestion); + return this.raise(pos, message); + } + }, { + key: "flowEnumErrorInvalidMemberInitializer", + value: function flowEnumErrorInvalidMemberInitializer(pos, _ref8) { + var enumName = _ref8.enumName, + explicitType = _ref8.explicitType, + memberName = _ref8.memberName; + var message = null; + + switch (explicitType) { + case "boolean": + case "number": + case "string": + message = "Enum `".concat(enumName, "` has type `").concat(explicitType, "`, so the initializer of ") + "`".concat(memberName, "` needs to be a ").concat(explicitType, " literal."); + break; - var _path = _ref2; + case "symbol": + message = "Symbol enum members cannot be initialized. Use `".concat(memberName, ",` in ") + "enum `".concat(enumName, "`."); + break; - var childOfFunction = !!_path.find(function (path) { - return path.node === targetFuncPath.node; - }); - if (childOfFunction) continue; + default: + message = "The enum member initializer for `".concat(memberName, "` needs to be a literal (either ") + "a boolean, number, or string) in enum `".concat(enumName, "`."); + } - var status = this._guessExecutionStatusRelativeTo(_path); + return this.raise(pos, message); + } + }, { + key: "flowEnumErrorNumberMemberNotInitialized", + value: function flowEnumErrorNumberMemberNotInitialized(pos, _ref9) { + var enumName = _ref9.enumName, + memberName = _ref9.memberName; + this.raise(pos, "Number enum members need to be initialized, e.g. `".concat(memberName, " = 1` in enum `").concat(enumName, "`.")); + } + }, { + key: "flowEnumErrorStringMemberInconsistentlyInitailized", + value: function flowEnumErrorStringMemberInconsistentlyInitailized(pos, _ref10) { + var enumName = _ref10.enumName; + this.raise(pos, "String enum members need to consistently either all use initializers, or use no initializers, " + "in enum `".concat(enumName, "`.")); + } + }, { + key: "flowEnumMemberInit", + value: function flowEnumMemberInit() { + var _this14 = this; - if (allStatus) { - if (allStatus !== status) return; - } else { - allStatus = status; - } - } + var startPos = this.state.start; - return allStatus; -} + var endOfInit = function endOfInit() { + return _this14.match(types.comma) || _this14.match(types.braceR); + }; -function resolve(dangerous, resolved) { - return this._resolve(dangerous, resolved) || this; -} + switch (this.state.type) { + case types.num: + { + var _literal = this.parseLiteral(this.state.value, "NumericLiteral"); + + if (endOfInit()) { + return { + type: "number", + pos: _literal.start, + value: _literal + }; + } -function _resolve(dangerous, resolved) { - if (resolved && resolved.indexOf(this) >= 0) return; + return { + type: "invalid", + pos: startPos + }; + } - resolved = resolved || []; - resolved.push(this); + case types.string: + { + var _literal2 = this.parseLiteral(this.state.value, "StringLiteral"); - if (this.isVariableDeclarator()) { - if (this.get("id").isIdentifier()) { - return this.get("init").resolve(dangerous, resolved); - } else {} - } else if (this.isReferencedIdentifier()) { - var binding = this.scope.getBinding(this.node.name); - if (!binding) return; + if (endOfInit()) { + return { + type: "string", + pos: _literal2.start, + value: _literal2 + }; + } - if (!binding.constant) return; + return { + type: "invalid", + pos: startPos + }; + } - if (binding.kind === "module") return; + case types._true: + case types._false: + { + var _literal3 = this.parseBooleanLiteral(); + + if (endOfInit()) { + return { + type: "boolean", + pos: _literal3.start, + value: _literal3 + }; + } - if (binding.path !== this) { - var ret = binding.path.resolve(dangerous, resolved); + return { + type: "invalid", + pos: startPos + }; + } - if (this.find(function (parent) { - return parent.node === ret.node; - })) return; - return ret; - } - } else if (this.isTypeCastExpression()) { - return this.get("expression").resolve(dangerous, resolved); - } else if (dangerous && this.isMemberExpression()) { + default: + return { + type: "invalid", + pos: startPos + }; + } + } + }, { + key: "flowEnumMemberRaw", + value: function flowEnumMemberRaw() { + var pos = this.state.start; + var id = this.parseIdentifier(true); + var init = this.eat(types.eq) ? this.flowEnumMemberInit() : { + type: "none", + pos: pos + }; + return { + id: id, + init: init + }; + } + }, { + key: "flowEnumCheckExplicitTypeMismatch", + value: function flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) { + var explicitType = context.explicitType; - var targetKey = this.toComputedKey(); - if (!t.isLiteral(targetKey)) return; + if (explicitType === null) { + return; + } - var targetName = targetKey.value; + if (explicitType !== expectedType) { + this.flowEnumErrorInvalidMemberInitializer(pos, context); + } + } + }, { + key: "flowEnumMembers", + value: function flowEnumMembers(_ref11) { + var enumName = _ref11.enumName, + explicitType = _ref11.explicitType; + var seenNames = new Set(); + var members = { + booleanMembers: [], + numberMembers: [], + stringMembers: [], + defaultedMembers: [] + }; - var target = this.get("object").resolve(dangerous, resolved); + while (!this.match(types.braceR)) { + var memberNode = this.startNode(); - if (target.isObjectExpression()) { - var props = target.get("properties"); - for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + var _this$flowEnumMemberR = this.flowEnumMemberRaw(), + id = _this$flowEnumMemberR.id, + init = _this$flowEnumMemberR.init; - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } + var memberName = id.name; - var prop = _ref3; + if (memberName === "") { + continue; + } - if (!prop.isProperty()) continue; + if (/^[a-z]/.test(memberName)) { + this.flowEnumErrorInvalidMemberName(id.start, { + enumName: enumName, + memberName: memberName + }); + } - var key = prop.get("key"); + if (seenNames.has(memberName)) { + this.flowEnumErrorDuplicateMemberName(id.start, { + enumName: enumName, + memberName: memberName + }); + } - var match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); + seenNames.add(memberName); + var context = { + enumName: enumName, + explicitType: explicitType, + memberName: memberName + }; + memberNode.id = id; + + switch (init.type) { + case "boolean": + { + this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean"); + memberNode.init = init.value; + members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); + break; + } - match = match || key.isLiteral({ value: targetName }); + case "number": + { + this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number"); + memberNode.init = init.value; + members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); + break; + } - if (match) return prop.get("value").resolve(dangerous, resolved); - } - } else if (target.isArrayExpression() && !isNaN(+targetName)) { - var elems = target.get("elements"); - var elem = elems[targetName]; - if (elem) return elem.resolve(dangerous, resolved); - } - } -} -},{"babel-runtime/core-js/get-iterator":95,"babel-types":151,"lodash/includes":482}],130:[function(require,module,exports){ -"use strict"; + case "string": + { + this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string"); + memberNode.init = init.value; + members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); + break; + } -exports.__esModule = true; + case "invalid": + { + throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + case "none": + { + switch (explicitType) { + case "boolean": + this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context); + break; -var _getIterator3 = _interopRequireDefault(_getIterator2); + case "number": + this.flowEnumErrorNumberMemberNotInitialized(init.pos, context); + break; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + default: + members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); + } + } + } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + if (!this.match(types.braceR)) { + this.expect(types.comma); + } + } -var _babelTypes = require("babel-types"); + return members; + } + }, { + key: "flowEnumStringBody", + value: function flowEnumStringBody(bodyNode, initializedMembers, defaultedMembers, _ref12) { + var enumName = _ref12.enumName; + + if (initializedMembers.length === 0) { + bodyNode.members = defaultedMembers; + } else if (defaultedMembers.length === 0) { + bodyNode.members = initializedMembers; + } else if (defaultedMembers.length > initializedMembers.length) { + bodyNode.members = defaultedMembers; + + for (var _i = 0; _i < initializedMembers.length; _i++) { + var member = initializedMembers[_i]; + this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, { + enumName: enumName + }); + } + } else { + bodyNode.members = initializedMembers; -var t = _interopRequireWildcard(_babelTypes); + for (var _i2 = 0; _i2 < defaultedMembers.length; _i2++) { + var _member = defaultedMembers[_i2]; + this.flowEnumErrorStringMemberInconsistentlyInitailized(_member.start, { + enumName: enumName + }); + } + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return this.finishNode(bodyNode, "EnumStringBody"); + } + }, { + key: "flowEnumParseExplicitType", + value: function flowEnumParseExplicitType(_ref13) { + var enumName = _ref13.enumName; + + if (this.eatContextual("of")) { + if (!this.match(types.name)) { + throw this.flowEnumErrorInvalidExplicitType(this.state.start, { + enumName: enumName, + suppliedType: null + }); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var value = this.state.value; + this.next(); -var referenceVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) { - return; - } + if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { + this.flowEnumErrorInvalidExplicitType(this.state.start, { + enumName: enumName, + suppliedType: value + }); + } - if (path.node.name === "this") { - var scope = path.scope; - do { - if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) break; - } while (scope = scope.parent); - if (scope) state.breakOnScopePaths.push(scope.path); - } + return value; + } - var binding = path.scope.getBinding(path.node.name); - if (!binding) return; + return null; + } + }, { + key: "flowParseEnumDeclaration", + value: function flowParseEnumDeclaration(node) { + var _this15 = this; + + var id = this.parseIdentifier(); + node.id = id; + var enumName = id.name; + var explicitType = this.flowEnumParseExplicitType({ + enumName: enumName + }); + this.expect(types.braceL); + var bodyNode = this.startNode(); + var members = this.flowEnumMembers({ + enumName: enumName, + explicitType: explicitType + }); - if (binding !== state.scope.getBinding(path.node.name)) return; + switch (explicitType) { + case "boolean": + bodyNode.explicitType = true; + bodyNode.members = members.booleanMembers; + node.body = this.finishNode(bodyNode, "EnumBooleanBody"); + break; - state.bindings[path.node.name] = binding; - } + case "number": + bodyNode.explicitType = true; + bodyNode.members = members.numberMembers; + node.body = this.finishNode(bodyNode, "EnumNumberBody"); + break; + + case "string": + bodyNode.explicitType = true; + node.body = this.flowEnumStringBody(bodyNode, members.stringMembers, members.defaultedMembers, { + enumName: enumName + }); + break; + + case "symbol": + bodyNode.members = members.defaultedMembers; + node.body = this.finishNode(bodyNode, "EnumSymbolBody"); + break; + + default: + { + var empty = function empty() { + bodyNode.members = []; + return _this15.finishNode(bodyNode, "EnumStringBody"); + }; + + bodyNode.explicitType = false; + var boolsLen = members.booleanMembers.length; + var numsLen = members.numberMembers.length; + var strsLen = members.stringMembers.length; + var defaultedLen = members.defaultedMembers.length; + + if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { + node.body = empty(); + } else if (!boolsLen && !numsLen) { + node.body = this.flowEnumStringBody(bodyNode, members.stringMembers, members.defaultedMembers, { + enumName: enumName + }); + } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { + bodyNode.members = members.booleanMembers; + node.body = this.finishNode(bodyNode, "EnumBooleanBody"); + + for (var _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) { + var member = _members$defaultedMem[_i3]; + this.flowEnumErrorBooleanMemberNotInitialized(member.start, { + enumName: enumName, + memberName: member.id.name + }); + } + } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { + bodyNode.members = members.numberMembers; + node.body = this.finishNode(bodyNode, "EnumNumberBody"); + + for (var _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) { + var _member2 = _members$defaultedMem2[_i4]; + this.flowEnumErrorNumberMemberNotInitialized(_member2.start, { + enumName: enumName, + memberName: _member2.id.name + }); + } + } else { + node.body = empty(); + this.flowEnumErrorInconsistentMemberValues(id.start, { + enumName: enumName + }); + } + } + } + + this.expect(types.braceR); + return this.finishNode(node, "EnumDeclaration"); + } + }]); + + return _class2; + }(superClass) + ); }; -var PathHoister = function () { - function PathHoister(path, scope) { - (0, _classCallCheck3.default)(this, PathHoister); +var entities = { + quot: "\"", + amp: "&", + apos: "'", + lt: "<", + gt: ">", + nbsp: "\xA0", + iexcl: "\xA1", + cent: "\xA2", + pound: "\xA3", + curren: "\xA4", + yen: "\xA5", + brvbar: "\xA6", + sect: "\xA7", + uml: "\xA8", + copy: "\xA9", + ordf: "\xAA", + laquo: "\xAB", + not: "\xAC", + shy: "\xAD", + reg: "\xAE", + macr: "\xAF", + deg: "\xB0", + plusmn: "\xB1", + sup2: "\xB2", + sup3: "\xB3", + acute: "\xB4", + micro: "\xB5", + para: "\xB6", + middot: "\xB7", + cedil: "\xB8", + sup1: "\xB9", + ordm: "\xBA", + raquo: "\xBB", + frac14: "\xBC", + frac12: "\xBD", + frac34: "\xBE", + iquest: "\xBF", + Agrave: "\xC0", + Aacute: "\xC1", + Acirc: "\xC2", + Atilde: "\xC3", + Auml: "\xC4", + Aring: "\xC5", + AElig: "\xC6", + Ccedil: "\xC7", + Egrave: "\xC8", + Eacute: "\xC9", + Ecirc: "\xCA", + Euml: "\xCB", + Igrave: "\xCC", + Iacute: "\xCD", + Icirc: "\xCE", + Iuml: "\xCF", + ETH: "\xD0", + Ntilde: "\xD1", + Ograve: "\xD2", + Oacute: "\xD3", + Ocirc: "\xD4", + Otilde: "\xD5", + Ouml: "\xD6", + times: "\xD7", + Oslash: "\xD8", + Ugrave: "\xD9", + Uacute: "\xDA", + Ucirc: "\xDB", + Uuml: "\xDC", + Yacute: "\xDD", + THORN: "\xDE", + szlig: "\xDF", + agrave: "\xE0", + aacute: "\xE1", + acirc: "\xE2", + atilde: "\xE3", + auml: "\xE4", + aring: "\xE5", + aelig: "\xE6", + ccedil: "\xE7", + egrave: "\xE8", + eacute: "\xE9", + ecirc: "\xEA", + euml: "\xEB", + igrave: "\xEC", + iacute: "\xED", + icirc: "\xEE", + iuml: "\xEF", + eth: "\xF0", + ntilde: "\xF1", + ograve: "\xF2", + oacute: "\xF3", + ocirc: "\xF4", + otilde: "\xF5", + ouml: "\xF6", + divide: "\xF7", + oslash: "\xF8", + ugrave: "\xF9", + uacute: "\xFA", + ucirc: "\xFB", + uuml: "\xFC", + yacute: "\xFD", + thorn: "\xFE", + yuml: "\xFF", + OElig: "\u0152", + oelig: "\u0153", + Scaron: "\u0160", + scaron: "\u0161", + Yuml: "\u0178", + fnof: "\u0192", + circ: "\u02C6", + tilde: "\u02DC", + Alpha: "\u0391", + Beta: "\u0392", + Gamma: "\u0393", + Delta: "\u0394", + Epsilon: "\u0395", + Zeta: "\u0396", + Eta: "\u0397", + Theta: "\u0398", + Iota: "\u0399", + Kappa: "\u039A", + Lambda: "\u039B", + Mu: "\u039C", + Nu: "\u039D", + Xi: "\u039E", + Omicron: "\u039F", + Pi: "\u03A0", + Rho: "\u03A1", + Sigma: "\u03A3", + Tau: "\u03A4", + Upsilon: "\u03A5", + Phi: "\u03A6", + Chi: "\u03A7", + Psi: "\u03A8", + Omega: "\u03A9", + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + iota: "\u03B9", + kappa: "\u03BA", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + omicron: "\u03BF", + pi: "\u03C0", + rho: "\u03C1", + sigmaf: "\u03C2", + sigma: "\u03C3", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + thetasym: "\u03D1", + upsih: "\u03D2", + piv: "\u03D6", + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009", + zwnj: "\u200C", + zwj: "\u200D", + lrm: "\u200E", + rlm: "\u200F", + ndash: "\u2013", + mdash: "\u2014", + lsquo: "\u2018", + rsquo: "\u2019", + sbquo: "\u201A", + ldquo: "\u201C", + rdquo: "\u201D", + bdquo: "\u201E", + dagger: "\u2020", + Dagger: "\u2021", + bull: "\u2022", + hellip: "\u2026", + permil: "\u2030", + prime: "\u2032", + Prime: "\u2033", + lsaquo: "\u2039", + rsaquo: "\u203A", + oline: "\u203E", + frasl: "\u2044", + euro: "\u20AC", + image: "\u2111", + weierp: "\u2118", + real: "\u211C", + trade: "\u2122", + alefsym: "\u2135", + larr: "\u2190", + uarr: "\u2191", + rarr: "\u2192", + darr: "\u2193", + harr: "\u2194", + crarr: "\u21B5", + lArr: "\u21D0", + uArr: "\u21D1", + rArr: "\u21D2", + dArr: "\u21D3", + hArr: "\u21D4", + forall: "\u2200", + part: "\u2202", + exist: "\u2203", + empty: "\u2205", + nabla: "\u2207", + isin: "\u2208", + notin: "\u2209", + ni: "\u220B", + prod: "\u220F", + sum: "\u2211", + minus: "\u2212", + lowast: "\u2217", + radic: "\u221A", + prop: "\u221D", + infin: "\u221E", + ang: "\u2220", + and: "\u2227", + or: "\u2228", + cap: "\u2229", + cup: "\u222A", + int: "\u222B", + there4: "\u2234", + sim: "\u223C", + cong: "\u2245", + asymp: "\u2248", + ne: "\u2260", + equiv: "\u2261", + le: "\u2264", + ge: "\u2265", + sub: "\u2282", + sup: "\u2283", + nsub: "\u2284", + sube: "\u2286", + supe: "\u2287", + oplus: "\u2295", + otimes: "\u2297", + perp: "\u22A5", + sdot: "\u22C5", + lceil: "\u2308", + rceil: "\u2309", + lfloor: "\u230A", + rfloor: "\u230B", + lang: "\u2329", + rang: "\u232A", + loz: "\u25CA", + spades: "\u2660", + clubs: "\u2663", + hearts: "\u2665", + diams: "\u2666" +}; +var HEX_NUMBER = /^[\da-fA-F]+$/; +var DECIMAL_NUMBER = /^\d+$/; +types$1.j_oTag = new TokContext("...", true, true); +types.jsxName = new TokenType("jsxName"); +types.jsxText = new TokenType("jsxText", { + beforeExpr: true +}); +types.jsxTagStart = new TokenType("jsxTagStart", { + startsExpr: true +}); +types.jsxTagEnd = new TokenType("jsxTagEnd"); - this.breakOnScopePaths = []; +types.jsxTagStart.updateContext = function () { + this.state.context.push(types$1.j_expr); + this.state.context.push(types$1.j_oTag); + this.state.exprAllowed = false; +}; - this.bindings = {}; +types.jsxTagEnd.updateContext = function (prevType) { + var out = this.state.context.pop(); - this.scopes = []; + if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) { + this.state.context.pop(); + this.state.exprAllowed = this.curContext() === types$1.j_expr; + } else { + this.state.exprAllowed = true; + } +}; - this.scope = scope; - this.path = path; +function isFragment(object) { + return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; +} - this.attachAfter = false; +function getQualifiedJSXName(object) { + if (object.type === "JSXIdentifier") { + return object.name; } - PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) { - for (var key in this.bindings) { - var binding = this.bindings[key]; - if (!scope.bindingIdentifierEquals(key, binding.identifier)) { - return false; - } - } + if (object.type === "JSXNamespacedName") { + return object.namespace.name + ":" + object.name.name; + } - return true; - }; + if (object.type === "JSXMemberExpression") { + return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); + } - PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() { - var scope = this.path.scope; - do { - if (this.isCompatibleScope(scope)) { - this.scopes.push(scope); - } else { - break; - } + throw new Error("Node had unexpected type: " + object.type); +} - if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { - break; - } - } while (scope = scope.parent); - }; +var jsx = function jsx(superClass) { + return ( + /*#__PURE__*/ + function (_superClass3) { + _inherits(_class3, _superClass3); - PathHoister.prototype.getAttachmentPath = function getAttachmentPath() { - var path = this._getAttachmentPath(); - if (!path) return; + function _class3() { + _classCallCheck(this, _class3); - var targetScope = path.scope; + return _possibleConstructorReturn(this, _getPrototypeOf(_class3).apply(this, arguments)); + } - if (targetScope.path === path) { - targetScope = path.scope.parent; - } + _createClass(_class3, [{ + key: "jsxReadToken", + value: function jsxReadToken() { + var out = ""; + var chunkStart = this.state.pos; - if (targetScope.path.isProgram() || targetScope.path.isFunction()) { - for (var name in this.bindings) { - if (!targetScope.hasOwnBinding(name)) continue; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(this.state.start, "Unterminated JSX contents"); + } - var binding = this.bindings[name]; + var ch = this.input.charCodeAt(this.state.pos); - if (binding.kind === "param") continue; + switch (ch) { + case 60: + case 123: + if (this.state.pos === this.state.start) { + if (ch === 60 && this.state.exprAllowed) { + ++this.state.pos; + return this.finishToken(types.jsxTagStart); + } - if (this.getAttachmentParentForPath(binding.path).key > path.key) { - this.attachAfter = true; - path = binding.path; + return _get(_getPrototypeOf(_class3.prototype), "getTokenFromCode", this).call(this, ch); + } - for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + out += this.input.slice(chunkStart, this.state.pos); + return this.finishToken(types.jsxText, out); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + case 38: + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + break; - var violationPath = _ref; + default: + if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(true); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } - if (this.getAttachmentParentForPath(violationPath).key > path.key) { - path = violationPath; } } } - } - } + }, { + key: "jsxReadNewLine", + value: function jsxReadNewLine(normalizeCRLF) { + var ch = this.input.charCodeAt(this.state.pos); + var out; + ++this.state.pos; - if (path.parentPath.isExportDeclaration()) { - path = path.parentPath; - } - - return path; - }; + if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + out = normalizeCRLF ? "\n" : "\r\n"; + } else { + out = String.fromCharCode(ch); + } - PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() { - var scopes = this.scopes; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + return out; + } + }, { + key: "jsxReadString", + value: function jsxReadString(quote) { + var out = ""; + var chunkStart = ++this.state.pos; + + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(this.state.start, "Unterminated string constant"); + } - var scope = scopes.pop(); + var ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; + + if (ch === 38) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(false); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } - if (!scope) return; + out += this.input.slice(chunkStart, this.state.pos++); + return this.finishToken(types.string, out); + } + }, { + key: "jsxReadEntity", + value: function jsxReadEntity() { + var str = ""; + var count = 0; + var entity; + var ch = this.input[this.state.pos]; + var startPos = ++this.state.pos; + + while (this.state.pos < this.length && count++ < 10) { + ch = this.input[this.state.pos++]; + + if (ch === ";") { + if (str[0] === "#") { + if (str[1] === "x") { + str = str.substr(2); + + if (HEX_NUMBER.test(str)) { + entity = String.fromCodePoint(parseInt(str, 16)); + } + } else { + str = str.substr(1); - if (scope.path.isFunction()) { - if (this.hasOwnParamBindings(scope)) { - if (this.scope === scope) return; + if (DECIMAL_NUMBER.test(str)) { + entity = String.fromCodePoint(parseInt(str, 10)); + } + } + } else { + entity = entities[str]; + } - return scope.path.get("body").get("body")[0]; - } else { - return this.getNextScopeAttachmentParent(); - } - } else if (scope.path.isProgram()) { - return this.getNextScopeAttachmentParent(); - } - }; + break; + } - PathHoister.prototype.getNextScopeAttachmentParent = function getNextScopeAttachmentParent() { - var scope = this.scopes.pop(); - if (scope) return this.getAttachmentParentForPath(scope.path); - }; + str += ch; + } - PathHoister.prototype.getAttachmentParentForPath = function getAttachmentParentForPath(path) { - do { - if (!path.parentPath || Array.isArray(path.container) && path.isStatement() || path.isVariableDeclarator() && path.parentPath.node !== null && path.parentPath.node.declarations.length > 1) return path; - } while (path = path.parentPath); - }; + if (!entity) { + this.state.pos = startPos; + return "&"; + } - PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) { - for (var name in this.bindings) { - if (!scope.hasOwnBinding(name)) continue; + return entity; + } + }, { + key: "jsxReadWord", + value: function jsxReadWord() { + var ch; + var start = this.state.pos; - var binding = this.bindings[name]; + do { + ch = this.input.charCodeAt(++this.state.pos); + } while (isIdentifierChar(ch) || ch === 45); - if (binding.kind === "param" && binding.constant) return true; - } - return false; - }; + return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos)); + } + }, { + key: "jsxParseIdentifier", + value: function jsxParseIdentifier() { + var node = this.startNode(); + + if (this.match(types.jsxName)) { + node.name = this.state.value; + } else if (this.state.type.keyword) { + node.name = this.state.type.keyword; + } else { + this.unexpected(); + } - PathHoister.prototype.run = function run() { - var node = this.path.node; - if (node._hoisted) return; - node._hoisted = true; + this.next(); + return this.finishNode(node, "JSXIdentifier"); + } + }, { + key: "jsxParseNamespacedName", + value: function jsxParseNamespacedName() { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var name = this.jsxParseIdentifier(); + if (!this.eat(types.colon)) return name; + var node = this.startNodeAt(startPos, startLoc); + node.namespace = name; + node.name = this.jsxParseIdentifier(); + return this.finishNode(node, "JSXNamespacedName"); + } + }, { + key: "jsxParseElementName", + value: function jsxParseElementName() { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var node = this.jsxParseNamespacedName(); + + if (node.type === "JSXNamespacedName") { + return node; + } - this.path.traverse(referenceVisitor, this); + while (this.eat(types.dot)) { + var newNode = this.startNodeAt(startPos, startLoc); + newNode.object = node; + newNode.property = this.jsxParseIdentifier(); + node = this.finishNode(newNode, "JSXMemberExpression"); + } - this.getCompatibleScopes(); + return node; + } + }, { + key: "jsxParseAttributeValue", + value: function jsxParseAttributeValue() { + var node; + + switch (this.state.type) { + case types.braceL: + node = this.startNode(); + this.next(); + node = this.jsxParseExpressionContainer(node); + + if (node.expression.type === "JSXEmptyExpression") { + this.raise(node.start, "JSX attributes must only be assigned a non-empty expression"); + } - var attachTo = this.getAttachmentPath(); - if (!attachTo) return; + return node; - if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; + case types.jsxTagStart: + case types.string: + return this.parseExprAtom(); - var uid = attachTo.scope.generateUidIdentifier("ref"); - var declarator = t.variableDeclarator(uid, this.path.node); + default: + throw this.raise(this.state.start, "JSX value should be either an expression or a quoted JSX text"); + } + } + }, { + key: "jsxParseEmptyExpression", + value: function jsxParseEmptyExpression() { + var node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc); + } + }, { + key: "jsxParseSpreadChild", + value: function jsxParseSpreadChild(node) { + this.next(); + node.expression = this.parseExpression(); + this.expect(types.braceR); + return this.finishNode(node, "JSXSpreadChild"); + } + }, { + key: "jsxParseExpressionContainer", + value: function jsxParseExpressionContainer(node) { + if (this.match(types.braceR)) { + node.expression = this.jsxParseEmptyExpression(); + } else { + node.expression = this.parseExpression(); + } - var insertFn = this.attachAfter ? "insertAfter" : "insertBefore"; - attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]); + this.expect(types.braceR); + return this.finishNode(node, "JSXExpressionContainer"); + } + }, { + key: "jsxParseAttribute", + value: function jsxParseAttribute() { + var node = this.startNode(); + + if (this.eat(types.braceL)) { + this.expect(types.ellipsis); + node.argument = this.parseMaybeAssign(); + this.expect(types.braceR); + return this.finishNode(node, "JSXSpreadAttribute"); + } - var parent = this.path.parentPath; - if (parent.isJSXElement() && this.path.container === parent.node.children) { - uid = t.JSXExpressionContainer(uid); - } + node.name = this.jsxParseNamespacedName(); + node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null; + return this.finishNode(node, "JSXAttribute"); + } + }, { + key: "jsxParseOpeningElementAt", + value: function jsxParseOpeningElementAt(startPos, startLoc) { + var node = this.startNodeAt(startPos, startLoc); + + if (this.match(types.jsxTagEnd)) { + this.expect(types.jsxTagEnd); + return this.finishNode(node, "JSXOpeningFragment"); + } - this.path.replaceWith(uid); - }; + node.name = this.jsxParseElementName(); + return this.jsxParseOpeningElementAfterName(node); + } + }, { + key: "jsxParseOpeningElementAfterName", + value: function jsxParseOpeningElementAfterName(node) { + var attributes = []; - return PathHoister; -}(); + while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) { + attributes.push(this.jsxParseAttribute()); + } -exports.default = PathHoister; -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/classCallCheck":109,"babel-types":151}],131:[function(require,module,exports){ -"use strict"; + node.attributes = attributes; + node.selfClosing = this.eat(types.slash); + this.expect(types.jsxTagEnd); + return this.finishNode(node, "JSXOpeningElement"); + } + }, { + key: "jsxParseClosingElementAt", + value: function jsxParseClosingElementAt(startPos, startLoc) { + var node = this.startNodeAt(startPos, startLoc); + + if (this.match(types.jsxTagEnd)) { + this.expect(types.jsxTagEnd); + return this.finishNode(node, "JSXClosingFragment"); + } -exports.__esModule = true; -var hooks = exports.hooks = [function (self, parent) { - var removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement(); + node.name = this.jsxParseElementName(); + this.expect(types.jsxTagEnd); + return this.finishNode(node, "JSXClosingElement"); + } + }, { + key: "jsxParseElementAt", + value: function jsxParseElementAt(startPos, startLoc) { + var node = this.startNodeAt(startPos, startLoc); + var children = []; + var openingElement = this.jsxParseOpeningElementAt(startPos, startLoc); + var closingElement = null; + + if (!openingElement.selfClosing) { + contents: for (;;) { + switch (this.state.type) { + case types.jsxTagStart: + startPos = this.state.start; + startLoc = this.state.startLoc; + this.next(); + + if (this.eat(types.slash)) { + closingElement = this.jsxParseClosingElementAt(startPos, startLoc); + break contents; + } - if (removeParent) { - parent.remove(); - return true; - } -}, function (self, parent) { - if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { - parent.replaceWith(parent.node.expressions[0]); - return true; - } -}, function (self, parent) { - if (parent.isBinary()) { - if (self.key === "left") { - parent.replaceWith(parent.node.right); - } else { - parent.replaceWith(parent.node.left); - } - return true; - } -}, function (self, parent) { - if (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate") || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) { - self.replaceWith({ - type: "BlockStatement", - body: [] - }); - return true; - } -}]; -},{}],132:[function(require,module,exports){ -"use strict"; + children.push(this.jsxParseElementAt(startPos, startLoc)); + break; -exports.__esModule = true; -exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = undefined; + case types.jsxText: + children.push(this.parseExprAtom()); + break; -var _babelTypes = require("babel-types"); + case types.braceL: + { + var _node5 = this.startNode(); -var t = _interopRequireWildcard(_babelTypes); + this.next(); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (this.match(types.ellipsis)) { + children.push(this.jsxParseSpreadChild(_node5)); + } else { + children.push(this.jsxParseExpressionContainer(_node5)); + } -var ReferencedIdentifier = exports.ReferencedIdentifier = { - types: ["Identifier", "JSXIdentifier"], - checkPath: function checkPath(_ref, opts) { - var node = _ref.node, - parent = _ref.parent; + break; + } - if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) { - if (t.isJSXIdentifier(node, opts)) { - if (_babelTypes.react.isCompatTag(node.name)) return false; - } else { - return false; - } - } + default: + throw this.unexpected(); + } + } - return t.isReferenced(node, parent); - } -}; + if (isFragment(openingElement) && !isFragment(closingElement)) { + this.raise(closingElement.start, "Expected corresponding JSX closing tag for <>"); + } else if (!isFragment(openingElement) && isFragment(closingElement)) { + this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">"); + } else if (!isFragment(openingElement) && !isFragment(closingElement)) { + if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { + this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">"); + } + } + } -var ReferencedMemberExpression = exports.ReferencedMemberExpression = { - types: ["MemberExpression"], - checkPath: function checkPath(_ref2) { - var node = _ref2.node, - parent = _ref2.parent; + if (isFragment(openingElement)) { + node.openingFragment = openingElement; + node.closingFragment = closingElement; + } else { + node.openingElement = openingElement; + node.closingElement = closingElement; + } - return t.isMemberExpression(node) && t.isReferenced(node, parent); - } -}; + node.children = children; -var BindingIdentifier = exports.BindingIdentifier = { - types: ["Identifier"], - checkPath: function checkPath(_ref3) { - var node = _ref3.node, - parent = _ref3.parent; + if (this.isRelational("<")) { + throw this.raise(this.state.start, "Adjacent JSX elements must be wrapped in an enclosing tag. " + "Did you want a JSX fragment <>...?"); + } - return t.isIdentifier(node) && t.isBinding(node, parent); - } -}; + return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); + } + }, { + key: "jsxParseElement", + value: function jsxParseElement() { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + this.next(); + return this.jsxParseElementAt(startPos, startLoc); + } + }, { + key: "parseExprAtom", + value: function parseExprAtom(refShortHandDefaultPos) { + if (this.match(types.jsxText)) { + return this.parseLiteral(this.state.value, "JSXText"); + } else if (this.match(types.jsxTagStart)) { + return this.jsxParseElement(); + } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) { + this.finishToken(types.jsxTagStart); + return this.jsxParseElement(); + } else { + return _get(_getPrototypeOf(_class3.prototype), "parseExprAtom", this).call(this, refShortHandDefaultPos); + } + } + }, { + key: "getTokenFromCode", + value: function getTokenFromCode(code) { + if (this.state.inPropertyName) return _get(_getPrototypeOf(_class3.prototype), "getTokenFromCode", this).call(this, code); + var context = this.curContext(); + + if (context === types$1.j_expr) { + return this.jsxReadToken(); + } -var Statement = exports.Statement = { - types: ["Statement"], - checkPath: function checkPath(_ref4) { - var node = _ref4.node, - parent = _ref4.parent; + if (context === types$1.j_oTag || context === types$1.j_cTag) { + if (isIdentifierStart(code)) { + return this.jsxReadWord(); + } - if (t.isStatement(node)) { - if (t.isVariableDeclaration(node)) { - if (t.isForXStatement(parent, { left: node })) return false; - if (t.isForStatement(parent, { init: node })) return false; - } + if (code === 62) { + ++this.state.pos; + return this.finishToken(types.jsxTagEnd); + } - return true; - } else { - return false; - } - } -}; + if ((code === 34 || code === 39) && context === types$1.j_oTag) { + return this.jsxReadString(code); + } + } -var Expression = exports.Expression = { - types: ["Expression"], - checkPath: function checkPath(path) { - if (path.isIdentifier()) { - return path.isReferencedIdentifier(); - } else { - return t.isExpression(path.node); - } - } -}; + if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) { + ++this.state.pos; + return this.finishToken(types.jsxTagStart); + } -var Scope = exports.Scope = { - types: ["Scopable"], - checkPath: function checkPath(path) { - return t.isScope(path.node, path.parent); - } -}; + return _get(_getPrototypeOf(_class3.prototype), "getTokenFromCode", this).call(this, code); + } + }, { + key: "updateContext", + value: function updateContext(prevType) { + if (this.match(types.braceL)) { + var curContext = this.curContext(); + + if (curContext === types$1.j_oTag) { + this.state.context.push(types$1.braceExpression); + } else if (curContext === types$1.j_expr) { + this.state.context.push(types$1.templateQuasi); + } else { + _get(_getPrototypeOf(_class3.prototype), "updateContext", this).call(this, prevType); + } -var Referenced = exports.Referenced = { - checkPath: function checkPath(path) { - return t.isReferenced(path.node, path.parent); - } -}; + this.state.exprAllowed = true; + } else if (this.match(types.slash) && prevType === types.jsxTagStart) { + this.state.context.length -= 2; + this.state.context.push(types$1.j_cTag); + this.state.exprAllowed = false; + } else { + return _get(_getPrototypeOf(_class3.prototype), "updateContext", this).call(this, prevType); + } + } + }]); -var BlockScoped = exports.BlockScoped = { - checkPath: function checkPath(path) { - return t.isBlockScoped(path.node); - } + return _class3; + }(superClass) + ); }; -var Var = exports.Var = { - types: ["VariableDeclaration"], - checkPath: function checkPath(path) { - return t.isVar(path.node); - } -}; +var Scope = function Scope(flags) { + _classCallCheck(this, Scope); -var User = exports.User = { - checkPath: function checkPath(path) { - return path.node && !!path.node.loc; - } + this.var = []; + this.lexical = []; + this.functions = []; + this.flags = flags; }; -var Generated = exports.Generated = { - checkPath: function checkPath(path) { - return !path.isUser(); - } -}; +var ScopeHandler = +/*#__PURE__*/ +function () { + function ScopeHandler(raise, inModule) { + _classCallCheck(this, ScopeHandler); -var Pure = exports.Pure = { - checkPath: function checkPath(path, opts) { - return path.scope.isPure(path.node, opts); + this.scopeStack = []; + this.undefinedExports = new Map(); + this.raise = raise; + this.inModule = inModule; } -}; - -var Flow = exports.Flow = { - types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], - checkPath: function checkPath(_ref5) { - var node = _ref5.node; - if (t.isFlow(node)) { - return true; - } else if (t.isImportDeclaration(node)) { - return node.importKind === "type" || node.importKind === "typeof"; - } else if (t.isExportDeclaration(node)) { - return node.exportKind === "type"; - } else if (t.isImportSpecifier(node)) { - return node.importKind === "type" || node.importKind === "typeof"; - } else { - return false; + _createClass(ScopeHandler, [{ + key: "createScope", + value: function createScope(flags) { + return new Scope(flags); } - } -}; -},{"babel-types":151}],133:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); + }, { + key: "enter", + value: function enter(flags) { + this.scopeStack.push(this.createScope(flags)); + } + }, { + key: "exit", + value: function exit() { + this.scopeStack.pop(); + } + }, { + key: "treatFunctionsAsVarInScope", + value: function treatFunctionsAsVarInScope(scope) { + return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM); + } + }, { + key: "declareName", + value: function declareName(name, bindingType, pos) { + var scope = this.currentScope(); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) { + this.checkRedeclarationInScope(scope, name, bindingType, pos); -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (bindingType & BIND_SCOPE_FUNCTION) { + scope.functions.push(name); + } else { + scope.lexical.push(name); + } -exports.insertBefore = insertBefore; -exports._containerInsert = _containerInsert; -exports._containerInsertBefore = _containerInsertBefore; -exports._containerInsertAfter = _containerInsertAfter; -exports._maybePopFromStatements = _maybePopFromStatements; -exports.insertAfter = insertAfter; -exports.updateSiblingKeys = updateSiblingKeys; -exports._verifyNodeList = _verifyNodeList; -exports.unshiftContainer = unshiftContainer; -exports.pushContainer = pushContainer; -exports.hoist = hoist; + if (bindingType & BIND_SCOPE_LEXICAL) { + this.maybeExportDefined(scope, name); + } + } else if (bindingType & BIND_SCOPE_VAR) { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + scope = this.scopeStack[i]; + this.checkRedeclarationInScope(scope, name, bindingType, pos); + scope.var.push(name); + this.maybeExportDefined(scope, name); + if (scope.flags & SCOPE_VAR) break; + } + } -var _cache = require("../cache"); + if (this.inModule && scope.flags & SCOPE_PROGRAM) { + this.undefinedExports.delete(name); + } + } + }, { + key: "maybeExportDefined", + value: function maybeExportDefined(scope, name) { + if (this.inModule && scope.flags & SCOPE_PROGRAM) { + this.undefinedExports.delete(name); + } + } + }, { + key: "checkRedeclarationInScope", + value: function checkRedeclarationInScope(scope, name, bindingType, pos) { + if (this.isRedeclaredInScope(scope, name, bindingType)) { + this.raise(pos, "Identifier '".concat(name, "' has already been declared")); + } + } + }, { + key: "isRedeclaredInScope", + value: function isRedeclaredInScope(scope, name, bindingType) { + if (!(bindingType & BIND_KIND_VALUE)) return false; -var _hoister = require("./lib/hoister"); + if (bindingType & BIND_SCOPE_LEXICAL) { + return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + } -var _hoister2 = _interopRequireDefault(_hoister); + if (bindingType & BIND_SCOPE_FUNCTION) { + return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1; + } -var _index = require("./index"); + return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1; + } + }, { + key: "checkLocalExport", + value: function checkLocalExport(id) { + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1 && this.scopeStack[0].functions.indexOf(id.name) === -1) { + this.undefinedExports.set(id.name, id.start); + } + } + }, { + key: "currentScope", + value: function currentScope() { + return this.scopeStack[this.scopeStack.length - 1]; + } + }, { + key: "currentVarScope", + value: function currentVarScope() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; -var _index2 = _interopRequireDefault(_index); + if (scope.flags & SCOPE_VAR) { + return scope; + } + } + } + }, { + key: "currentThisScope", + value: function currentThisScope() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; -var _babelTypes = require("babel-types"); + if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) { + return scope; + } + } + } + }, { + key: "inFunction", + get: function get() { + return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0; + } + }, { + key: "inGenerator", + get: function get() { + return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0; + } + }, { + key: "inAsync", + get: function get() { + return (this.currentVarScope().flags & SCOPE_ASYNC) > 0; + } + }, { + key: "allowSuper", + get: function get() { + return (this.currentThisScope().flags & SCOPE_SUPER) > 0; + } + }, { + key: "allowDirectSuper", + get: function get() { + return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0; + } + }, { + key: "inNonArrowFunction", + get: function get() { + return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0; + } + }, { + key: "treatFunctionsAsVar", + get: function get() { + return this.treatFunctionsAsVarInScope(this.currentScope()); + } + }]); -var t = _interopRequireWildcard(_babelTypes); + return ScopeHandler; +}(); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var TypeScriptScope = +/*#__PURE__*/ +function (_Scope) { + _inherits(TypeScriptScope, _Scope); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function TypeScriptScope() { + var _getPrototypeOf2; -function insertBefore(nodes) { - this._assertUnremoved(); + var _this16; - nodes = this._verifyNodeList(nodes); + _classCallCheck(this, TypeScriptScope); - if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { - return this.parentPath.insertBefore(nodes); - } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { - if (this.node) nodes.push(this.node); - this.replaceExpressionWithStatements(nodes); - } else { - this._maybePopFromStatements(nodes); - if (Array.isArray(this.container)) { - return this._containerInsertBefore(nodes); - } else if (this.isStatementOrBlock()) { - if (this.node) nodes.push(this.node); - this._replaceWith(t.blockStatement(nodes)); - } else { - throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - } - return [this]; -} - -function _containerInsert(from, nodes) { - this.updateSiblingKeys(from, nodes.length); + _this16 = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(TypeScriptScope)).call.apply(_getPrototypeOf2, [this].concat(args))); + _this16.types = []; + _this16.enums = []; + _this16.constEnums = []; + _this16.classes = []; + _this16.exportOnlyBindings = []; + return _this16; + } - var paths = []; + return TypeScriptScope; +}(Scope); - for (var i = 0; i < nodes.length; i++) { - var to = from + i; - var node = nodes[i]; - this.container.splice(to, 0, node); +var TypeScriptScopeHandler = +/*#__PURE__*/ +function (_ScopeHandler) { + _inherits(TypeScriptScopeHandler, _ScopeHandler); - if (this.context) { - var path = this.context.create(this.parent, this.container, to, this.listKey); + function TypeScriptScopeHandler() { + _classCallCheck(this, TypeScriptScopeHandler); - if (this.context.queue) path.pushContext(this.context); - paths.push(path); - } else { - paths.push(_index2.default.get({ - parentPath: this.parentPath, - parent: this.parent, - container: this.container, - listKey: this.listKey, - key: to - })); - } + return _possibleConstructorReturn(this, _getPrototypeOf(TypeScriptScopeHandler).apply(this, arguments)); } - var contexts = this._getQueueContexts(); - - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + _createClass(TypeScriptScopeHandler, [{ + key: "createScope", + value: function createScope(flags) { + return new TypeScriptScope(flags); } + }, { + key: "declareName", + value: function declareName(name, bindingType, pos) { + var scope = this.currentScope(); - var _path = _ref; + if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) { + this.maybeExportDefined(scope, name); + scope.exportOnlyBindings.push(name); + return; + } - _path.setScope(); - _path.debug(function () { - return "Inserted."; - }); + _get(_getPrototypeOf(TypeScriptScopeHandler.prototype), "declareName", this).apply(this, arguments); - for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + if (bindingType & BIND_KIND_TYPE) { + if (!(bindingType & BIND_KIND_VALUE)) { + this.checkRedeclarationInScope(scope, name, bindingType, pos); + this.maybeExportDefined(scope, name); + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + scope.types.push(name); } - var context = _ref2; - - context.maybeQueue(_path, true); + if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name); + if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name); + if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name); } - } - - return paths; -} - -function _containerInsertBefore(nodes) { - return this._containerInsert(this.key, nodes); -} - -function _containerInsertAfter(nodes) { - return this._containerInsert(this.key + 1, nodes); -} - -function _maybePopFromStatements(nodes) { - var last = nodes[nodes.length - 1]; - var isIdentifier = t.isIdentifier(last) || t.isExpressionStatement(last) && t.isIdentifier(last.expression); + }, { + key: "isRedeclaredInScope", + value: function isRedeclaredInScope(scope, name, bindingType) { + if (scope.enums.indexOf(name) > -1) { + if (bindingType & BIND_FLAGS_TS_ENUM) { + var isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM); + var wasConst = scope.constEnums.indexOf(name) > -1; + return isConst !== wasConst; + } - if (isIdentifier && !this.isCompletionRecord()) { - nodes.pop(); - } -} + return true; + } -function insertAfter(nodes) { - this._assertUnremoved(); + if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) { + if (scope.lexical.indexOf(name) > -1) { + return !!(bindingType & BIND_KIND_VALUE); + } else { + return false; + } + } - nodes = this._verifyNodeList(nodes); + if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) { + return true; + } - if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { - return this.parentPath.insertAfter(nodes); - } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { - if (this.node) { - var temp = this.scope.generateDeclaredUidIdentifier(); - nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node))); - nodes.push(t.expressionStatement(temp)); + return _get(_getPrototypeOf(TypeScriptScopeHandler.prototype), "isRedeclaredInScope", this).apply(this, arguments); } - this.replaceExpressionWithStatements(nodes); - } else { - this._maybePopFromStatements(nodes); - if (Array.isArray(this.container)) { - return this._containerInsertAfter(nodes); - } else if (this.isStatementOrBlock()) { - if (this.node) nodes.unshift(this.node); - this._replaceWith(t.blockStatement(nodes)); - } else { - throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); + }, { + key: "checkLocalExport", + value: function checkLocalExport(id) { + if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) { + _get(_getPrototypeOf(TypeScriptScopeHandler.prototype), "checkLocalExport", this).call(this, id); + } } - } - - return [this]; -} + }]); -function updateSiblingKeys(fromIndex, incrementBy) { - if (!this.parent) return; + return TypeScriptScopeHandler; +}(ScopeHandler); - var paths = _cache.path.get(this.parent); - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (path.key >= fromIndex) { - path.key += incrementBy; - } +function nonNull(x) { + if (x == null) { + throw new Error("Unexpected ".concat(x, " value.")); } -} -function _verifyNodeList(nodes) { - if (!nodes) { - return []; - } + return x; +} - if (nodes.constructor !== Array) { - nodes = [nodes]; +function assert(x) { + if (!x) { + throw new Error("Assert fail"); } +} - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - var msg = void 0; - - if (!node) { - msg = "has falsy node"; - } else if ((typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node)) !== "object") { - msg = "contains a non-object node"; - } else if (!node.type) { - msg = "without a type"; - } else if (node instanceof _index2.default) { - msg = "has a NodePath when it expected a raw object"; - } +function keywordTypeFromName(value) { + switch (value) { + case "any": + return "TSAnyKeyword"; - if (msg) { - var type = Array.isArray(node) ? "array" : typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node); - throw new Error("Node list " + msg + " with the index of " + i + " and type of " + type); - } - } + case "boolean": + return "TSBooleanKeyword"; - return nodes; -} + case "bigint": + return "TSBigIntKeyword"; -function unshiftContainer(listKey, nodes) { - this._assertUnremoved(); + case "never": + return "TSNeverKeyword"; - nodes = this._verifyNodeList(nodes); + case "number": + return "TSNumberKeyword"; - var path = _index2.default.get({ - parentPath: this, - parent: this.node, - container: this.node[listKey], - listKey: listKey, - key: 0 - }); + case "object": + return "TSObjectKeyword"; - return path.insertBefore(nodes); -} + case "string": + return "TSStringKeyword"; -function pushContainer(listKey, nodes) { - this._assertUnremoved(); + case "symbol": + return "TSSymbolKeyword"; - nodes = this._verifyNodeList(nodes); + case "undefined": + return "TSUndefinedKeyword"; - var container = this.node[listKey]; - var path = _index2.default.get({ - parentPath: this, - parent: this.node, - container: container, - listKey: listKey, - key: container.length - }); + case "unknown": + return "TSUnknownKeyword"; - return path.replaceWithMultiple(nodes); + default: + return undefined; + } } -function hoist() { - var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.scope; - - var hoister = new _hoister2.default(this, scope); - return hoister.run(); -} -},{"../cache":115,"./index":125,"./lib/hoister":130,"babel-runtime/core-js/get-iterator":95,"babel-runtime/helpers/typeof":113,"babel-types":151}],134:[function(require,module,exports){ -"use strict"; +var typescript = function typescript(superClass) { + return ( + /*#__PURE__*/ + function (_superClass4) { + _inherits(_class4, _superClass4); -exports.__esModule = true; + function _class4() { + _classCallCheck(this, _class4); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + return _possibleConstructorReturn(this, _getPrototypeOf(_class4).apply(this, arguments)); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + _createClass(_class4, [{ + key: "getScopeHandler", + value: function getScopeHandler() { + return TypeScriptScopeHandler; + } + }, { + key: "tsIsIdentifier", + value: function tsIsIdentifier() { + return this.match(types.name); + } + }, { + key: "tsNextTokenCanFollowModifier", + value: function tsNextTokenCanFollowModifier() { + this.next(); + return !this.hasPrecedingLineBreak() && !this.match(types.parenL) && !this.match(types.parenR) && !this.match(types.colon) && !this.match(types.eq) && !this.match(types.question) && !this.match(types.bang); + } + }, { + key: "tsParseModifier", + value: function tsParseModifier(allowedModifiers) { + if (!this.match(types.name)) { + return undefined; + } -exports.remove = remove; -exports._callRemovalHooks = _callRemovalHooks; -exports._remove = _remove; -exports._markRemoved = _markRemoved; -exports._assertUnremoved = _assertUnremoved; + var modifier = this.state.value; -var _removalHooks = require("./lib/removal-hooks"); + if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { + return modifier; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return undefined; + } + }, { + key: "tsParseModifiers", + value: function tsParseModifiers(allowedModifiers) { + var modifiers = Object.create(null); + + while (true) { + var startPos = this.state.start; + var modifier = this.tsParseModifier(allowedModifiers); + if (!modifier) break; + + if (Object.hasOwnProperty.call(modifiers, modifier)) { + this.raise(startPos, "Duplicate modifier: '".concat(modifier, "'")); + } -function remove() { - this._assertUnremoved(); + modifiers[modifier] = true; + } - this.resync(); + return modifiers; + } + }, { + key: "tsIsListTerminator", + value: function tsIsListTerminator(kind) { + switch (kind) { + case "EnumMembers": + case "TypeMembers": + return this.match(types.braceR); + + case "HeritageClauseElement": + return this.match(types.braceL); + + case "TupleElementTypes": + return this.match(types.bracketR); + + case "TypeParametersOrArguments": + return this.isRelational(">"); + } - if (this._callRemovalHooks()) { - this._markRemoved(); - return; - } + throw new Error("Unreachable"); + } + }, { + key: "tsParseList", + value: function tsParseList(kind, parseElement) { + var result = []; - this.shareCommentsWithSiblings(); - this._remove(); - this._markRemoved(); -} + while (!this.tsIsListTerminator(kind)) { + result.push(parseElement()); + } -function _callRemovalHooks() { - for (var _iterator = _removalHooks.hooks, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + return result; + } + }, { + key: "tsParseDelimitedList", + value: function tsParseDelimitedList(kind, parseElement) { + return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true)); + } + }, { + key: "tsParseDelimitedListWorker", + value: function tsParseDelimitedListWorker(kind, parseElement, expectSuccess) { + var result = []; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + while (true) { + if (this.tsIsListTerminator(kind)) { + break; + } - var fn = _ref; + var element = parseElement(); - if (fn(this, this.parentPath)) return true; - } -} + if (element == null) { + return undefined; + } -function _remove() { - if (Array.isArray(this.container)) { - this.container.splice(this.key, 1); - this.updateSiblingKeys(this.key, -1); - } else { - this._replaceWith(null); - } -} + result.push(element); -function _markRemoved() { - this.shouldSkip = true; - this.removed = true; - this.node = null; -} + if (this.eat(types.comma)) { + continue; + } -function _assertUnremoved() { - if (this.removed) { - throw this.buildCodeFrameError("NodePath has been removed so is read-only."); - } -} -},{"./lib/removal-hooks":131,"babel-runtime/core-js/get-iterator":95}],135:[function(require,module,exports){ -"use strict"; + if (this.tsIsListTerminator(kind)) { + break; + } -exports.__esModule = true; + if (expectSuccess) { + this.expect(types.comma); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + return undefined; + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + return result; + } + }, { + key: "tsParseBracketedList", + value: function tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) { + if (!skipFirstToken) { + if (bracket) { + this.expect(types.bracketL); + } else { + this.expectRelational("<"); + } + } -exports.replaceWithMultiple = replaceWithMultiple; -exports.replaceWithSourceString = replaceWithSourceString; -exports.replaceWith = replaceWith; -exports._replaceWith = _replaceWith; -exports.replaceExpressionWithStatements = replaceExpressionWithStatements; -exports.replaceInline = replaceInline; + var result = this.tsParseDelimitedList(kind, parseElement); -var _babelCodeFrame = require("babel-code-frame"); + if (bracket) { + this.expect(types.bracketR); + } else { + this.expectRelational(">"); + } -var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); + return result; + } + }, { + key: "tsParseImportType", + value: function tsParseImportType() { + var node = this.startNode(); + this.expect(types._import); + this.expect(types.parenL); + + if (!this.match(types.string)) { + this.raise(this.state.start, "Argument in a type import must be a string literal"); + } -var _index = require("../index"); + node.argument = this.parseExprAtom(); + this.expect(types.parenR); -var _index2 = _interopRequireDefault(_index); + if (this.eat(types.dot)) { + node.qualifier = this.tsParseEntityName(true); + } -var _index3 = require("./index"); + if (this.isRelational("<")) { + node.typeParameters = this.tsParseTypeArguments(); + } -var _index4 = _interopRequireDefault(_index3); + return this.finishNode(node, "TSImportType"); + } + }, { + key: "tsParseEntityName", + value: function tsParseEntityName(allowReservedWords) { + var entity = this.parseIdentifier(); + + while (this.eat(types.dot)) { + var node = this.startNodeAtNode(entity); + node.left = entity; + node.right = this.parseIdentifier(allowReservedWords); + entity = this.finishNode(node, "TSQualifiedName"); + } -var _babylon = require("babylon"); + return entity; + } + }, { + key: "tsParseTypeReference", + value: function tsParseTypeReference() { + var node = this.startNode(); + node.typeName = this.tsParseEntityName(false); + + if (!this.hasPrecedingLineBreak() && this.isRelational("<")) { + node.typeParameters = this.tsParseTypeArguments(); + } -var _babelTypes = require("babel-types"); + return this.finishNode(node, "TSTypeReference"); + } + }, { + key: "tsParseThisTypePredicate", + value: function tsParseThisTypePredicate(lhs) { + this.next(); + var node = this.startNodeAtNode(lhs); + node.parameterName = lhs; + node.typeAnnotation = this.tsParseTypeAnnotation(false); + return this.finishNode(node, "TSTypePredicate"); + } + }, { + key: "tsParseThisTypeNode", + value: function tsParseThisTypeNode() { + var node = this.startNode(); + this.next(); + return this.finishNode(node, "TSThisType"); + } + }, { + key: "tsParseTypeQuery", + value: function tsParseTypeQuery() { + var node = this.startNode(); + this.expect(types._typeof); + + if (this.match(types._import)) { + node.exprName = this.tsParseImportType(); + } else { + node.exprName = this.tsParseEntityName(true); + } -var t = _interopRequireWildcard(_babelTypes); + return this.finishNode(node, "TSTypeQuery"); + } + }, { + key: "tsParseTypeParameter", + value: function tsParseTypeParameter() { + var node = this.startNode(); + node.name = this.parseIdentifierName(node.start); + node.constraint = this.tsEatThenParseType(types._extends); + node.default = this.tsEatThenParseType(types.eq); + return this.finishNode(node, "TSTypeParameter"); + } + }, { + key: "tsTryParseTypeParameters", + value: function tsTryParseTypeParameters() { + if (this.isRelational("<")) { + return this.tsParseTypeParameters(); + } + } + }, { + key: "tsParseTypeParameters", + value: function tsParseTypeParameters() { + var node = this.startNode(); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (this.isRelational("<") || this.match(types.jsxTagStart)) { + this.next(); + } else { + this.unexpected(); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true); + return this.finishNode(node, "TSTypeParameterDeclaration"); + } + }, { + key: "tsTryNextParseConstantContext", + value: function tsTryNextParseConstantContext() { + if (this.lookahead().type === types._const) { + this.next(); + return this.tsParseTypeReference(); + } -var hoistVariablesVisitor = { - Function: function Function(path) { - path.skip(); - }, - VariableDeclaration: function VariableDeclaration(path) { - if (path.node.kind !== "var") return; - - var bindings = path.getBindingIdentifiers(); - for (var key in bindings) { - path.scope.push({ id: bindings[key] }); - } - - var exprs = []; - - for (var _iterator = path.node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + return null; + } + }, { + key: "tsFillSignature", + value: function tsFillSignature(returnToken, signature) { + var returnTokenRequired = returnToken === types.arrow; + signature.typeParameters = this.tsTryParseTypeParameters(); + this.expect(types.parenL); + signature.parameters = this.tsParseBindingListForSignature(); + + if (returnTokenRequired) { + signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } else if (this.match(returnToken)) { + signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } + } + }, { + key: "tsParseBindingListForSignature", + value: function tsParseBindingListForSignature() { + var _this17 = this; + + return this.parseBindingList(types.parenR, 41).map(function (pattern) { + if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") { + _this17.raise(pattern.start, "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern," + "instead got ".concat(pattern.type)); + } - var declar = _ref; + return pattern; + }); + } + }, { + key: "tsParseTypeMemberSemicolon", + value: function tsParseTypeMemberSemicolon() { + if (!this.eat(types.comma)) { + this.semicolon(); + } + } + }, { + key: "tsParseSignatureMember", + value: function tsParseSignatureMember(kind, node) { + this.tsFillSignature(types.colon, node); + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, kind); + } + }, { + key: "tsIsUnambiguouslyIndexSignature", + value: function tsIsUnambiguouslyIndexSignature() { + this.next(); + return this.eat(types.name) && this.match(types.colon); + } + }, { + key: "tsTryParseIndexSignature", + value: function tsTryParseIndexSignature(node) { + if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { + return undefined; + } - if (declar.init) { - exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init))); - } - } + this.expect(types.bracketL); + var id = this.parseIdentifier(); + id.typeAnnotation = this.tsParseTypeAnnotation(); + this.resetEndLocation(id); + this.expect(types.bracketR); + node.parameters = [id]; + var type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, "TSIndexSignature"); + } + }, { + key: "tsParsePropertyOrMethodSignature", + value: function tsParsePropertyOrMethodSignature(node, readonly) { + if (this.eat(types.question)) node.optional = true; + var nodeAny = node; + + if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) { + var method = nodeAny; + this.tsFillSignature(types.colon, method); + this.tsParseTypeMemberSemicolon(); + return this.finishNode(method, "TSMethodSignature"); + } else { + var property = nodeAny; + if (readonly) property.readonly = true; + var type = this.tsTryParseTypeAnnotation(); + if (type) property.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(property, "TSPropertySignature"); + } + } + }, { + key: "tsParseTypeMember", + value: function tsParseTypeMember() { + var node = this.startNode(); - path.replaceWithMultiple(exprs); - } -}; + if (this.match(types.parenL) || this.isRelational("<")) { + return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); + } -function replaceWithMultiple(nodes) { - this.resync(); + if (this.match(types._new)) { + var id = this.startNode(); + this.next(); - nodes = this._verifyNodeList(nodes); - t.inheritLeadingComments(nodes[0], this.node); - t.inheritTrailingComments(nodes[nodes.length - 1], this.node); - this.node = this.container[this.key] = null; - this.insertAfter(nodes); + if (this.match(types.parenL) || this.isRelational("<")) { + return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); + } else { + node.key = this.createIdentifier(id, "new"); + return this.tsParsePropertyOrMethodSignature(node, false); + } + } - if (this.node) { - this.requeue(); - } else { - this.remove(); - } -} + var readonly = !!this.tsParseModifier(["readonly"]); + var idx = this.tsTryParseIndexSignature(node); -function replaceWithSourceString(replacement) { - this.resync(); + if (idx) { + if (readonly) node.readonly = true; + return idx; + } - try { - replacement = "(" + replacement + ")"; - replacement = (0, _babylon.parse)(replacement); - } catch (err) { - var loc = err.loc; - if (loc) { - err.message += " - make sure this is an expression."; - err.message += "\n" + (0, _babelCodeFrame2.default)(replacement, loc.line, loc.column + 1); - } - throw err; - } + this.parsePropertyName(node); + return this.tsParsePropertyOrMethodSignature(node, readonly); + } + }, { + key: "tsParseTypeLiteral", + value: function tsParseTypeLiteral() { + var node = this.startNode(); + node.members = this.tsParseObjectTypeMembers(); + return this.finishNode(node, "TSTypeLiteral"); + } + }, { + key: "tsParseObjectTypeMembers", + value: function tsParseObjectTypeMembers() { + this.expect(types.braceL); + var members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); + this.expect(types.braceR); + return members; + } + }, { + key: "tsIsStartOfMappedType", + value: function tsIsStartOfMappedType() { + this.next(); - replacement = replacement.program.body[0].expression; - _index2.default.removeProperties(replacement); - return this.replaceWith(replacement); -} + if (this.eat(types.plusMin)) { + return this.isContextual("readonly"); + } -function replaceWith(replacement) { - this.resync(); + if (this.isContextual("readonly")) { + this.next(); + } - if (this.removed) { - throw new Error("You can't replace this node, we've already removed it"); - } + if (!this.match(types.bracketL)) { + return false; + } - if (replacement instanceof _index4.default) { - replacement = replacement.node; - } + this.next(); - if (!replacement) { - throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead"); - } + if (!this.tsIsIdentifier()) { + return false; + } - if (this.node === replacement) { - return; - } + this.next(); + return this.match(types._in); + } + }, { + key: "tsParseMappedTypeParameter", + value: function tsParseMappedTypeParameter() { + var node = this.startNode(); + node.name = this.parseIdentifierName(node.start); + node.constraint = this.tsExpectThenParseType(types._in); + return this.finishNode(node, "TSTypeParameter"); + } + }, { + key: "tsParseMappedType", + value: function tsParseMappedType() { + var node = this.startNode(); + this.expect(types.braceL); + + if (this.match(types.plusMin)) { + node.readonly = this.state.value; + this.next(); + this.expectContextual("readonly"); + } else if (this.eatContextual("readonly")) { + node.readonly = true; + } - if (this.isProgram() && !t.isProgram(replacement)) { - throw new Error("You can only replace a Program root node with another Program node"); - } + this.expect(types.bracketL); + node.typeParameter = this.tsParseMappedTypeParameter(); + this.expect(types.bracketR); - if (Array.isArray(replacement)) { - throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`"); - } + if (this.match(types.plusMin)) { + node.optional = this.state.value; + this.next(); + this.expect(types.question); + } else if (this.eat(types.question)) { + node.optional = true; + } - if (typeof replacement === "string") { - throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`"); - } + node.typeAnnotation = this.tsTryParseType(); + this.semicolon(); + this.expect(types.braceR); + return this.finishNode(node, "TSMappedType"); + } + }, { + key: "tsParseTupleType", + value: function tsParseTupleType() { + var _this18 = this; + + var node = this.startNode(); + node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); + var seenOptionalElement = false; + node.elementTypes.forEach(function (elementNode) { + if (elementNode.type === "TSOptionalType") { + seenOptionalElement = true; + } else if (seenOptionalElement && elementNode.type !== "TSRestType") { + _this18.raise(elementNode.start, "A required element cannot follow an optional element."); + } + }); + return this.finishNode(node, "TSTupleType"); + } + }, { + key: "tsParseTupleElementType", + value: function tsParseTupleElementType() { + if (this.match(types.ellipsis)) { + var restNode = this.startNode(); + this.next(); + restNode.typeAnnotation = this.tsParseType(); + this.checkCommaAfterRest(93); + return this.finishNode(restNode, "TSRestType"); + } - if (this.isNodeType("Statement") && t.isExpression(replacement)) { - if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) { - replacement = t.expressionStatement(replacement); - } - } + var type = this.tsParseType(); - if (this.isNodeType("Expression") && t.isStatement(replacement)) { - if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { - return this.replaceExpressionWithStatements([replacement]); - } - } + if (this.eat(types.question)) { + var optionalTypeNode = this.startNodeAtNode(type); + optionalTypeNode.typeAnnotation = type; + return this.finishNode(optionalTypeNode, "TSOptionalType"); + } - var oldNode = this.node; - if (oldNode) { - t.inheritsComments(replacement, oldNode); - t.removeComments(oldNode); - } + return type; + } + }, { + key: "tsParseParenthesizedType", + value: function tsParseParenthesizedType() { + var node = this.startNode(); + this.expect(types.parenL); + node.typeAnnotation = this.tsParseType(); + this.expect(types.parenR); + return this.finishNode(node, "TSParenthesizedType"); + } + }, { + key: "tsParseFunctionOrConstructorType", + value: function tsParseFunctionOrConstructorType(type) { + var node = this.startNode(); - this._replaceWith(replacement); - this.type = replacement.type; + if (type === "TSConstructorType") { + this.expect(types._new); + } - this.setScope(); + this.tsFillSignature(types.arrow, node); + return this.finishNode(node, type); + } + }, { + key: "tsParseLiteralTypeNode", + value: function tsParseLiteralTypeNode() { + var _this19 = this; + + var node = this.startNode(); + + node.literal = function () { + switch (_this19.state.type) { + case types.num: + case types.string: + case types._true: + case types._false: + return _this19.parseExprAtom(); + + default: + throw _this19.unexpected(); + } + }(); - this.requeue(); -} + return this.finishNode(node, "TSLiteralType"); + } + }, { + key: "tsParseTemplateLiteralType", + value: function tsParseTemplateLiteralType() { + var node = this.startNode(); + var templateNode = this.parseTemplate(false); + + if (templateNode.expressions.length > 0) { + this.raise(templateNode.expressions[0].start, "Template literal types cannot have any substitution"); + } -function _replaceWith(node) { - if (!this.container) { - throw new ReferenceError("Container is falsy"); - } + node.literal = templateNode; + return this.finishNode(node, "TSLiteralType"); + } + }, { + key: "tsParseNonArrayType", + value: function tsParseNonArrayType() { + switch (this.state.type) { + case types.name: + case types._void: + case types._null: + { + var type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value); + + if (type !== undefined && this.lookaheadCharCode() !== 46) { + var node = this.startNode(); + this.next(); + return this.finishNode(node, type); + } - if (this.inList) { - t.validate(this.parent, this.key, [node]); - } else { - t.validate(this.parent, this.key, node); - } + return this.tsParseTypeReference(); + } - this.debug(function () { - return "Replace with " + (node && node.type); - }); + case types.string: + case types.num: + case types._true: + case types._false: + return this.tsParseLiteralTypeNode(); - this.node = this.container[this.key] = node; -} + case types.plusMin: + if (this.state.value === "-") { + var _node6 = this.startNode(); -function replaceExpressionWithStatements(nodes) { - this.resync(); + if (this.lookahead().type !== types.num) { + throw this.unexpected(); + } - var toSequenceExpression = t.toSequenceExpression(nodes, this.scope); + _node6.literal = this.parseMaybeUnary(); + return this.finishNode(_node6, "TSLiteralType"); + } - if (t.isSequenceExpression(toSequenceExpression)) { - var exprs = toSequenceExpression.expressions; + break; - if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) { - this._maybePopFromStatements(exprs); - } + case types._this: + { + var thisKeyword = this.tsParseThisTypeNode(); - if (exprs.length === 1) { - this.replaceWith(exprs[0]); - } else { - this.replaceWith(toSequenceExpression); - } - } else if (toSequenceExpression) { - this.replaceWith(toSequenceExpression); - } else { - var container = t.functionExpression(null, [], t.blockStatement(nodes)); - container.shadow = true; + if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { + return this.tsParseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } + } - this.replaceWith(t.callExpression(container, [])); - this.traverse(hoistVariablesVisitor); + case types._typeof: + return this.tsParseTypeQuery(); - var completionRecords = this.get("callee").getCompletionRecords(); - for (var _iterator2 = completionRecords, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + case types._import: + return this.tsParseImportType(); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + case types.braceL: + return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); - var path = _ref2; + case types.bracketL: + return this.tsParseTupleType(); - if (!path.isExpressionStatement()) continue; + case types.parenL: + return this.tsParseParenthesizedType(); - var loop = path.findParent(function (path) { - return path.isLoop(); - }); - if (loop) { - var uid = loop.getData("expressionReplacementReturnUid"); + case types.backQuote: + return this.tsParseTemplateLiteralType(); + } - if (!uid) { - var callee = this.get("callee"); - uid = callee.scope.generateDeclaredUidIdentifier("ret"); - callee.get("body").pushContainer("body", t.returnStatement(uid)); - loop.setData("expressionReplacementReturnUid", uid); - } else { - uid = t.identifier(uid.name); + throw this.unexpected(); } + }, { + key: "tsParseArrayTypeOrHigher", + value: function tsParseArrayTypeOrHigher() { + var type = this.tsParseNonArrayType(); + + while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) { + if (this.match(types.bracketR)) { + var node = this.startNodeAtNode(type); + node.elementType = type; + this.expect(types.bracketR); + type = this.finishNode(node, "TSArrayType"); + } else { + var _node7 = this.startNodeAtNode(type); - path.get("expression").replaceWith(t.assignmentExpression("=", uid, path.node.expression)); - } else { - path.replaceWith(t.returnStatement(path.node.expression)); - } - } + _node7.objectType = type; + _node7.indexType = this.tsParseType(); + this.expect(types.bracketR); + type = this.finishNode(_node7, "TSIndexedAccessType"); + } + } - return this.node; - } -} + return type; + } + }, { + key: "tsParseTypeOperator", + value: function tsParseTypeOperator(operator) { + var node = this.startNode(); + this.expectContextual(operator); + node.operator = operator; + node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); + + if (operator === "readonly") { + this.tsCheckTypeAnnotationForReadOnly(node); + } -function replaceInline(nodes) { - this.resync(); + return this.finishNode(node, "TSTypeOperator"); + } + }, { + key: "tsCheckTypeAnnotationForReadOnly", + value: function tsCheckTypeAnnotationForReadOnly(node) { + switch (node.typeAnnotation.type) { + case "TSTupleType": + case "TSArrayType": + return; - if (Array.isArray(nodes)) { - if (Array.isArray(this.container)) { - nodes = this._verifyNodeList(nodes); - this._containerInsertAfter(nodes); - return this.remove(); - } else { - return this.replaceWithMultiple(nodes); - } - } else { - return this.replaceWith(nodes); - } -} -},{"../index":118,"./index":125,"babel-code-frame":4,"babel-runtime/core-js/get-iterator":95,"babel-types":151,"babylon":155}],136:[function(require,module,exports){ -"use strict"; + default: + this.raise(node.start, "'readonly' type modifier is only permitted on array and tuple literal types."); + } + } + }, { + key: "tsParseInferType", + value: function tsParseInferType() { + var node = this.startNode(); + this.expectContextual("infer"); + var typeParameter = this.startNode(); + typeParameter.name = this.parseIdentifierName(typeParameter.start); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + return this.finishNode(node, "TSInferType"); + } + }, { + key: "tsParseTypeOperatorOrHigher", + value: function tsParseTypeOperatorOrHigher() { + var _this20 = this; -exports.__esModule = true; + var operator = ["keyof", "unique", "readonly"].find(function (kw) { + return _this20.isContextual(kw); + }); + return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher(); + } + }, { + key: "tsParseUnionOrIntersectionType", + value: function tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { + this.eat(operator); + var type = parseConstituentType(); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + if (this.match(operator)) { + var _types = [type]; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + while (this.eat(operator)) { + _types.push(parseConstituentType()); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var node = this.startNodeAtNode(type); + node.types = _types; + type = this.finishNode(node, kind); + } -var Binding = function () { - function Binding(_ref) { - var existing = _ref.existing, - identifier = _ref.identifier, - scope = _ref.scope, - path = _ref.path, - kind = _ref.kind; - (0, _classCallCheck3.default)(this, Binding); + return type; + } + }, { + key: "tsParseIntersectionTypeOrHigher", + value: function tsParseIntersectionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND); + } + }, { + key: "tsParseUnionTypeOrHigher", + value: function tsParseUnionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR); + } + }, { + key: "tsIsStartOfFunctionType", + value: function tsIsStartOfFunctionType() { + if (this.isRelational("<")) { + return true; + } - this.identifier = identifier; - this.scope = scope; - this.path = path; - this.kind = kind; + return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); + } + }, { + key: "tsSkipParameterStart", + value: function tsSkipParameterStart() { + if (this.match(types.name) || this.match(types._this)) { + this.next(); + return true; + } - this.constantViolations = []; - this.constant = true; + if (this.match(types.braceL)) { + var braceStackCounter = 1; + this.next(); - this.referencePaths = []; - this.referenced = false; - this.references = 0; + while (braceStackCounter > 0) { + if (this.match(types.braceL)) { + ++braceStackCounter; + } else if (this.match(types.braceR)) { + --braceStackCounter; + } - this.clearValue(); + this.next(); + } - if (existing) { - this.constantViolations = [].concat(existing.path, existing.constantViolations, this.constantViolations); - } - } + return true; + } - Binding.prototype.deoptValue = function deoptValue() { - this.clearValue(); - this.hasDeoptedValue = true; - }; + if (this.match(types.bracketL)) { + var _braceStackCounter = 1; + this.next(); - Binding.prototype.setValue = function setValue(value) { - if (this.hasDeoptedValue) return; - this.hasValue = true; - this.value = value; - }; + while (_braceStackCounter > 0) { + if (this.match(types.bracketL)) { + ++_braceStackCounter; + } else if (this.match(types.bracketR)) { + --_braceStackCounter; + } - Binding.prototype.clearValue = function clearValue() { - this.hasDeoptedValue = false; - this.hasValue = false; - this.value = null; - }; + this.next(); + } - Binding.prototype.reassign = function reassign(path) { - this.constant = false; - if (this.constantViolations.indexOf(path) !== -1) { - return; - } - this.constantViolations.push(path); - }; + return true; + } - Binding.prototype.reference = function reference(path) { - if (this.referencePaths.indexOf(path) !== -1) { - return; - } - this.referenced = true; - this.references++; - this.referencePaths.push(path); - }; + return false; + } + }, { + key: "tsIsUnambiguouslyStartOfFunctionType", + value: function tsIsUnambiguouslyStartOfFunctionType() { + this.next(); - Binding.prototype.dereference = function dereference() { - this.references--; - this.referenced = !!this.references; - }; + if (this.match(types.parenR) || this.match(types.ellipsis)) { + return true; + } - return Binding; -}(); + if (this.tsSkipParameterStart()) { + if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) { + return true; + } -exports.default = Binding; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":109}],137:[function(require,module,exports){ -"use strict"; + if (this.match(types.parenR)) { + this.next(); -exports.__esModule = true; + if (this.match(types.arrow)) { + return true; + } + } + } -var _keys = require("babel-runtime/core-js/object/keys"); + return false; + } + }, { + key: "tsParseTypeOrTypePredicateAnnotation", + value: function tsParseTypeOrTypePredicateAnnotation(returnToken) { + var _this21 = this; -var _keys2 = _interopRequireDefault(_keys); + return this.tsInType(function () { + var t = _this21.startNode(); -var _create = require("babel-runtime/core-js/object/create"); + _this21.expect(returnToken); -var _create2 = _interopRequireDefault(_create); + var asserts = _this21.tsTryParse(_this21.tsParseTypePredicateAsserts.bind(_this21)); -var _map = require("babel-runtime/core-js/map"); + var typePredicateVariable = _this21.tsIsIdentifier() && _this21.tsTryParse(_this21.tsParseTypePredicatePrefix.bind(_this21)); -var _map2 = _interopRequireDefault(_map); + if (!typePredicateVariable) { + if (!asserts) { + return _this21.tsParseTypeAnnotation(false, t); + } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + var _node8 = _this21.startNodeAtNode(t); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + _node8.parameterName = _this21.parseIdentifier(); + _node8.asserts = asserts; + t.typeAnnotation = _this21.finishNode(_node8, "TSTypePredicate"); + return _this21.finishNode(t, "TSTypeAnnotation"); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + var type = _this21.tsParseTypeAnnotation(false); -var _getIterator3 = _interopRequireDefault(_getIterator2); + var node = _this21.startNodeAtNode(t); -var _includes = require("lodash/includes"); + node.parameterName = typePredicateVariable; + node.typeAnnotation = type; + node.asserts = asserts; + t.typeAnnotation = _this21.finishNode(node, "TSTypePredicate"); + return _this21.finishNode(t, "TSTypeAnnotation"); + }); + } + }, { + key: "tsTryParseTypeOrTypePredicateAnnotation", + value: function tsTryParseTypeOrTypePredicateAnnotation() { + return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined; + } + }, { + key: "tsTryParseTypeAnnotation", + value: function tsTryParseTypeAnnotation() { + return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined; + } + }, { + key: "tsTryParseType", + value: function tsTryParseType() { + return this.tsEatThenParseType(types.colon); + } + }, { + key: "tsParseTypePredicatePrefix", + value: function tsParseTypePredicatePrefix() { + var id = this.parseIdentifier(); + + if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { + this.next(); + return id; + } + } + }, { + key: "tsParseTypePredicateAsserts", + value: function tsParseTypePredicateAsserts() { + if (!this.tsIsIdentifier()) { + return false; + } -var _includes2 = _interopRequireDefault(_includes); + var id = this.parseIdentifier(); -var _repeat = require("lodash/repeat"); + if (id.name !== "asserts" || this.hasPrecedingLineBreak() || !this.tsIsIdentifier()) { + return false; + } -var _repeat2 = _interopRequireDefault(_repeat); + return true; + } + }, { + key: "tsParseTypeAnnotation", + value: function tsParseTypeAnnotation() { + var _this22 = this; + + var eatColon = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.startNode(); + this.tsInType(function () { + if (eatColon) _this22.expect(types.colon); + t.typeAnnotation = _this22.tsParseType(); + }); + return this.finishNode(t, "TSTypeAnnotation"); + } + }, { + key: "tsParseType", + value: function tsParseType() { + assert(this.state.inType); + var type = this.tsParseNonConditionalType(); + + if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) { + return type; + } -var _renamer = require("./lib/renamer"); + var node = this.startNodeAtNode(type); + node.checkType = type; + node.extendsType = this.tsParseNonConditionalType(); + this.expect(types.question); + node.trueType = this.tsParseType(); + this.expect(types.colon); + node.falseType = this.tsParseType(); + return this.finishNode(node, "TSConditionalType"); + } + }, { + key: "tsParseNonConditionalType", + value: function tsParseNonConditionalType() { + if (this.tsIsStartOfFunctionType()) { + return this.tsParseFunctionOrConstructorType("TSFunctionType"); + } -var _renamer2 = _interopRequireDefault(_renamer); + if (this.match(types._new)) { + return this.tsParseFunctionOrConstructorType("TSConstructorType"); + } -var _index = require("../index"); + return this.tsParseUnionTypeOrHigher(); + } + }, { + key: "tsParseTypeAssertion", + value: function tsParseTypeAssertion() { + var node = this.startNode(); -var _index2 = _interopRequireDefault(_index); + var _const = this.tsTryNextParseConstantContext(); -var _defaults = require("lodash/defaults"); + node.typeAnnotation = _const || this.tsNextThenParseType(); + this.expectRelational(">"); + node.expression = this.parseMaybeUnary(); + return this.finishNode(node, "TSTypeAssertion"); + } + }, { + key: "tsParseHeritageClause", + value: function tsParseHeritageClause(descriptor) { + var originalStart = this.state.start; + var delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this)); + + if (!delimitedList.length) { + this.raise(originalStart, "'".concat(descriptor, "' list cannot be empty.")); + } -var _defaults2 = _interopRequireDefault(_defaults); + return delimitedList; + } + }, { + key: "tsParseExpressionWithTypeArguments", + value: function tsParseExpressionWithTypeArguments() { + var node = this.startNode(); + node.expression = this.tsParseEntityName(false); -var _babelMessages = require("babel-messages"); + if (this.isRelational("<")) { + node.typeParameters = this.tsParseTypeArguments(); + } -var messages = _interopRequireWildcard(_babelMessages); + return this.finishNode(node, "TSExpressionWithTypeArguments"); + } + }, { + key: "tsParseInterfaceDeclaration", + value: function tsParseInterfaceDeclaration(node) { + node.id = this.parseIdentifier(); + this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration"); + node.typeParameters = this.tsTryParseTypeParameters(); + + if (this.eat(types._extends)) { + node.extends = this.tsParseHeritageClause("extends"); + } -var _binding2 = require("./binding"); + var body = this.startNode(); + body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); + node.body = this.finishNode(body, "TSInterfaceBody"); + return this.finishNode(node, "TSInterfaceDeclaration"); + } + }, { + key: "tsParseTypeAliasDeclaration", + value: function tsParseTypeAliasDeclaration(node) { + node.id = this.parseIdentifier(); + this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias"); + node.typeParameters = this.tsTryParseTypeParameters(); + node.typeAnnotation = this.tsExpectThenParseType(types.eq); + this.semicolon(); + return this.finishNode(node, "TSTypeAliasDeclaration"); + } + }, { + key: "tsInNoContext", + value: function tsInNoContext(cb) { + var oldContext = this.state.context; + this.state.context = [oldContext[0]]; -var _binding3 = _interopRequireDefault(_binding2); + try { + return cb(); + } finally { + this.state.context = oldContext; + } + } + }, { + key: "tsInType", + value: function tsInType(cb) { + var oldInType = this.state.inType; + this.state.inType = true; -var _globals = require("globals"); + try { + return cb(); + } finally { + this.state.inType = oldInType; + } + } + }, { + key: "tsEatThenParseType", + value: function tsEatThenParseType(token) { + return !this.match(token) ? undefined : this.tsNextThenParseType(); + } + }, { + key: "tsExpectThenParseType", + value: function tsExpectThenParseType(token) { + var _this23 = this; -var _globals2 = _interopRequireDefault(_globals); + return this.tsDoThenParseType(function () { + return _this23.expect(token); + }); + } + }, { + key: "tsNextThenParseType", + value: function tsNextThenParseType() { + var _this24 = this; -var _babelTypes = require("babel-types"); + return this.tsDoThenParseType(function () { + return _this24.next(); + }); + } + }, { + key: "tsDoThenParseType", + value: function tsDoThenParseType(cb) { + var _this25 = this; + + return this.tsInType(function () { + cb(); + return _this25.tsParseType(); + }); + } + }, { + key: "tsParseEnumMember", + value: function tsParseEnumMember() { + var node = this.startNode(); + node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true); + + if (this.eat(types.eq)) { + node.initializer = this.parseMaybeAssign(); + } -var t = _interopRequireWildcard(_babelTypes); + return this.finishNode(node, "TSEnumMember"); + } + }, { + key: "tsParseEnumDeclaration", + value: function tsParseEnumDeclaration(node, isConst) { + if (isConst) node.const = true; + node.id = this.parseIdentifier(); + this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration"); + this.expect(types.braceL); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(types.braceR); + return this.finishNode(node, "TSEnumDeclaration"); + } + }, { + key: "tsParseModuleBlock", + value: function tsParseModuleBlock() { + var node = this.startNode(); + this.scope.enter(SCOPE_OTHER); + this.expect(types.braceL); + this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR); + this.scope.exit(); + return this.finishNode(node, "TSModuleBlock"); + } + }, { + key: "tsParseModuleOrNamespaceDeclaration", + value: function tsParseModuleOrNamespaceDeclaration(node) { + var nested = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + node.id = this.parseIdentifier(); + + if (!nested) { + this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration"); + } -var _cache = require("../cache"); + if (this.eat(types.dot)) { + var inner = this.startNode(); + this.tsParseModuleOrNamespaceDeclaration(inner, true); + node.body = inner; + } else { + this.scope.enter(SCOPE_TS_MODULE); + node.body = this.tsParseModuleBlock(); + this.scope.exit(); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return this.finishNode(node, "TSModuleDeclaration"); + } + }, { + key: "tsParseAmbientExternalModuleDeclaration", + value: function tsParseAmbientExternalModuleDeclaration(node) { + if (this.isContextual("global")) { + node.global = true; + node.id = this.parseIdentifier(); + } else if (this.match(types.string)) { + node.id = this.parseExprAtom(); + } else { + this.unexpected(); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this.match(types.braceL)) { + this.scope.enter(SCOPE_TS_MODULE); + node.body = this.tsParseModuleBlock(); + this.scope.exit(); + } else { + this.semicolon(); + } -var _crawlCallsCount = 0; + return this.finishNode(node, "TSModuleDeclaration"); + } + }, { + key: "tsParseImportEqualsDeclaration", + value: function tsParseImportEqualsDeclaration(node, isExport) { + node.isExport = isExport || false; + node.id = this.parseIdentifier(); + this.expect(types.eq); + node.moduleReference = this.tsParseModuleReference(); + this.semicolon(); + return this.finishNode(node, "TSImportEqualsDeclaration"); + } + }, { + key: "tsIsExternalModuleReference", + value: function tsIsExternalModuleReference() { + return this.isContextual("require") && this.lookaheadCharCode() === 40; + } + }, { + key: "tsParseModuleReference", + value: function tsParseModuleReference() { + return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false); + } + }, { + key: "tsParseExternalModuleReference", + value: function tsParseExternalModuleReference() { + var node = this.startNode(); + this.expectContextual("require"); + this.expect(types.parenL); + + if (!this.match(types.string)) { + throw this.unexpected(); + } -function getCache(path, parentScope, self) { - var scopes = _cache.scope.get(path.node) || []; + node.expression = this.parseExprAtom(); + this.expect(types.parenR); + return this.finishNode(node, "TSExternalModuleReference"); + } + }, { + key: "tsLookAhead", + value: function tsLookAhead(f) { + var state = this.state.clone(); + var res = f(); + this.state = state; + return res; + } + }, { + key: "tsTryParseAndCatch", + value: function tsTryParseAndCatch(f) { + var result = this.tryParse(function (abort) { + return f() || abort(); + }); + if (result.aborted || !result.node) return undefined; + if (result.error) this.state = result.failState; + return result.node; + } + }, { + key: "tsTryParse", + value: function tsTryParse(f) { + var state = this.state.clone(); + var result = f(); + + if (result !== undefined && result !== false) { + return result; + } else { + this.state = state; + return undefined; + } + } + }, { + key: "tsTryParseDeclare", + value: function tsTryParseDeclare(nany) { + if (this.isLineTerminator()) { + return; + } - for (var _iterator = scopes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + var starttype = this.state.type; + var kind; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (this.isContextual("let")) { + starttype = types._var; + kind = "let"; + } - var scope = _ref; + switch (starttype) { + case types._function: + return this.parseFunctionStatement(nany, false, true); - if (scope.parent === parentScope && scope.path === path) return scope; - } + case types._class: + nany.declare = true; + return this.parseClass(nany, true, false); - scopes.push(self); + case types._const: + if (this.match(types._const) && this.isLookaheadContextual("enum")) { + this.expect(types._const); + this.expectContextual("enum"); + return this.tsParseEnumDeclaration(nany, true); + } - if (!_cache.scope.has(path.node)) { - _cache.scope.set(path.node, scopes); - } -} + case types._var: + kind = kind || this.state.value; + return this.parseVarStatement(nany, kind); -function gatherNodeParts(node, parts) { - if (t.isModuleDeclaration(node)) { - if (node.source) { - gatherNodeParts(node.source, parts); - } else if (node.specifiers && node.specifiers.length) { - for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + case types.name: + { + var value = this.state.value; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + if (value === "global") { + return this.tsParseAmbientExternalModuleDeclaration(nany); + } else { + return this.tsParseDeclaration(nany, value, true); + } + } + } } + }, { + key: "tsTryParseExportDeclaration", + value: function tsTryParseExportDeclaration() { + return this.tsParseDeclaration(this.startNode(), this.state.value, true); + } + }, { + key: "tsParseExpressionStatement", + value: function tsParseExpressionStatement(node, expr) { + switch (expr.name) { + case "declare": + { + var declaration = this.tsTryParseDeclare(node); + + if (declaration) { + declaration.declare = true; + return declaration; + } - var specifier = _ref2; - - gatherNodeParts(specifier, parts); - } - } else if (node.declaration) { - gatherNodeParts(node.declaration, parts); - } - } else if (t.isModuleSpecifier(node)) { - gatherNodeParts(node.local, parts); - } else if (t.isMemberExpression(node)) { - gatherNodeParts(node.object, parts); - gatherNodeParts(node.property, parts); - } else if (t.isIdentifier(node)) { - parts.push(node.name); - } else if (t.isLiteral(node)) { - parts.push(node.value); - } else if (t.isCallExpression(node)) { - gatherNodeParts(node.callee, parts); - } else if (t.isObjectExpression(node) || t.isObjectPattern(node)) { - for (var _iterator3 = node.properties, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + break; + } - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } + case "global": + if (this.match(types.braceL)) { + this.scope.enter(SCOPE_TS_MODULE); + var mod = node; + mod.global = true; + mod.id = expr; + mod.body = this.tsParseModuleBlock(); + this.scope.exit(); + return this.finishNode(mod, "TSModuleDeclaration"); + } - var prop = _ref3; + break; - gatherNodeParts(prop.key || prop.argument, parts); - } - } -} + default: + return this.tsParseDeclaration(node, expr.name, false); + } + } + }, { + key: "tsParseDeclaration", + value: function tsParseDeclaration(node, value, next) { + switch (value) { + case "abstract": + if (this.tsCheckLineTerminatorAndMatch(types._class, next)) { + var cls = node; + cls.abstract = true; + + if (next) { + this.next(); + + if (!this.match(types._class)) { + this.unexpected(null, types._class); + } + } -var collectorVisitor = { - For: function For(path) { - for (var _iterator4 = t.FOR_INIT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; + return this.parseClass(cls, true, false); + } - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } + break; - var key = _ref4; + case "enum": + if (next || this.match(types.name)) { + if (next) this.next(); + return this.tsParseEnumDeclaration(node, false); + } - var declar = path.get(key); - if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar); - } - }, - Declaration: function Declaration(path) { - if (path.isBlockScoped()) return; + break; - if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) return; + case "interface": + if (this.tsCheckLineTerminatorAndMatch(types.name, next)) { + if (next) this.next(); + return this.tsParseInterfaceDeclaration(node); + } - path.scope.getFunctionParent().registerDeclaration(path); - }, - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - state.references.push(path); - }, - ForXStatement: function ForXStatement(path, state) { - var left = path.get("left"); - if (left.isPattern() || left.isIdentifier()) { - state.constantViolations.push(left); - } - }, + break; + case "module": + if (next) this.next(); - ExportDeclaration: { - exit: function exit(path) { - var node = path.node, - scope = path.scope; + if (this.match(types.string)) { + return this.tsParseAmbientExternalModuleDeclaration(node); + } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } - var declar = node.declaration; - if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) { - var _id = declar.id; - if (!_id) return; + break; - var binding = scope.getBinding(_id.name); - if (binding) binding.reference(path); - } else if (t.isVariableDeclaration(declar)) { - for (var _iterator5 = declar.declarations, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; + case "namespace": + if (this.tsCheckLineTerminatorAndMatch(types.name, next)) { + if (next) this.next(); + return this.tsParseModuleOrNamespaceDeclaration(node); + } - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } + break; - var decl = _ref5; + case "type": + if (this.tsCheckLineTerminatorAndMatch(types.name, next)) { + if (next) this.next(); + return this.tsParseTypeAliasDeclaration(node); + } - var ids = t.getBindingIdentifiers(decl); - for (var name in ids) { - var _binding = scope.getBinding(name); - if (_binding) _binding.reference(path); + break; } } - } - } - }, - - LabeledStatement: function LabeledStatement(path) { - path.scope.getProgramParent().addGlobal(path.node); - path.scope.getBlockParent().registerDeclaration(path); - }, - AssignmentExpression: function AssignmentExpression(path, state) { - state.assignments.push(path); - }, - UpdateExpression: function UpdateExpression(path, state) { - state.constantViolations.push(path.get("argument")); - }, - UnaryExpression: function UnaryExpression(path, state) { - if (path.node.operator === "delete") { - state.constantViolations.push(path.get("argument")); - } - }, - BlockScoped: function BlockScoped(path) { - var scope = path.scope; - if (scope.path === path) scope = scope.parent; - scope.getBlockParent().registerDeclaration(path); - }, - ClassDeclaration: function ClassDeclaration(path) { - var id = path.node.id; - if (!id) return; + }, { + key: "tsCheckLineTerminatorAndMatch", + value: function tsCheckLineTerminatorAndMatch(tokenType, next) { + return (next || this.match(tokenType)) && !this.isLineTerminator(); + } + }, { + key: "tsTryParseGenericAsyncArrowFunction", + value: function tsTryParseGenericAsyncArrowFunction(startPos, startLoc) { + var _this26 = this; - var name = id.name; - path.scope.bindings[name] = path.scope.getBinding(name); - }, - Block: function Block(path) { - var paths = path.get("body"); - for (var _iterator6 = paths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; + if (!this.isRelational("<")) { + return undefined; + } - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } + var res = this.tsTryParseAndCatch(function () { + var node = _this26.startNodeAt(startPos, startLoc); - var bodyPath = _ref6; + node.typeParameters = _this26.tsParseTypeParameters(); - if (bodyPath.isFunctionDeclaration()) { - path.scope.getBlockParent().registerDeclaration(bodyPath); - } - } - } -}; + _get(_getPrototypeOf(_class4.prototype), "parseFunctionParams", _this26).call(_this26, node); -var uid = 0; + node.returnType = _this26.tsTryParseTypeOrTypePredicateAnnotation(); -var Scope = function () { - function Scope(path, parentScope) { - (0, _classCallCheck3.default)(this, Scope); + _this26.expect(types.arrow); - if (parentScope && parentScope.block === path.node) { - return parentScope; - } + return node; + }); - var cached = getCache(path, parentScope, this); - if (cached) return cached; + if (!res) { + return undefined; + } - this.uid = uid++; - this.parent = parentScope; - this.hub = path.hub; + return this.parseArrowExpression(res, null, true); + } + }, { + key: "tsParseTypeArguments", + value: function tsParseTypeArguments() { + var _this27 = this; - this.parentBlock = path.parent; - this.block = path.node; - this.path = path; + var node = this.startNode(); + node.params = this.tsInType(function () { + return _this27.tsInNoContext(function () { + _this27.expectRelational("<"); - this.labels = new _map2.default(); - } + return _this27.tsParseDelimitedList("TypeParametersOrArguments", _this27.tsParseType.bind(_this27)); + }); + }); + this.state.exprAllowed = false; + this.expectRelational(">"); + return this.finishNode(node, "TSTypeParameterInstantiation"); + } + }, { + key: "tsIsDeclarationStart", + value: function tsIsDeclarationStart() { + if (this.match(types.name)) { + switch (this.state.value) { + case "abstract": + case "declare": + case "enum": + case "interface": + case "module": + case "namespace": + case "type": + return true; + } + } - Scope.prototype.traverse = function traverse(node, opts, state) { - (0, _index2.default)(node, opts, this, state, this.path); - }; + return false; + } + }, { + key: "isExportDefaultSpecifier", + value: function isExportDefaultSpecifier() { + if (this.tsIsDeclarationStart()) return false; + return _get(_getPrototypeOf(_class4.prototype), "isExportDefaultSpecifier", this).call(this); + } + }, { + key: "parseAssignableListItem", + value: function parseAssignableListItem(allowModifiers, decorators) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var accessibility; + var readonly = false; + + if (allowModifiers) { + accessibility = this.parseAccessModifier(); + readonly = !!this.tsParseModifier(["readonly"]); + } - Scope.prototype.generateDeclaredUidIdentifier = function generateDeclaredUidIdentifier() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + var left = this.parseMaybeDefault(); + this.parseAssignableListItemTypes(left); + var elt = this.parseMaybeDefault(left.start, left.loc.start, left); - var id = this.generateUidIdentifier(name); - this.push({ id: id }); - return id; - }; + if (accessibility || readonly) { + var pp = this.startNodeAt(startPos, startLoc); - Scope.prototype.generateUidIdentifier = function generateUidIdentifier() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + if (decorators.length) { + pp.decorators = decorators; + } - return t.identifier(this.generateUid(name)); - }; + if (accessibility) pp.accessibility = accessibility; + if (readonly) pp.readonly = readonly; - Scope.prototype.generateUid = function generateUid() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { + this.raise(pp.start, "A parameter property may not be declared using a binding pattern."); + } - name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, ""); + pp.parameter = elt; + return this.finishNode(pp, "TSParameterProperty"); + } - var uid = void 0; - var i = 0; - do { - uid = this._generateUid(name, i); - i++; - } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); + if (decorators.length) { + left.decorators = decorators; + } - var program = this.getProgramParent(); - program.references[uid] = true; - program.uids[uid] = true; + return elt; + } + }, { + key: "parseFunctionBodyAndFinish", + value: function parseFunctionBodyAndFinish(node, type) { + var isMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - return uid; - }; + if (this.match(types.colon)) { + node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon); + } - Scope.prototype._generateUid = function _generateUid(name, i) { - var id = name; - if (i > 1) id += i; - return "_" + id; - }; + var bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined; - Scope.prototype.generateUidIdentifierBasedOnNode = function generateUidIdentifierBasedOnNode(parent, defaultName) { - var node = parent; + if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) { + this.finishNode(node, bodilessType); + return; + } - if (t.isAssignmentExpression(parent)) { - node = parent.left; - } else if (t.isVariableDeclarator(parent)) { - node = parent.id; - } else if (t.isObjectProperty(node) || t.isObjectMethod(node)) { - node = node.key; - } - - var parts = []; - gatherNodeParts(node, parts); - - var id = parts.join("$"); - id = id.replace(/^_/, "") || defaultName || "ref"; - - return this.generateUidIdentifier(id.slice(0, 20)); - }; + _get(_getPrototypeOf(_class4.prototype), "parseFunctionBodyAndFinish", this).call(this, node, type, isMethod); + } + }, { + key: "registerFunctionStatementId", + value: function registerFunctionStatementId(node) { + if (!node.body && node.id) { + this.checkLVal(node.id, BIND_TS_AMBIENT, null, "function name"); + } else { + _get(_getPrototypeOf(_class4.prototype), "registerFunctionStatementId", this).apply(this, arguments); + } + } + }, { + key: "parseSubscript", + value: function parseSubscript(base, startPos, startLoc, noCalls, state) { + var _this28 = this; + + if (!this.hasPrecedingLineBreak() && this.match(types.bang)) { + this.state.exprAllowed = false; + this.next(); + var nonNullExpression = this.startNodeAt(startPos, startLoc); + nonNullExpression.expression = base; + return this.finishNode(nonNullExpression, "TSNonNullExpression"); + } - Scope.prototype.isStatic = function isStatic(node) { - if (t.isThisExpression(node) || t.isSuper(node)) { - return true; - } + if (this.isRelational("<")) { + var result = this.tsTryParseAndCatch(function () { + if (!noCalls && _this28.atPossibleAsync(base)) { + var asyncArrowFn = _this28.tsTryParseGenericAsyncArrowFunction(startPos, startLoc); - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (binding) { - return binding.constant; - } else { - return this.hasBinding(node.name); - } - } + if (asyncArrowFn) { + return asyncArrowFn; + } + } - return false; - }; + var node = _this28.startNodeAt(startPos, startLoc); - Scope.prototype.maybeGenerateMemoised = function maybeGenerateMemoised(node, dontPush) { - if (this.isStatic(node)) { - return null; - } else { - var _id2 = this.generateUidIdentifierBasedOnNode(node); - if (!dontPush) this.push({ id: _id2 }); - return _id2; - } - }; + node.callee = base; - Scope.prototype.checkBlockScopedCollisions = function checkBlockScopedCollisions(local, kind, name, id) { - if (kind === "param") return; + var typeArguments = _this28.tsParseTypeArguments(); - if (kind === "hoisted" && local.kind === "let") return; + if (typeArguments) { + if (!noCalls && _this28.eat(types.parenL)) { + node.arguments = _this28.parseCallExpressionArguments(types.parenR, false); + node.typeParameters = typeArguments; + return _this28.finishCallExpression(node, state.optionalChainMember); + } else if (_this28.match(types.backQuote)) { + return _this28.parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments); + } + } - var duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && (kind === "let" || kind === "const"); + _this28.unexpected(); + }); + if (result) return result; + } - if (duplicate) { - throw this.hub.file.buildCodeFrameError(id, messages.get("scopeDuplicateDeclaration", name), TypeError); - } - }; + return _get(_getPrototypeOf(_class4.prototype), "parseSubscript", this).call(this, base, startPos, startLoc, noCalls, state); + } + }, { + key: "parseNewArguments", + value: function parseNewArguments(node) { + var _this29 = this; - Scope.prototype.rename = function rename(oldName, newName, block) { - var binding = this.getBinding(oldName); - if (binding) { - newName = newName || this.generateUidIdentifier(oldName).name; - return new _renamer2.default(binding, oldName, newName).rename(block); - } - }; + if (this.isRelational("<")) { + var typeParameters = this.tsTryParseAndCatch(function () { + var args = _this29.tsParseTypeArguments(); - Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) { - if (map[oldName]) { - map[newName] = value; - map[oldName] = null; - } - }; + if (!_this29.match(types.parenL)) _this29.unexpected(); + return args; + }); - Scope.prototype.dump = function dump() { - var sep = (0, _repeat2.default)("-", 60); - console.log(sep); - var scope = this; - do { - console.log("#", scope.block.type); - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - console.log(" -", name, { - constant: binding.constant, - references: binding.references, - violations: binding.constantViolations.length, - kind: binding.kind - }); - } - } while (scope = scope.parent); - console.log(sep); - }; + if (typeParameters) { + node.typeParameters = typeParameters; + } + } - Scope.prototype.toArray = function toArray(node, i) { - var file = this.hub.file; + _get(_getPrototypeOf(_class4.prototype), "parseNewArguments", this).call(this, node); + } + }, { + key: "parseExprOp", + value: function parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) { + if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) { + var node = this.startNodeAt(leftStartPos, leftStartLoc); + node.expression = left; - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (binding && binding.constant && binding.path.isGenericType("Array")) return node; - } + var _const = this.tsTryNextParseConstantContext(); - if (t.isArrayExpression(node)) { - return node; - } + if (_const) { + node.typeAnnotation = _const; + } else { + node.typeAnnotation = this.tsNextThenParseType(); + } - if (t.isIdentifier(node, { name: "arguments" })) { - return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]); - } + this.finishNode(node, "TSAsExpression"); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); + } - var helperName = "toArray"; - var args = [node]; - if (i === true) { - helperName = "toConsumableArray"; - } else if (i) { - args.push(t.numericLiteral(i)); - helperName = "slicedToArray"; - } - return t.callExpression(file.addHelper(helperName), args); - }; + return _get(_getPrototypeOf(_class4.prototype), "parseExprOp", this).call(this, left, leftStartPos, leftStartLoc, minPrec, noIn); + } + }, { + key: "checkReservedWord", + value: function checkReservedWord(word, startLoc, checkKeywords, isBinding) {} + }, { + key: "checkDuplicateExports", + value: function checkDuplicateExports() {} + }, { + key: "parseImport", + value: function parseImport(node) { + if (this.match(types.name) && this.lookahead().type === types.eq) { + return this.tsParseImportEqualsDeclaration(node); + } - Scope.prototype.hasLabel = function hasLabel(name) { - return !!this.getLabel(name); - }; + return _get(_getPrototypeOf(_class4.prototype), "parseImport", this).call(this, node); + } + }, { + key: "parseExport", + value: function parseExport(node) { + if (this.match(types._import)) { + this.expect(types._import); + return this.tsParseImportEqualsDeclaration(node, true); + } else if (this.eat(types.eq)) { + var assign = node; + assign.expression = this.parseExpression(); + this.semicolon(); + return this.finishNode(assign, "TSExportAssignment"); + } else if (this.eatContextual("as")) { + var decl = node; + this.expectContextual("namespace"); + decl.id = this.parseIdentifier(); + this.semicolon(); + return this.finishNode(decl, "TSNamespaceExportDeclaration"); + } else { + return _get(_getPrototypeOf(_class4.prototype), "parseExport", this).call(this, node); + } + } + }, { + key: "isAbstractClass", + value: function isAbstractClass() { + return this.isContextual("abstract") && this.lookahead().type === types._class; + } + }, { + key: "parseExportDefaultExpression", + value: function parseExportDefaultExpression() { + if (this.isAbstractClass()) { + var cls = this.startNode(); + this.next(); + this.parseClass(cls, true, true); + cls.abstract = true; + return cls; + } - Scope.prototype.getLabel = function getLabel(name) { - return this.labels.get(name); - }; + if (this.state.value === "interface") { + var result = this.tsParseDeclaration(this.startNode(), this.state.value, true); + if (result) return result; + } - Scope.prototype.registerLabel = function registerLabel(path) { - this.labels.set(path.node.label.name, path); - }; + return _get(_getPrototypeOf(_class4.prototype), "parseExportDefaultExpression", this).call(this); + } + }, { + key: "parseStatementContent", + value: function parseStatementContent(context, topLevel) { + if (this.state.type === types._const) { + var ahead = this.lookahead(); + + if (ahead.type === types.name && ahead.value === "enum") { + var node = this.startNode(); + this.expect(types._const); + this.expectContextual("enum"); + return this.tsParseEnumDeclaration(node, true); + } + } - Scope.prototype.registerDeclaration = function registerDeclaration(path) { - if (path.isLabeledStatement()) { - this.registerLabel(path); - } else if (path.isFunctionDeclaration()) { - this.registerBinding("hoisted", path.get("id"), path); - } else if (path.isVariableDeclaration()) { - var declarations = path.get("declarations"); - for (var _iterator7 = declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; + return _get(_getPrototypeOf(_class4.prototype), "parseStatementContent", this).call(this, context, topLevel); + } + }, { + key: "parseAccessModifier", + value: function parseAccessModifier() { + return this.tsParseModifier(["public", "protected", "private"]); + } + }, { + key: "parseClassMember", + value: function parseClassMember(classBody, member, state, constructorAllowsSuper) { + var accessibility = this.parseAccessModifier(); + if (accessibility) member.accessibility = accessibility; - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; + _get(_getPrototypeOf(_class4.prototype), "parseClassMember", this).call(this, classBody, member, state, constructorAllowsSuper); } + }, { + key: "parseClassMemberWithIsStatic", + value: function parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) { + var modifiers = this.tsParseModifiers(["abstract", "readonly", "declare"]); + Object.assign(member, modifiers); + var idx = this.tsTryParseIndexSignature(member); + + if (idx) { + classBody.body.push(idx); + + if (modifiers.abstract) { + this.raise(member.start, "Index signatures cannot have the 'abstract' modifier"); + } - var declar = _ref7; + if (isStatic) { + this.raise(member.start, "Index signatures cannot have the 'static' modifier"); + } - this.registerBinding(path.node.kind, declar); - } - } else if (path.isClassDeclaration()) { - this.registerBinding("let", path); - } else if (path.isImportDeclaration()) { - var specifiers = path.get("specifiers"); - for (var _iterator8 = specifiers, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; + if (member.accessibility) { + this.raise(member.start, "Index signatures cannot have an accessibility modifier ('".concat(member.accessibility, "')")); + } - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref8 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref8 = _i8.value; + return; + } + + _get(_getPrototypeOf(_class4.prototype), "parseClassMemberWithIsStatic", this).call(this, classBody, member, state, isStatic, constructorAllowsSuper); } + }, { + key: "parsePostMemberNameModifiers", + value: function parsePostMemberNameModifiers(methodOrProp) { + var optional = this.eat(types.question); + if (optional) methodOrProp.optional = true; + + if (methodOrProp.readonly && this.match(types.parenL)) { + this.raise(methodOrProp.start, "Class methods cannot have the 'readonly' modifier"); + } - var specifier = _ref8; + if (methodOrProp.declare && this.match(types.parenL)) { + this.raise(methodOrProp.start, "Class methods cannot have the 'declare' modifier"); + } + } + }, { + key: "parseExpressionStatement", + value: function parseExpressionStatement(node, expr) { + var decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined; + return decl || _get(_getPrototypeOf(_class4.prototype), "parseExpressionStatement", this).call(this, node, expr); + } + }, { + key: "shouldParseExportDeclaration", + value: function shouldParseExportDeclaration() { + if (this.tsIsDeclarationStart()) return true; + return _get(_getPrototypeOf(_class4.prototype), "shouldParseExportDeclaration", this).call(this); + } + }, { + key: "parseConditional", + value: function parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) { + var _this30 = this; - this.registerBinding("module", specifier); - } - } else if (path.isExportDeclaration()) { - var _declar = path.get("declaration"); - if (_declar.isClassDeclaration() || _declar.isFunctionDeclaration() || _declar.isVariableDeclaration()) { - this.registerDeclaration(_declar); - } - } else { - this.registerBinding("unknown", path); - } - }; + if (!refNeedsArrowPos || !this.match(types.question)) { + return _get(_getPrototypeOf(_class4.prototype), "parseConditional", this).call(this, expr, noIn, startPos, startLoc, refNeedsArrowPos); + } - Scope.prototype.buildUndefinedNode = function buildUndefinedNode() { - if (this.hasBinding("undefined")) { - return t.unaryExpression("void", t.numericLiteral(0), true); - } else { - return t.identifier("undefined"); - } - }; + var result = this.tryParse(function () { + return _get(_getPrototypeOf(_class4.prototype), "parseConditional", _this30).call(_this30, expr, noIn, startPos, startLoc); + }); - Scope.prototype.registerConstantViolation = function registerConstantViolation(path) { - var ids = path.getBindingIdentifiers(); - for (var name in ids) { - var binding = this.getBinding(name); - if (binding) binding.reassign(path); - } - }; + if (!result.node) { + refNeedsArrowPos.start = result.error.pos || this.state.start; + return expr; + } - Scope.prototype.registerBinding = function registerBinding(kind, path) { - var bindingPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : path; + if (result.error) this.state = result.failState; + return result.node; + } + }, { + key: "parseParenItem", + value: function parseParenItem(node, startPos, startLoc) { + node = _get(_getPrototypeOf(_class4.prototype), "parseParenItem", this).call(this, node, startPos, startLoc); - if (!kind) throw new ReferenceError("no `kind`"); + if (this.eat(types.question)) { + node.optional = true; + this.resetEndLocation(node); + } - if (path.isVariableDeclaration()) { - var declarators = path.get("declarations"); - for (var _iterator9 = declarators, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; + if (this.match(types.colon)) { + var typeCastNode = this.startNodeAt(startPos, startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TSTypeCastExpression"); + } - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref9 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref9 = _i9.value; + return node; } + }, { + key: "parseExportDeclaration", + value: function parseExportDeclaration(node) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var isDeclare = this.eatContextual("declare"); + var declaration; + + if (this.match(types.name)) { + declaration = this.tsTryParseExportDeclaration(); + } - var declar = _ref9; + if (!declaration) { + declaration = _get(_getPrototypeOf(_class4.prototype), "parseExportDeclaration", this).call(this, node); + } - this.registerBinding(kind, declar); - } - return; - } + if (declaration && isDeclare) { + this.resetStartLocation(declaration, startPos, startLoc); + declaration.declare = true; + } - var parent = this.getProgramParent(); - var ids = path.getBindingIdentifiers(true); + return declaration; + } + }, { + key: "parseClassId", + value: function parseClassId(node, isStatement, optionalId) { + if ((!isStatement || optionalId) && this.isContextual("implements")) { + return; + } - for (var name in ids) { - for (var _iterator10 = ids[name], _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { - var _ref10; + _get(_getPrototypeOf(_class4.prototype), "parseClassId", this).call(this, node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS); - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref10 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref10 = _i10.value; + var typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) node.typeParameters = typeParameters; } + }, { + key: "parseClassPropertyAnnotation", + value: function parseClassPropertyAnnotation(node) { + if (!node.optional && this.eat(types.bang)) { + node.definite = true; + } - var _id3 = _ref10; + var type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + } + }, { + key: "parseClassProperty", + value: function parseClassProperty(node) { + this.parseClassPropertyAnnotation(node); - var local = this.getOwnBinding(name); - if (local) { - if (local.identifier === _id3) continue; + if (node.declare && this.match(types.equal)) { + this.raise(this.state.start, "'declare' class fields cannot have an initializer"); + } - this.checkBlockScopedCollisions(local, kind, name, _id3); + return _get(_getPrototypeOf(_class4.prototype), "parseClassProperty", this).call(this, node); } + }, { + key: "parseClassPrivateProperty", + value: function parseClassPrivateProperty(node) { + if (node.abstract) { + this.raise(node.start, "Private elements cannot have the 'abstract' modifier."); + } - if (local && local.path.isFlow()) local = null; - - parent.references[name] = true; + if (node.accessibility) { + this.raise(node.start, "Private elements cannot have an accessibility modifier ('".concat(node.accessibility, "')")); + } - this.bindings[name] = new _binding3.default({ - identifier: _id3, - existing: local, - scope: this, - path: bindingPath, - kind: kind - }); - } - } - }; + this.parseClassPropertyAnnotation(node); + return _get(_getPrototypeOf(_class4.prototype), "parseClassPrivateProperty", this).call(this, node); + } + }, { + key: "pushClassMethod", + value: function pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + var typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) method.typeParameters = typeParameters; - Scope.prototype.addGlobal = function addGlobal(node) { - this.globals[node.name] = node; - }; + _get(_getPrototypeOf(_class4.prototype), "pushClassMethod", this).call(this, classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + } + }, { + key: "pushClassPrivateMethod", + value: function pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + var typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) method.typeParameters = typeParameters; - Scope.prototype.hasUid = function hasUid(name) { - var scope = this; + _get(_getPrototypeOf(_class4.prototype), "pushClassPrivateMethod", this).call(this, classBody, method, isGenerator, isAsync); + } + }, { + key: "parseClassSuper", + value: function parseClassSuper(node) { + _get(_getPrototypeOf(_class4.prototype), "parseClassSuper", this).call(this, node); - do { - if (scope.uids[name]) return true; - } while (scope = scope.parent); + if (node.superClass && this.isRelational("<")) { + node.superTypeParameters = this.tsParseTypeArguments(); + } - return false; - }; + if (this.eatContextual("implements")) { + node.implements = this.tsParseHeritageClause("implements"); + } + } + }, { + key: "parseObjPropValue", + value: function parseObjPropValue(prop) { + var _get2; - Scope.prototype.hasGlobal = function hasGlobal(name) { - var scope = this; + var typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) prop.typeParameters = typeParameters; - do { - if (scope.globals[name]) return true; - } while (scope = scope.parent); + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } - return false; - }; + (_get2 = _get(_getPrototypeOf(_class4.prototype), "parseObjPropValue", this)).call.apply(_get2, [this, prop].concat(args)); + } + }, { + key: "parseFunctionParams", + value: function parseFunctionParams(node, allowModifiers) { + var typeParameters = this.tsTryParseTypeParameters(); + if (typeParameters) node.typeParameters = typeParameters; - Scope.prototype.hasReference = function hasReference(name) { - var scope = this; + _get(_getPrototypeOf(_class4.prototype), "parseFunctionParams", this).call(this, node, allowModifiers); + } + }, { + key: "parseVarId", + value: function parseVarId(decl, kind) { + _get(_getPrototypeOf(_class4.prototype), "parseVarId", this).call(this, decl, kind); - do { - if (scope.references[name]) return true; - } while (scope = scope.parent); + if (decl.id.type === "Identifier" && this.eat(types.bang)) { + decl.definite = true; + } - return false; - }; + var type = this.tsTryParseTypeAnnotation(); - Scope.prototype.isPure = function isPure(node, constantsOnly) { - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (!binding) return false; - if (constantsOnly) return binding.constant; - return true; - } else if (t.isClass(node)) { - if (node.superClass && !this.isPure(node.superClass, constantsOnly)) return false; - return this.isPure(node.body, constantsOnly); - } else if (t.isClassBody(node)) { - for (var _iterator11 = node.body, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : (0, _getIterator3.default)(_iterator11);;) { - var _ref11; + if (type) { + decl.id.typeAnnotation = type; + this.resetEndLocation(decl.id); + } + } + }, { + key: "parseAsyncArrowFromCallExpression", + value: function parseAsyncArrowFromCallExpression(node, call) { + if (this.match(types.colon)) { + node.returnType = this.tsParseTypeAnnotation(); + } - if (_isArray11) { - if (_i11 >= _iterator11.length) break; - _ref11 = _iterator11[_i11++]; - } else { - _i11 = _iterator11.next(); - if (_i11.done) break; - _ref11 = _i11.value; + return _get(_getPrototypeOf(_class4.prototype), "parseAsyncArrowFromCallExpression", this).call(this, node, call); } + }, { + key: "parseMaybeAssign", + value: function parseMaybeAssign() { + var _this31 = this; - var method = _ref11; + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } - if (!this.isPure(method, constantsOnly)) return false; - } - return true; - } else if (t.isBinary(node)) { - return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); - } else if (t.isArrayExpression(node)) { - for (var _iterator12 = node.elements, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : (0, _getIterator3.default)(_iterator12);;) { - var _ref12; + var state; + var jsx; + var typeCast; - if (_isArray12) { - if (_i12 >= _iterator12.length) break; - _ref12 = _iterator12[_i12++]; - } else { - _i12 = _iterator12.next(); - if (_i12.done) break; - _ref12 = _i12.value; - } + if (this.match(types.jsxTagStart)) { + state = this.state.clone(); + jsx = this.tryParse(function () { + var _get3; - var elem = _ref12; + return (_get3 = _get(_getPrototypeOf(_class4.prototype), "parseMaybeAssign", _this31)).call.apply(_get3, [_this31].concat(args)); + }, state); + if (!jsx.error) return jsx.node; + var context = this.state.context; - if (!this.isPure(elem, constantsOnly)) return false; - } - return true; - } else if (t.isObjectExpression(node)) { - for (var _iterator13 = node.properties, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : (0, _getIterator3.default)(_iterator13);;) { - var _ref13; + if (context[context.length - 1] === types$1.j_oTag) { + context.length -= 2; + } else if (context[context.length - 1] === types$1.j_expr) { + context.length -= 1; + } + } - if (_isArray13) { - if (_i13 >= _iterator13.length) break; - _ref13 = _iterator13[_i13++]; - } else { - _i13 = _iterator13.next(); - if (_i13.done) break; - _ref13 = _i13.value; - } + if (!(jsx && jsx.error) && !this.isRelational("<")) { + var _get4; - var prop = _ref13; + return (_get4 = _get(_getPrototypeOf(_class4.prototype), "parseMaybeAssign", this)).call.apply(_get4, [this].concat(args)); + } - if (!this.isPure(prop, constantsOnly)) return false; - } - return true; - } else if (t.isClassMethod(node)) { - if (node.computed && !this.isPure(node.key, constantsOnly)) return false; - if (node.kind === "get" || node.kind === "set") return false; - return true; - } else if (t.isClassProperty(node) || t.isObjectProperty(node)) { - if (node.computed && !this.isPure(node.key, constantsOnly)) return false; - return this.isPure(node.value, constantsOnly); - } else if (t.isUnaryExpression(node)) { - return this.isPure(node.argument, constantsOnly); - } else { - return t.isPureish(node); - } - }; + var typeParameters; + state = state || this.state.clone(); + var arrow = this.tryParse(function (abort) { + var _get5; - Scope.prototype.setData = function setData(key, val) { - return this.data[key] = val; - }; + typeParameters = _this31.tsParseTypeParameters(); - Scope.prototype.getData = function getData(key) { - var scope = this; - do { - var data = scope.data[key]; - if (data != null) return data; - } while (scope = scope.parent); - }; + var expr = (_get5 = _get(_getPrototypeOf(_class4.prototype), "parseMaybeAssign", _this31)).call.apply(_get5, [_this31].concat(args)); - Scope.prototype.removeData = function removeData(key) { - var scope = this; - do { - var data = scope.data[key]; - if (data != null) scope.data[key] = null; - } while (scope = scope.parent); - }; + if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) { + abort(); + } - Scope.prototype.init = function init() { - if (!this.references) this.crawl(); - }; + if (typeParameters && typeParameters.params.length !== 0) { + _this31.resetStartLocationFromNode(expr, typeParameters); + } - Scope.prototype.crawl = function crawl() { - _crawlCallsCount++; - this._crawl(); - _crawlCallsCount--; - }; + expr.typeParameters = typeParameters; + return expr; + }, state); + if (!arrow.error && !arrow.aborted) return arrow.node; - Scope.prototype._crawl = function _crawl() { - var path = this.path; + if (!jsx) { + assert(!this.hasPlugin("jsx")); + typeCast = this.tryParse(function () { + var _get6; - this.references = (0, _create2.default)(null); - this.bindings = (0, _create2.default)(null); - this.globals = (0, _create2.default)(null); - this.uids = (0, _create2.default)(null); - this.data = (0, _create2.default)(null); + return (_get6 = _get(_getPrototypeOf(_class4.prototype), "parseMaybeAssign", _this31)).call.apply(_get6, [_this31].concat(args)); + }, state); + if (!typeCast.error) return typeCast.node; + } - if (path.isLoop()) { - for (var _iterator14 = t.FOR_INIT_KEYS, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : (0, _getIterator3.default)(_iterator14);;) { - var _ref14; + if (jsx && jsx.node) { + this.state = jsx.failState; + return jsx.node; + } - if (_isArray14) { - if (_i14 >= _iterator14.length) break; - _ref14 = _iterator14[_i14++]; - } else { - _i14 = _iterator14.next(); - if (_i14.done) break; - _ref14 = _i14.value; - } + if (arrow.node) { + this.state = arrow.failState; + return arrow.node; + } - var key = _ref14; + if (typeCast && typeCast.node) { + this.state = typeCast.failState; + return typeCast.node; + } - var node = path.get(key); - if (node.isBlockScoped()) this.registerBinding(node.node.kind, node); - } - } + if (jsx && jsx.thrown) throw jsx.error; + if (arrow.thrown) throw arrow.error; + if (typeCast && typeCast.thrown) throw typeCast.error; + throw jsx && jsx.error || arrow.error || typeCast && typeCast.error; + } + }, { + key: "parseMaybeUnary", + value: function parseMaybeUnary(refShorthandDefaultPos) { + if (!this.hasPlugin("jsx") && this.isRelational("<")) { + return this.tsParseTypeAssertion(); + } else { + return _get(_getPrototypeOf(_class4.prototype), "parseMaybeUnary", this).call(this, refShorthandDefaultPos); + } + } + }, { + key: "parseArrow", + value: function parseArrow(node) { + var _this32 = this; - if (path.isFunctionExpression() && path.has("id")) { - if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { - this.registerBinding("local", path.get("id"), path); - } - } + if (this.match(types.colon)) { + var result = this.tryParse(function (abort) { + var returnType = _this32.tsParseTypeOrTypePredicateAnnotation(types.colon); - if (path.isClassExpression() && path.has("id")) { - if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { - this.registerBinding("local", path); - } - } + if (_this32.canInsertSemicolon() || !_this32.match(types.arrow)) abort(); + return returnType; + }); + if (result.aborted) return; - if (path.isFunction()) { - var params = path.get("params"); - for (var _iterator15 = params, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : (0, _getIterator3.default)(_iterator15);;) { - var _ref15; + if (!result.thrown) { + if (result.error) this.state = result.failState; + node.returnType = result.node; + } + } - if (_isArray15) { - if (_i15 >= _iterator15.length) break; - _ref15 = _iterator15[_i15++]; - } else { - _i15 = _iterator15.next(); - if (_i15.done) break; - _ref15 = _i15.value; + return _get(_getPrototypeOf(_class4.prototype), "parseArrow", this).call(this, node); } + }, { + key: "parseAssignableListItemTypes", + value: function parseAssignableListItemTypes(param) { + if (this.eat(types.question)) { + if (param.type !== "Identifier") { + this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature."); + } - var param = _ref15; + param.optional = true; + } - this.registerBinding("param", param); - } - } + var type = this.tsTryParseTypeAnnotation(); + if (type) param.typeAnnotation = type; + this.resetEndLocation(param); + return param; + } + }, { + key: "toAssignable", + value: function toAssignable(node, isBinding, contextDescription) { + switch (node.type) { + case "TSTypeCastExpression": + return _get(_getPrototypeOf(_class4.prototype), "toAssignable", this).call(this, this.typeCastToParameter(node), isBinding, contextDescription); + + case "TSParameterProperty": + return _get(_getPrototypeOf(_class4.prototype), "toAssignable", this).call(this, node, isBinding, contextDescription); + + case "TSAsExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + node.expression = this.toAssignable(node.expression, isBinding, contextDescription); + return node; - if (path.isCatchClause()) { - this.registerBinding("let", path); - } + default: + return _get(_getPrototypeOf(_class4.prototype), "toAssignable", this).call(this, node, isBinding, contextDescription); + } + } + }, { + key: "checkLVal", + value: function checkLVal(expr) { + var bindingType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : BIND_NONE; + var checkClashes = arguments.length > 2 ? arguments[2] : undefined; + var contextDescription = arguments.length > 3 ? arguments[3] : undefined; + + switch (expr.type) { + case "TSTypeCastExpression": + return; - var parent = this.getProgramParent(); - if (parent.crawling) return; + case "TSParameterProperty": + this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property"); + return; - var state = { - references: [], - constantViolations: [], - assignments: [] - }; + case "TSAsExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription); + return; - this.crawling = true; - path.traverse(collectorVisitor, state); - this.crawling = false; + default: + _get(_getPrototypeOf(_class4.prototype), "checkLVal", this).call(this, expr, bindingType, checkClashes, contextDescription); - for (var _iterator16 = state.assignments, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : (0, _getIterator3.default)(_iterator16);;) { - var _ref16; + return; + } + } + }, { + key: "parseBindingAtom", + value: function parseBindingAtom() { + switch (this.state.type) { + case types._this: + return this.parseIdentifier(true); - if (_isArray16) { - if (_i16 >= _iterator16.length) break; - _ref16 = _iterator16[_i16++]; - } else { - _i16 = _iterator16.next(); - if (_i16.done) break; - _ref16 = _i16.value; - } + default: + return _get(_getPrototypeOf(_class4.prototype), "parseBindingAtom", this).call(this); + } + } + }, { + key: "parseMaybeDecoratorArguments", + value: function parseMaybeDecoratorArguments(expr) { + if (this.isRelational("<")) { + var typeArguments = this.tsParseTypeArguments(); - var _path = _ref16; + if (this.match(types.parenL)) { + var call = _get(_getPrototypeOf(_class4.prototype), "parseMaybeDecoratorArguments", this).call(this, expr); - var ids = _path.getBindingIdentifiers(); - var programParent = void 0; - for (var name in ids) { - if (_path.scope.getBinding(name)) continue; + call.typeParameters = typeArguments; + return call; + } - programParent = programParent || _path.scope.getProgramParent(); - programParent.addGlobal(ids[name]); - } + this.unexpected(this.state.start, types.parenL); + } - _path.scope.registerConstantViolation(_path); - } + return _get(_getPrototypeOf(_class4.prototype), "parseMaybeDecoratorArguments", this).call(this, expr); + } + }, { + key: "isClassMethod", + value: function isClassMethod() { + return this.isRelational("<") || _get(_getPrototypeOf(_class4.prototype), "isClassMethod", this).call(this); + } + }, { + key: "isClassProperty", + value: function isClassProperty() { + return this.match(types.bang) || this.match(types.colon) || _get(_getPrototypeOf(_class4.prototype), "isClassProperty", this).call(this); + } + }, { + key: "parseMaybeDefault", + value: function parseMaybeDefault() { + var _get7; - for (var _iterator17 = state.references, _isArray17 = Array.isArray(_iterator17), _i17 = 0, _iterator17 = _isArray17 ? _iterator17 : (0, _getIterator3.default)(_iterator17);;) { - var _ref17; + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } - if (_isArray17) { - if (_i17 >= _iterator17.length) break; - _ref17 = _iterator17[_i17++]; - } else { - _i17 = _iterator17.next(); - if (_i17.done) break; - _ref17 = _i17.value; - } + var node = (_get7 = _get(_getPrototypeOf(_class4.prototype), "parseMaybeDefault", this)).call.apply(_get7, [this].concat(args)); - var ref = _ref17; + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`"); + } - var binding = ref.scope.getBinding(ref.node.name); - if (binding) { - binding.reference(ref); - } else { - ref.scope.getProgramParent().addGlobal(ref.node); - } - } + return node; + } + }, { + key: "getTokenFromCode", + value: function getTokenFromCode(code) { + if (this.state.inType && (code === 62 || code === 60)) { + return this.finishOp(types.relational, 1); + } else { + return _get(_getPrototypeOf(_class4.prototype), "getTokenFromCode", this).call(this, code); + } + } + }, { + key: "toAssignableList", + value: function toAssignableList(exprList) { + for (var i = 0; i < exprList.length; i++) { + var expr = exprList[i]; + if (!expr) continue; + + switch (expr.type) { + case "TSTypeCastExpression": + exprList[i] = this.typeCastToParameter(expr); + break; + + case "TSAsExpression": + case "TSTypeAssertion": + this.raise(expr.start, "Unexpected type cast in parameter position."); + break; + } + } - for (var _iterator18 = state.constantViolations, _isArray18 = Array.isArray(_iterator18), _i18 = 0, _iterator18 = _isArray18 ? _iterator18 : (0, _getIterator3.default)(_iterator18);;) { - var _ref18; + return _get(_getPrototypeOf(_class4.prototype), "toAssignableList", this).apply(this, arguments); + } + }, { + key: "typeCastToParameter", + value: function typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); + return node.expression; + } + }, { + key: "toReferencedList", + value: function toReferencedList(exprList, isInParens) { + for (var i = 0; i < exprList.length; i++) { + var expr = exprList[i]; + + if (expr && expr._exprListItem && expr.type === "TsTypeCastExpression") { + this.raise(expr.start, "Did not expect a type annotation here."); + } + } - if (_isArray18) { - if (_i18 >= _iterator18.length) break; - _ref18 = _iterator18[_i18++]; - } else { - _i18 = _iterator18.next(); - if (_i18.done) break; - _ref18 = _i18.value; - } + return exprList; + } + }, { + key: "shouldParseArrow", + value: function shouldParseArrow() { + return this.match(types.colon) || _get(_getPrototypeOf(_class4.prototype), "shouldParseArrow", this).call(this); + } + }, { + key: "shouldParseAsyncArrow", + value: function shouldParseAsyncArrow() { + return this.match(types.colon) || _get(_getPrototypeOf(_class4.prototype), "shouldParseAsyncArrow", this).call(this); + } + }, { + key: "canHaveLeadingDecorator", + value: function canHaveLeadingDecorator() { + return _get(_getPrototypeOf(_class4.prototype), "canHaveLeadingDecorator", this).call(this) || this.isAbstractClass(); + } + }, { + key: "jsxParseOpeningElementAfterName", + value: function jsxParseOpeningElementAfterName(node) { + var _this33 = this; - var _path2 = _ref18; + if (this.isRelational("<")) { + var typeArguments = this.tsTryParseAndCatch(function () { + return _this33.tsParseTypeArguments(); + }); + if (typeArguments) node.typeParameters = typeArguments; + } - _path2.scope.registerConstantViolation(_path2); - } - }; + return _get(_getPrototypeOf(_class4.prototype), "jsxParseOpeningElementAfterName", this).call(this, node); + } + }, { + key: "getGetterSetterExpectedParamCount", + value: function getGetterSetterExpectedParamCount(method) { + var baseCount = _get(_getPrototypeOf(_class4.prototype), "getGetterSetterExpectedParamCount", this).call(this, method); + + var firstParam = method.params[0]; + var hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this"; + return hasContextParam ? baseCount + 1 : baseCount; + } + }]); - Scope.prototype.push = function push(opts) { - var path = this.path; + return _class4; + }(superClass) + ); +}; - if (!path.isBlockStatement() && !path.isProgram()) { - path = this.getBlockParent().path; - } +types.placeholder = new TokenType("%%", { + startsExpr: true +}); - if (path.isSwitchStatement()) { - path = this.getFunctionParent().path; - } +var placeholders = function placeholders(superClass) { + return ( + /*#__PURE__*/ + function (_superClass5) { + _inherits(_class5, _superClass5); + + function _class5() { + _classCallCheck(this, _class5); + + return _possibleConstructorReturn(this, _getPrototypeOf(_class5).apply(this, arguments)); + } + + _createClass(_class5, [{ + key: "parsePlaceholder", + value: function parsePlaceholder(expectedNode) { + if (this.match(types.placeholder)) { + var node = this.startNode(); + this.next(); + this.assertNoSpace("Unexpected space in placeholder."); + node.name = _get(_getPrototypeOf(_class5.prototype), "parseIdentifier", this).call(this, true); + this.assertNoSpace("Unexpected space in placeholder."); + this.expect(types.placeholder); + return this.finishPlaceholder(node, expectedNode); + } + } + }, { + key: "finishPlaceholder", + value: function finishPlaceholder(node, expectedNode) { + var isFinished = !!(node.expectedNode && node.type === "Placeholder"); + node.expectedNode = expectedNode; + return isFinished ? node : this.finishNode(node, "Placeholder"); + } + }, { + key: "getTokenFromCode", + value: function getTokenFromCode(code) { + if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { + return this.finishOp(types.placeholder, 2); + } - if (path.isLoop() || path.isCatchClause() || path.isFunction()) { - t.ensureBlock(path.node); - path = path.get("body"); - } + return _get(_getPrototypeOf(_class5.prototype), "getTokenFromCode", this).apply(this, arguments); + } + }, { + key: "parseExprAtom", + value: function parseExprAtom() { + return this.parsePlaceholder("Expression") || _get(_getPrototypeOf(_class5.prototype), "parseExprAtom", this).apply(this, arguments); + } + }, { + key: "parseIdentifier", + value: function parseIdentifier() { + return this.parsePlaceholder("Identifier") || _get(_getPrototypeOf(_class5.prototype), "parseIdentifier", this).apply(this, arguments); + } + }, { + key: "checkReservedWord", + value: function checkReservedWord(word) { + if (word !== undefined) _get(_getPrototypeOf(_class5.prototype), "checkReservedWord", this).apply(this, arguments); + } + }, { + key: "parseBindingAtom", + value: function parseBindingAtom() { + return this.parsePlaceholder("Pattern") || _get(_getPrototypeOf(_class5.prototype), "parseBindingAtom", this).apply(this, arguments); + } + }, { + key: "checkLVal", + value: function checkLVal(expr) { + if (expr.type !== "Placeholder") _get(_getPrototypeOf(_class5.prototype), "checkLVal", this).apply(this, arguments); + } + }, { + key: "toAssignable", + value: function toAssignable(node) { + if (node && node.type === "Placeholder" && node.expectedNode === "Expression") { + node.expectedNode = "Pattern"; + return node; + } - var unique = opts.unique; - var kind = opts.kind || "var"; - var blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; + return _get(_getPrototypeOf(_class5.prototype), "toAssignable", this).apply(this, arguments); + } + }, { + key: "verifyBreakContinue", + value: function verifyBreakContinue(node) { + if (node.label && node.label.type === "Placeholder") return; - var dataKey = "declaration:" + kind + ":" + blockHoist; - var declarPath = !unique && path.getData(dataKey); + _get(_getPrototypeOf(_class5.prototype), "verifyBreakContinue", this).apply(this, arguments); + } + }, { + key: "parseExpressionStatement", + value: function parseExpressionStatement(node, expr) { + if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) { + return _get(_getPrototypeOf(_class5.prototype), "parseExpressionStatement", this).apply(this, arguments); + } - if (!declarPath) { - var declar = t.variableDeclaration(kind, []); - declar._generated = true; - declar._blockHoist = blockHoist; + if (this.match(types.colon)) { + var stmt = node; + stmt.label = this.finishPlaceholder(expr, "Identifier"); + this.next(); + stmt.body = this.parseStatement("label"); + return this.finishNode(stmt, "LabeledStatement"); + } - var _path$unshiftContaine = path.unshiftContainer("body", [declar]); + this.semicolon(); + node.name = expr.name; + return this.finishPlaceholder(node, "Statement"); + } + }, { + key: "parseBlock", + value: function parseBlock() { + return this.parsePlaceholder("BlockStatement") || _get(_getPrototypeOf(_class5.prototype), "parseBlock", this).apply(this, arguments); + } + }, { + key: "parseFunctionId", + value: function parseFunctionId() { + return this.parsePlaceholder("Identifier") || _get(_getPrototypeOf(_class5.prototype), "parseFunctionId", this).apply(this, arguments); + } + }, { + key: "parseClass", + value: function parseClass(node, isStatement, optionalId) { + var type = isStatement ? "ClassDeclaration" : "ClassExpression"; + this.next(); + this.takeDecorators(node); + var placeholder = this.parsePlaceholder("Identifier"); + + if (placeholder) { + if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) { + node.id = placeholder; + } else if (optionalId || !isStatement) { + node.id = null; + node.body = this.finishPlaceholder(placeholder, "ClassBody"); + return this.finishNode(node, type); + } else { + this.unexpected(null, "A class name is required"); + } + } else { + this.parseClassId(node, isStatement, optionalId); + } - declarPath = _path$unshiftContaine[0]; + this.parseClassSuper(node); + node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass); + return this.finishNode(node, type); + } + }, { + key: "parseExport", + value: function parseExport(node) { + var placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return _get(_getPrototypeOf(_class5.prototype), "parseExport", this).apply(this, arguments); + + if (!this.isContextual("from") && !this.match(types.comma)) { + node.specifiers = []; + node.source = null; + node.declaration = this.finishPlaceholder(placeholder, "Declaration"); + return this.finishNode(node, "ExportNamedDeclaration"); + } - if (!unique) path.setData(dataKey, declarPath); - } + this.expectPlugin("exportDefaultFrom"); + var specifier = this.startNode(); + specifier.exported = placeholder; + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return _get(_getPrototypeOf(_class5.prototype), "parseExport", this).call(this, node); + } + }, { + key: "maybeParseExportDefaultSpecifier", + value: function maybeParseExportDefaultSpecifier(node) { + if (node.specifiers && node.specifiers.length > 0) { + return true; + } - var declarator = t.variableDeclarator(opts.id, opts.init); - declarPath.node.declarations.push(declarator); - this.registerBinding(kind, declarPath.get("declarations").pop()); - }; + return _get(_getPrototypeOf(_class5.prototype), "maybeParseExportDefaultSpecifier", this).apply(this, arguments); + } + }, { + key: "checkExport", + value: function checkExport(node) { + var specifiers = node.specifiers; + + if (specifiers && specifiers.length) { + node.specifiers = specifiers.filter(function (node) { + return node.exported.type === "Placeholder"; + }); + } - Scope.prototype.getProgramParent = function getProgramParent() { - var scope = this; - do { - if (scope.path.isProgram()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a Function or Program..."); - }; + _get(_getPrototypeOf(_class5.prototype), "checkExport", this).call(this, node); - Scope.prototype.getFunctionParent = function getFunctionParent() { - var scope = this; - do { - if (scope.path.isFunctionParent()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a Function or Program..."); - }; + node.specifiers = specifiers; + } + }, { + key: "parseImport", + value: function parseImport(node) { + var placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return _get(_getPrototypeOf(_class5.prototype), "parseImport", this).apply(this, arguments); + node.specifiers = []; + + if (!this.isContextual("from") && !this.match(types.comma)) { + node.source = this.finishPlaceholder(placeholder, "StringLiteral"); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } - Scope.prototype.getBlockParent = function getBlockParent() { - var scope = this; - do { - if (scope.path.isBlockParent()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); - }; + var specifier = this.startNodeAtNode(placeholder); + specifier.local = placeholder; + this.finishNode(specifier, "ImportDefaultSpecifier"); + node.specifiers.push(specifier); - Scope.prototype.getAllBindings = function getAllBindings() { - var ids = (0, _create2.default)(null); + if (this.eat(types.comma)) { + var hasStarImport = this.maybeParseStarImportSpecifier(node); + if (!hasStarImport) this.parseNamedImportSpecifiers(node); + } - var scope = this; - do { - (0, _defaults2.default)(ids, scope.bindings); - scope = scope.parent; - } while (scope); + this.expectContextual("from"); + node.source = this.parseImportSource(); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + }, { + key: "parseImportSource", + value: function parseImportSource() { + return this.parsePlaceholder("StringLiteral") || _get(_getPrototypeOf(_class5.prototype), "parseImportSource", this).apply(this, arguments); + } + }]); - return ids; - }; + return _class5; + }(superClass) + ); +}; - Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind() { - var ids = (0, _create2.default)(null); +var v8intrinsic = function v8intrinsic(superClass) { + return ( + /*#__PURE__*/ + function (_superClass6) { + _inherits(_class6, _superClass6); - for (var _iterator19 = arguments, _isArray19 = Array.isArray(_iterator19), _i19 = 0, _iterator19 = _isArray19 ? _iterator19 : (0, _getIterator3.default)(_iterator19);;) { - var _ref19; + function _class6() { + _classCallCheck(this, _class6); - if (_isArray19) { - if (_i19 >= _iterator19.length) break; - _ref19 = _iterator19[_i19++]; - } else { - _i19 = _iterator19.next(); - if (_i19.done) break; - _ref19 = _i19.value; + return _possibleConstructorReturn(this, _getPrototypeOf(_class6).apply(this, arguments)); } - var kind = _ref19; - - var scope = this; - do { - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - if (binding.kind === kind) ids[name] = binding; - } - scope = scope.parent; - } while (scope); - } + _createClass(_class6, [{ + key: "parseV8Intrinsic", + value: function parseV8Intrinsic() { + if (this.match(types.modulo)) { + var v8IntrinsicStart = this.state.start; + var node = this.startNode(); + this.eat(types.modulo); - return ids; - }; + if (this.match(types.name)) { + var name = this.parseIdentifierName(this.state.start); + var identifier = this.createIdentifier(node, name); + identifier.type = "V8IntrinsicIdentifier"; - Scope.prototype.bindingIdentifierEquals = function bindingIdentifierEquals(name, node) { - return this.getBindingIdentifier(name) === node; - }; + if (this.match(types.parenL)) { + return identifier; + } + } - Scope.prototype.warnOnFlowBinding = function warnOnFlowBinding(binding) { - if (_crawlCallsCount === 0 && binding && binding.path.isFlow()) { - console.warn("\n You or one of the Babel plugins you are using are using Flow declarations as bindings.\n Support for this will be removed in version 7. To find out the caller, grep for this\n message and change it to a `console.trace()`.\n "); - } - return binding; - }; + this.unexpected(v8IntrinsicStart); + } + } + }, { + key: "parseExprAtom", + value: function parseExprAtom() { + return this.parseV8Intrinsic() || _get(_getPrototypeOf(_class6.prototype), "parseExprAtom", this).apply(this, arguments); + } + }]); - Scope.prototype.getBinding = function getBinding(name) { - var scope = this; + return _class6; + }(superClass) + ); +}; - do { - var binding = scope.getOwnBinding(name); - if (binding) return this.warnOnFlowBinding(binding); - } while (scope = scope.parent); - }; +function hasPlugin(plugins, name) { + return plugins.some(function (plugin) { + if (Array.isArray(plugin)) { + return plugin[0] === name; + } else { + return plugin === name; + } + }); +} - Scope.prototype.getOwnBinding = function getOwnBinding(name) { - return this.warnOnFlowBinding(this.bindings[name]); - }; +function getPluginOption(plugins, name, option) { + var plugin = plugins.find(function (plugin) { + if (Array.isArray(plugin)) { + return plugin[0] === name; + } else { + return plugin === name; + } + }); - Scope.prototype.getBindingIdentifier = function getBindingIdentifier(name) { - var info = this.getBinding(name); - return info && info.identifier; - }; + if (plugin && Array.isArray(plugin)) { + return plugin[1][option]; + } - Scope.prototype.getOwnBindingIdentifier = function getOwnBindingIdentifier(name) { - var binding = this.bindings[name]; - return binding && binding.identifier; - }; + return null; +} - Scope.prototype.hasOwnBinding = function hasOwnBinding(name) { - return !!this.getOwnBinding(name); - }; +var PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"]; - Scope.prototype.hasBinding = function hasBinding(name, noGlobals) { - if (!name) return false; - if (this.hasOwnBinding(name)) return true; - if (this.parentHasBinding(name, noGlobals)) return true; - if (this.hasUid(name)) return true; - if (!noGlobals && (0, _includes2.default)(Scope.globals, name)) return true; - if (!noGlobals && (0, _includes2.default)(Scope.contextVariables, name)) return true; - return false; - }; +function validatePlugins(plugins) { + if (hasPlugin(plugins, "decorators")) { + if (hasPlugin(plugins, "decorators-legacy")) { + throw new Error("Cannot use the decorators and decorators-legacy plugin together"); + } - Scope.prototype.parentHasBinding = function parentHasBinding(name, noGlobals) { - return this.parent && this.parent.hasBinding(name, noGlobals); - }; + var decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport"); - Scope.prototype.moveBindingTo = function moveBindingTo(name, scope) { - var info = this.getBinding(name); - if (info) { - info.scope.removeOwnBinding(name); - info.scope = scope; - scope.bindings[name] = info; + if (decoratorsBeforeExport == null) { + throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'."); + } else if (typeof decoratorsBeforeExport !== "boolean") { + throw new Error("'decoratorsBeforeExport' must be a boolean."); } - }; + } - Scope.prototype.removeOwnBinding = function removeOwnBinding(name) { - delete this.bindings[name]; - }; + if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) { + throw new Error("Cannot combine flow and typescript plugins."); + } - Scope.prototype.removeBinding = function removeBinding(name) { - var info = this.getBinding(name); - if (info) { - info.scope.removeOwnBinding(name); - } + if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) { + throw new Error("Cannot combine placeholders and v8intrinsic plugins."); + } - var scope = this; - do { - if (scope.uids[name]) { - scope.uids[name] = false; - } - } while (scope = scope.parent); - }; + if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) { + throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(function (p) { + return "'".concat(p, "'"); + }).join(", ")); + } +} - return Scope; -}(); +var mixinPlugins = { + estree: estree, + jsx: jsx, + flow: flow, + typescript: typescript, + v8intrinsic: v8intrinsic, + placeholders: placeholders +}; +var mixinPluginNames = Object.keys(mixinPlugins); +var defaultOptions = { + sourceType: "script", + sourceFilename: undefined, + startLine: 1, + allowAwaitOutsideFunction: false, + allowReturnOutsideFunction: false, + allowImportExportEverywhere: false, + allowSuperOutsideMethod: false, + allowUndeclaredExports: false, + plugins: [], + strictMode: null, + ranges: false, + tokens: false, + createParenthesizedExpressions: false, + errorRecovery: false +}; -Scope.globals = (0, _keys2.default)(_globals2.default.builtin); -Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"]; -exports.default = Scope; -module.exports = exports["default"]; -},{"../cache":115,"../index":118,"./binding":136,"./lib/renamer":138,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/map":97,"babel-runtime/core-js/object/create":100,"babel-runtime/core-js/object/keys":102,"babel-runtime/helpers/classCallCheck":109,"babel-types":151,"globals":289,"lodash/defaults":470,"lodash/includes":482,"lodash/repeat":507}],138:[function(require,module,exports){ -"use strict"; +function getOptions(opts) { + var options = {}; -exports.__esModule = true; + for (var _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) { + var key = _Object$keys[_i]; + options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key]; + } + + return options; +} -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +var Position = function Position(line, col) { + _classCallCheck(this, Position); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + this.line = line; + this.column = col; +}; -var _binding = require("../binding"); +var SourceLocation = function SourceLocation(start, end) { + _classCallCheck(this, SourceLocation); -var _binding2 = _interopRequireDefault(_binding); + this.start = start; + this.end = end; +}; -var _babelTypes = require("babel-types"); +function getLineInfo(input, offset) { + var line = 1; + var lineStart = 0; + var match; + lineBreakG.lastIndex = 0; -var t = _interopRequireWildcard(_babelTypes); + while ((match = lineBreakG.exec(input)) && match.index < offset) { + line++; + lineStart = lineBreakG.lastIndex; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return new Position(line, offset - lineStart); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var BaseParser = +/*#__PURE__*/ +function () { + function BaseParser() { + _classCallCheck(this, BaseParser); -var renameVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(_ref, state) { - var node = _ref.node; + this.sawUnambiguousESM = false; + this.ambiguousScriptDifferentAst = false; + } - if (node.name === state.oldName) { - node.name = state.newName; + _createClass(BaseParser, [{ + key: "hasPlugin", + value: function hasPlugin(name) { + return this.plugins.has(name); } - }, - Scope: function Scope(path, state) { - if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { - path.skip(); + }, { + key: "getPluginOption", + value: function getPluginOption(plugin, name) { + if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name]; } - }, - "AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) { - var ids = path.getOuterBindingIdentifiers(); + }]); - for (var name in ids) { - if (name === state.oldName) ids[name].name = state.newName; - } - } -}; + return BaseParser; +}(); -var Renamer = function () { - function Renamer(binding, oldName, newName) { - (0, _classCallCheck3.default)(this, Renamer); +function last(stack) { + return stack[stack.length - 1]; +} - this.newName = newName; - this.oldName = oldName; - this.binding = binding; - } +var CommentsParser = +/*#__PURE__*/ +function (_BaseParser) { + _inherits(CommentsParser, _BaseParser); - Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) { - var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; - if (!exportDeclar) return; + function CommentsParser() { + _classCallCheck(this, CommentsParser); - var isDefault = exportDeclar.isExportDefaultDeclaration(); + return _possibleConstructorReturn(this, _getPrototypeOf(CommentsParser).apply(this, arguments)); + } - if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) { - parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default"); + _createClass(CommentsParser, [{ + key: "addComment", + value: function addComment(comment) { + if (this.filename) comment.loc.filename = this.filename; + this.state.trailingComments.push(comment); + this.state.leadingComments.push(comment); } + }, { + key: "adjustCommentsAfterTrailingComma", + value: function adjustCommentsAfterTrailingComma(node, elements, takeAllComments) { + if (this.state.leadingComments.length === 0) { + return; + } - var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); - var specifiers = []; + var lastElement = null; + var i = elements.length; - for (var name in bindingIdentifiers) { - var localName = name === this.oldName ? this.newName : name; - var exportedName = isDefault ? "default" : name; - specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName))); - } + while (lastElement === null && i > 0) { + lastElement = elements[--i]; + } - if (specifiers.length) { - var aliasDeclar = t.exportNamedDeclaration(null, specifiers); + if (lastElement === null) { + return; + } - if (parentDeclar.isFunctionDeclaration()) { - aliasDeclar._blockHoist = 3; + for (var j = 0; j < this.state.leadingComments.length; j++) { + if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { + this.state.leadingComments.splice(j, 1); + j--; + } } - exportDeclar.insertAfter(aliasDeclar); - exportDeclar.replaceWith(parentDeclar.node); - } - }; + var newTrailingComments = []; - Renamer.prototype.rename = function rename(block) { - var binding = this.binding, - oldName = this.oldName, - newName = this.newName; - var scope = binding.scope, - path = binding.path; + for (var _i7 = 0; _i7 < this.state.leadingComments.length; _i7++) { + var leadingComment = this.state.leadingComments[_i7]; + if (leadingComment.end < node.end) { + newTrailingComments.push(leadingComment); - var parentDeclar = path.find(function (path) { - return path.isDeclaration() || path.isFunctionExpression(); - }); - if (parentDeclar) { - this.maybeConvertFromExportDeclaration(parentDeclar); - } + if (!takeAllComments) { + this.state.leadingComments.splice(_i7, 1); + _i7--; + } + } else { + if (node.trailingComments === undefined) { + node.trailingComments = []; + } + + node.trailingComments.push(leadingComment); + } + } - scope.traverse(block || scope.block, renameVisitor, this); + if (takeAllComments) this.state.leadingComments = []; - if (!block) { - scope.removeOwnBinding(oldName); - scope.bindings[newName] = binding; - this.binding.identifier.name = newName; + if (newTrailingComments.length > 0) { + lastElement.trailingComments = newTrailingComments; + } else if (lastElement.trailingComments !== undefined) { + lastElement.trailingComments = []; + } } + }, { + key: "processComment", + value: function processComment(node) { + if (node.type === "Program" && node.body.length > 0) return; + var stack = this.state.commentStack; + var firstChild, lastChild, trailingComments, i, j; - if (binding.type === "hoisted") {} - }; + if (this.state.trailingComments.length > 0) { + if (this.state.trailingComments[0].start >= node.end) { + trailingComments = this.state.trailingComments; + this.state.trailingComments = []; + } else { + this.state.trailingComments.length = 0; + } + } else if (stack.length > 0) { + var lastInStack = last(stack); - return Renamer; -}(); + if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) { + trailingComments = lastInStack.trailingComments; + delete lastInStack.trailingComments; + } + } -exports.default = Renamer; -module.exports = exports["default"]; -},{"../binding":136,"babel-runtime/helpers/classCallCheck":109,"babel-types":151}],139:[function(require,module,exports){ -"use strict"; + if (stack.length > 0 && last(stack).start >= node.start) { + firstChild = stack.pop(); + } -exports.__esModule = true; + while (stack.length > 0 && last(stack).start >= node.start) { + lastChild = stack.pop(); + } -var _typeof2 = require("babel-runtime/helpers/typeof"); + if (!lastChild && firstChild) lastChild = firstChild; -var _typeof3 = _interopRequireDefault(_typeof2); + if (firstChild) { + switch (node.type) { + case "ObjectExpression": + this.adjustCommentsAfterTrailingComma(node, node.properties); + break; -var _keys = require("babel-runtime/core-js/object/keys"); + case "ObjectPattern": + this.adjustCommentsAfterTrailingComma(node, node.properties, true); + break; -var _keys2 = _interopRequireDefault(_keys); + case "CallExpression": + this.adjustCommentsAfterTrailingComma(node, node.arguments); + break; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + case "ArrayExpression": + this.adjustCommentsAfterTrailingComma(node, node.elements); + break; -var _getIterator3 = _interopRequireDefault(_getIterator2); + case "ArrayPattern": + this.adjustCommentsAfterTrailingComma(node, node.elements, true); + break; + } + } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) { + this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode], true); + } -exports.explode = explode; -exports.verify = verify; -exports.merge = merge; + if (lastChild) { + if (lastChild.leadingComments) { + if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) { + node.leadingComments = lastChild.leadingComments; + delete lastChild.leadingComments; + } else { + for (i = lastChild.leadingComments.length - 2; i >= 0; --i) { + if (lastChild.leadingComments[i].end <= node.start) { + node.leadingComments = lastChild.leadingComments.splice(0, i + 1); + break; + } + } + } + } + } else if (this.state.leadingComments.length > 0) { + if (last(this.state.leadingComments).end <= node.start) { + if (this.state.commentPreviousNode) { + for (j = 0; j < this.state.leadingComments.length; j++) { + if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { + this.state.leadingComments.splice(j, 1); + j--; + } + } + } -var _virtualTypes = require("./path/lib/virtual-types"); + if (this.state.leadingComments.length > 0) { + node.leadingComments = this.state.leadingComments; + this.state.leadingComments = []; + } + } else { + for (i = 0; i < this.state.leadingComments.length; i++) { + if (this.state.leadingComments[i].end > node.start) { + break; + } + } -var virtualTypes = _interopRequireWildcard(_virtualTypes); + var leadingComments = this.state.leadingComments.slice(0, i); -var _babelMessages = require("babel-messages"); + if (leadingComments.length) { + node.leadingComments = leadingComments; + } -var messages = _interopRequireWildcard(_babelMessages); + trailingComments = this.state.leadingComments.slice(i); -var _babelTypes = require("babel-types"); + if (trailingComments.length === 0) { + trailingComments = null; + } + } + } -var t = _interopRequireWildcard(_babelTypes); + this.state.commentPreviousNode = node; -var _clone = require("lodash/clone"); + if (trailingComments) { + if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) { + node.innerComments = trailingComments; + } else { + node.trailingComments = trailingComments; + } + } -var _clone2 = _interopRequireDefault(_clone); + stack.push(node); + } + }]); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return CommentsParser; +}(BaseParser); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var LocationParser = +/*#__PURE__*/ +function (_CommentsParser) { + _inherits(LocationParser, _CommentsParser); -function explode(visitor) { - if (visitor._exploded) return visitor; - visitor._exploded = true; + function LocationParser() { + _classCallCheck(this, LocationParser); - for (var nodeType in visitor) { - if (shouldIgnoreKey(nodeType)) continue; + return _possibleConstructorReturn(this, _getPrototypeOf(LocationParser).apply(this, arguments)); + } - var parts = nodeType.split("|"); - if (parts.length === 1) continue; - - var fns = visitor[nodeType]; - delete visitor[nodeType]; + _createClass(LocationParser, [{ + key: "getLocationForPosition", + value: function getLocationForPosition(pos) { + var loc; + if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos); + return loc; + } + }, { + key: "raise", + value: function raise(pos, message) { + var _ref14 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + missingPluginNames = _ref14.missingPluginNames, + code = _ref14.code; - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + var loc = this.getLocationForPosition(pos); + message += " (".concat(loc.line, ":").concat(loc.column, ")"); + var err = new SyntaxError(message); + err.pos = pos; + err.loc = loc; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + if (missingPluginNames) { + err.missingPlugin = missingPluginNames; } - var part = _ref; + if (code !== undefined) { + err.code = code; + } - visitor[part] = fns; + if (this.options.errorRecovery) { + if (!this.isLookahead) this.state.errors.push(err); + return err; + } else { + throw err; + } } - } - - verify(visitor); - - delete visitor.__esModule; + }]); - ensureEntranceObjects(visitor); + return LocationParser; +}(CommentsParser); - ensureCallbackArrays(visitor); +var State = +/*#__PURE__*/ +function () { + function State() { + _classCallCheck(this, State); - for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + this.errors = []; + this.potentialArrowAt = -1; + this.noArrowAt = []; + this.noArrowParamsConversionAt = []; + this.inParameters = false; + this.maybeInArrowParameters = false; + this.inPipeline = false; + this.inType = false; + this.noAnonFunctionType = false; + this.inPropertyName = false; + this.inClassProperty = false; + this.hasFlowComment = false; + this.isIterator = false; + this.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + this.soloAwait = false; + this.inFSharpPipelineDirectBody = false; + this.classLevel = 0; + this.labels = []; + this.decoratorStack = [[]]; + this.yieldPos = -1; + this.awaitPos = -1; + this.tokens = []; + this.comments = []; + this.trailingComments = []; + this.leadingComments = []; + this.commentStack = []; + this.commentPreviousNode = null; + this.pos = 0; + this.lineStart = 0; + this.type = types.eof; + this.value = null; + this.start = 0; + this.end = 0; + this.lastTokEndLoc = null; + this.lastTokStartLoc = null; + this.lastTokStart = 0; + this.lastTokEnd = 0; + this.context = [types$1.braceStatement]; + this.exprAllowed = true; + this.containsEsc = false; + this.containsOctal = false; + this.octalPosition = null; + this.exportedIdentifiers = []; + this.invalidTemplateEscapePosition = null; + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + _createClass(State, [{ + key: "init", + value: function init(options) { + this.strict = options.strictMode === false ? false : options.sourceType === "module"; + this.curLine = options.startLine; + this.startLoc = this.endLoc = this.curPosition(); } + }, { + key: "curPosition", + value: function curPosition() { + return new Position(this.curLine, this.pos - this.lineStart); + } + }, { + key: "clone", + value: function clone(skipArrays) { + var state = new State(); + var keys = Object.keys(this); - var _nodeType3 = _ref2; + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; + var val = this[key]; - if (shouldIgnoreKey(_nodeType3)) continue; + if (!skipArrays && Array.isArray(val)) { + val = val.slice(); + } - var wrapper = virtualTypes[_nodeType3]; - if (!wrapper) continue; + state[key] = val; + } - var _fns2 = visitor[_nodeType3]; - for (var type in _fns2) { - _fns2[type] = wrapCheck(wrapper, _fns2[type]); + return state; } + }]); - delete visitor[_nodeType3]; + return State; +}(); - if (wrapper.types) { - for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } +var VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]); +var forbiddenNumericSeparatorSiblings = { + decBinOct: [46, 66, 69, 79, 95, 98, 101, 111], + hex: [46, 88, 95, 120] +}; +var allowedNumericSeparatorSiblings = {}; +allowedNumericSeparatorSiblings.bin = [48, 49]; +allowedNumericSeparatorSiblings.oct = [].concat(_toConsumableArray(allowedNumericSeparatorSiblings.bin), [50, 51, 52, 53, 54, 55]); +allowedNumericSeparatorSiblings.dec = [].concat(_toConsumableArray(allowedNumericSeparatorSiblings.oct), [56, 57]); +allowedNumericSeparatorSiblings.hex = [].concat(_toConsumableArray(allowedNumericSeparatorSiblings.dec), [65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102]); - var _type = _ref4; +var Token = function Token(state) { + _classCallCheck(this, Token); - if (visitor[_type]) { - mergePair(visitor[_type], _fns2); - } else { - visitor[_type] = _fns2; - } - } - } else { - mergePair(visitor, _fns2); - } - } + this.type = state.type; + this.value = state.value; + this.start = state.start; + this.end = state.end; + this.loc = new SourceLocation(state.startLoc, state.endLoc); +}; - for (var _nodeType in visitor) { - if (shouldIgnoreKey(_nodeType)) continue; +var Tokenizer = +/*#__PURE__*/ +function (_LocationParser) { + _inherits(Tokenizer, _LocationParser); - var _fns = visitor[_nodeType]; + function Tokenizer(options, input) { + var _this34; - var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType]; + _classCallCheck(this, Tokenizer); - var deprecratedKey = t.DEPRECATED_KEYS[_nodeType]; - if (deprecratedKey) { - console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey); - aliases = [deprecratedKey]; - } + _this34 = _possibleConstructorReturn(this, _getPrototypeOf(Tokenizer).call(this)); + _this34.state = new State(); - if (!aliases) continue; + _this34.state.init(options); - delete visitor[_nodeType]; + _this34.input = input; + _this34.length = input.length; + _this34.isLookahead = false; + return _this34; + } - for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + _createClass(Tokenizer, [{ + key: "next", + value: function next() { + if (!this.isLookahead) { + this.checkKeywordEscapes(); - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; + if (this.options.tokens) { + this.state.tokens.push(new Token(this.state)); + } } - var alias = _ref3; + this.state.lastTokEnd = this.state.end; + this.state.lastTokStart = this.state.start; + this.state.lastTokEndLoc = this.state.endLoc; + this.state.lastTokStartLoc = this.state.startLoc; + this.nextToken(); + } + }, { + key: "eat", + value: function eat(type) { + if (this.match(type)) { + this.next(); + return true; + } else { + return false; + } + } + }, { + key: "match", + value: function match(type) { + return this.state.type === type; + } + }, { + key: "lookahead", + value: function lookahead() { + var old = this.state; + this.state = old.clone(true); + this.isLookahead = true; + this.next(); + this.isLookahead = false; + var curr = this.state; + this.state = old; + return curr; + } + }, { + key: "nextTokenStart", + value: function nextTokenStart() { + var thisTokEnd = this.state.pos; + skipWhiteSpace.lastIndex = thisTokEnd; + var skip = skipWhiteSpace.exec(this.input); + return thisTokEnd + skip[0].length; + } + }, { + key: "lookaheadCharCode", + value: function lookaheadCharCode() { + return this.input.charCodeAt(this.nextTokenStart()); + } + }, { + key: "setStrict", + value: function setStrict(strict) { + this.state.strict = strict; + if (!this.match(types.num) && !this.match(types.string)) return; + this.state.pos = this.state.start; + + while (this.state.pos < this.state.lineStart) { + this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1; + --this.state.curLine; + } + + this.nextToken(); + } + }, { + key: "curContext", + value: function curContext() { + return this.state.context[this.state.context.length - 1]; + } + }, { + key: "nextToken", + value: function nextToken() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) this.skipSpace(); + this.state.containsOctal = false; + this.state.octalPosition = null; + this.state.start = this.state.pos; + this.state.startLoc = this.state.curPosition(); + + if (this.state.pos >= this.length) { + this.finishToken(types.eof); + return; + } - var existing = visitor[alias]; - if (existing) { - mergePair(existing, _fns); + if (curContext.override) { + curContext.override(this); } else { - visitor[alias] = (0, _clone2.default)(_fns); + this.getTokenFromCode(this.input.codePointAt(this.state.pos)); + } + } + }, { + key: "pushComment", + value: function pushComment(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "CommentBlock" : "CommentLine", + value: text, + start: start, + end: end, + loc: new SourceLocation(startLoc, endLoc) + }; + if (this.options.tokens) this.state.tokens.push(comment); + this.state.comments.push(comment); + this.addComment(comment); + } + }, { + key: "skipBlockComment", + value: function skipBlockComment() { + var startLoc = this.state.curPosition(); + var start = this.state.pos; + var end = this.input.indexOf("*/", this.state.pos + 2); + if (end === -1) throw this.raise(start, "Unterminated comment"); + this.state.pos = end + 2; + lineBreakG.lastIndex = start; + var match; + + while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) { + ++this.state.curLine; + this.state.lineStart = match.index + match[0].length; } + + if (this.isLookahead) return; + this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition()); } - } + }, { + key: "skipLineComment", + value: function skipLineComment(startSkip) { + var start = this.state.pos; + var startLoc = this.state.curPosition(); + var ch = this.input.charCodeAt(this.state.pos += startSkip); - for (var _nodeType2 in visitor) { - if (shouldIgnoreKey(_nodeType2)) continue; + if (this.state.pos < this.length) { + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + } - ensureCallbackArrays(visitor[_nodeType2]); - } + if (this.isLookahead) return; + this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition()); + } + }, { + key: "skipSpace", + value: function skipSpace() { + loop: while (this.state.pos < this.length) { + var ch = this.input.charCodeAt(this.state.pos); - return visitor; -} + switch (ch) { + case 32: + case 160: + case 9: + ++this.state.pos; + break; -function verify(visitor) { - if (visitor._verified) return; + case 13: + if (this.input.charCodeAt(this.state.pos + 1) === 10) { + ++this.state.pos; + } - if (typeof visitor === "function") { - throw new Error(messages.get("traverseVerifyRootFunction")); - } + case 10: + case 8232: + case 8233: + ++this.state.pos; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + break; - for (var nodeType in visitor) { - if (nodeType === "enter" || nodeType === "exit") { - validateVisitorMethods(nodeType, visitor[nodeType]); - } + case 47: + switch (this.input.charCodeAt(this.state.pos + 1)) { + case 42: + this.skipBlockComment(); + break; - if (shouldIgnoreKey(nodeType)) continue; + case 47: + this.skipLineComment(2); + break; - if (t.TYPES.indexOf(nodeType) < 0) { - throw new Error(messages.get("traverseVerifyNodeType", nodeType)); - } + default: + break loop; + } + + break; + + default: + if (isWhitespace(ch)) { + ++this.state.pos; + } else { + break loop; + } - var visitors = visitor[nodeType]; - if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") { - for (var visitorKey in visitors) { - if (visitorKey === "enter" || visitorKey === "exit") { - validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]); - } else { - throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey)); } } } - } + }, { + key: "finishToken", + value: function finishToken(type, val) { + this.state.end = this.state.pos; + this.state.endLoc = this.state.curPosition(); + var prevType = this.state.type; + this.state.type = type; + this.state.value = val; + if (!this.isLookahead) this.updateContext(prevType); + } + }, { + key: "readToken_numberSign", + value: function readToken_numberSign() { + if (this.state.pos === 0 && this.readToken_interpreter()) { + return; + } - visitor._verified = true; -} + var nextPos = this.state.pos + 1; + var next = this.input.charCodeAt(nextPos); -function validateVisitorMethods(path, val) { - var fns = [].concat(val); - for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; + if (next >= 48 && next <= 57) { + throw this.raise(this.state.pos, "Unexpected digit after hash token"); + } - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; + if ((this.hasPlugin("classPrivateProperties") || this.hasPlugin("classPrivateMethods")) && this.state.classLevel > 0) { + ++this.state.pos; + this.finishToken(types.hash); + return; + } else if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { + this.finishOp(types.hash, 1); + } else { + throw this.raise(this.state.pos, "Unexpected character '#'"); + } } + }, { + key: "readToken_dot", + value: function readToken_dot() { + var next = this.input.charCodeAt(this.state.pos + 1); - var fn = _ref5; + if (next >= 48 && next <= 57) { + this.readNumber(true); + return; + } - if (typeof fn !== "function") { - throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn))); + if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) { + this.state.pos += 3; + this.finishToken(types.ellipsis); + } else { + ++this.state.pos; + this.finishToken(types.dot); + } } - } -} + }, { + key: "readToken_slash", + value: function readToken_slash() { + if (this.state.exprAllowed && !this.state.inType) { + ++this.state.pos; + this.readRegexp(); + return; + } -function merge(visitors) { - var states = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var wrapper = arguments[2]; + var next = this.input.charCodeAt(this.state.pos + 1); - var rootVisitor = {}; + if (next === 61) { + this.finishOp(types.assign, 2); + } else { + this.finishOp(types.slash, 1); + } + } + }, { + key: "readToken_interpreter", + value: function readToken_interpreter() { + if (this.state.pos !== 0 || this.length < 2) return false; + var start = this.state.pos; + this.state.pos += 1; + var ch = this.input.charCodeAt(this.state.pos); + if (ch !== 33) return false; - for (var i = 0; i < visitors.length; i++) { - var visitor = visitors[i]; - var state = states[i]; + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } - explode(visitor); + var value = this.input.slice(start + 2, this.state.pos); + this.finishToken(types.interpreterDirective, value); + return true; + } + }, { + key: "readToken_mult_modulo", + value: function readToken_mult_modulo(code) { + var type = code === 42 ? types.star : types.modulo; + var width = 1; + var next = this.input.charCodeAt(this.state.pos + 1); + var exprAllowed = this.state.exprAllowed; - for (var type in visitor) { - var visitorType = visitor[type]; + if (code === 42 && next === 42) { + width++; + next = this.input.charCodeAt(this.state.pos + 2); + type = types.exponent; + } - if (state || wrapper) { - visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); + if (next === 61 && !exprAllowed) { + width++; + type = types.assign; } - var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; - mergePair(nodeVisitor, visitorType); + this.finishOp(type, width); } - } + }, { + key: "readToken_pipe_amp", + value: function readToken_pipe_amp(code) { + var next = this.input.charCodeAt(this.state.pos + 1); - return rootVisitor; -} + if (next === code) { + if (this.input.charCodeAt(this.state.pos + 2) === 61) { + this.finishOp(types.assign, 3); + } else { + this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2); + } -function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { - var newVisitor = {}; + return; + } - var _loop = function _loop(key) { - var fns = oldVisitor[key]; + if (code === 124) { + if (next === 62) { + this.finishOp(types.pipeline, 2); + return; + } + } - if (!Array.isArray(fns)) return "continue"; + if (next === 61) { + this.finishOp(types.assign, 2); + return; + } - fns = fns.map(function (fn) { - var newFn = fn; + this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1); + } + }, { + key: "readToken_caret", + value: function readToken_caret() { + var next = this.input.charCodeAt(this.state.pos + 1); - if (state) { - newFn = function newFn(path) { - return fn.call(state, path, state); - }; + if (next === 61) { + this.finishOp(types.assign, 2); + } else { + this.finishOp(types.bitwiseXOR, 1); } + } + }, { + key: "readToken_plus_min", + value: function readToken_plus_min(code) { + var next = this.input.charCodeAt(this.state.pos + 1); - if (wrapper) { - newFn = wrapper(state.key, key, newFn); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos)))) { + this.skipLineComment(3); + this.skipSpace(); + this.nextToken(); + return; + } + + this.finishOp(types.incDec, 2); + return; } - return newFn; - }); + if (next === 61) { + this.finishOp(types.assign, 2); + } else { + this.finishOp(types.plusMin, 1); + } + } + }, { + key: "readToken_lt_gt", + value: function readToken_lt_gt(code) { + var next = this.input.charCodeAt(this.state.pos + 1); + var size = 1; - newVisitor[key] = fns; - }; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; - for (var key in oldVisitor) { - var _ret = _loop(key); + if (this.input.charCodeAt(this.state.pos + size) === 61) { + this.finishOp(types.assign, size + 1); + return; + } - if (_ret === "continue") continue; - } + this.finishOp(types.bitShift, size); + return; + } - return newVisitor; -} + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { + this.skipLineComment(4); + this.skipSpace(); + this.nextToken(); + return; + } -function ensureEntranceObjects(obj) { - for (var key in obj) { - if (shouldIgnoreKey(key)) continue; + if (next === 61) { + size = 2; + } - var fns = obj[key]; - if (typeof fns === "function") { - obj[key] = { enter: fns }; + this.finishOp(types.relational, size); } - } -} + }, { + key: "readToken_eq_excl", + value: function readToken_eq_excl(code) { + var next = this.input.charCodeAt(this.state.pos + 1); -function ensureCallbackArrays(obj) { - if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; - if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; -} + if (next === 61) { + this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); + return; + } -function wrapCheck(wrapper, fn) { - var newFn = function newFn(path) { - if (wrapper.checkPath(path)) { - return fn.apply(this, arguments); + if (code === 61 && next === 62) { + this.state.pos += 2; + this.finishToken(types.arrow); + return; + } + + this.finishOp(code === 61 ? types.eq : types.bang, 1); } - }; - newFn.toString = function () { - return fn.toString(); - }; - return newFn; -} + }, { + key: "readToken_question", + value: function readToken_question() { + var next = this.input.charCodeAt(this.state.pos + 1); + var next2 = this.input.charCodeAt(this.state.pos + 2); -function shouldIgnoreKey(key) { - if (key[0] === "_") return true; + if (next === 63 && !this.state.inType) { + if (next2 === 61) { + this.finishOp(types.assign, 3); + } else { + this.finishOp(types.nullishCoalescing, 2); + } + } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { + this.state.pos += 2; + this.finishToken(types.questionDot); + } else { + ++this.state.pos; + this.finishToken(types.question); + } + } + }, { + key: "getTokenFromCode", + value: function getTokenFromCode(code) { + switch (code) { + case 46: + this.readToken_dot(); + return; - if (key === "enter" || key === "exit" || key === "shouldSkip") return true; + case 40: + ++this.state.pos; + this.finishToken(types.parenL); + return; - if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true; + case 41: + ++this.state.pos; + this.finishToken(types.parenR); + return; - return false; -} + case 59: + ++this.state.pos; + this.finishToken(types.semi); + return; -function mergePair(dest, src) { - for (var key in src) { - dest[key] = [].concat(dest[key] || [], src[key]); - } -} -},{"./path/lib/virtual-types":132,"babel-messages":61,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/keys":102,"babel-runtime/helpers/typeof":113,"babel-types":151,"lodash/clone":466}],140:[function(require,module,exports){ -"use strict"; + case 44: + ++this.state.pos; + this.finishToken(types.comma); + return; -exports.__esModule = true; -exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; + case 91: + ++this.state.pos; + this.finishToken(types.bracketL); + return; + + case 93: + ++this.state.pos; + this.finishToken(types.bracketR); + return; -var _for = require("babel-runtime/core-js/symbol/for"); + case 123: + ++this.state.pos; + this.finishToken(types.braceL); + return; -var _for2 = _interopRequireDefault(_for); + case 125: + ++this.state.pos; + this.finishToken(types.braceR); + return; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case 58: + if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { + this.finishOp(types.doubleColon, 2); + } else { + ++this.state.pos; + this.finishToken(types.colon); + } -var STATEMENT_OR_BLOCK_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; -var FLATTENABLE_KEYS = exports.FLATTENABLE_KEYS = ["body", "expressions"]; -var FOR_INIT_KEYS = exports.FOR_INIT_KEYS = ["left", "init"]; -var COMMENT_KEYS = exports.COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; + return; -var LOGICAL_OPERATORS = exports.LOGICAL_OPERATORS = ["||", "&&"]; -var UPDATE_OPERATORS = exports.UPDATE_OPERATORS = ["++", "--"]; + case 63: + this.readToken_question(); + return; -var BOOLEAN_NUMBER_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; -var EQUALITY_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; -var COMPARISON_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = [].concat(EQUALITY_BINARY_OPERATORS, ["in", "instanceof"]); -var BOOLEAN_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = [].concat(COMPARISON_BINARY_OPERATORS, BOOLEAN_NUMBER_BINARY_OPERATORS); -var NUMBER_BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; -var BINARY_OPERATORS = exports.BINARY_OPERATORS = ["+"].concat(NUMBER_BINARY_OPERATORS, BOOLEAN_BINARY_OPERATORS); + case 96: + ++this.state.pos; + this.finishToken(types.backQuote); + return; -var BOOLEAN_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; -var NUMBER_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = ["+", "-", "++", "--", "~"]; -var STRING_UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = ["typeof"]; -var UNARY_OPERATORS = exports.UNARY_OPERATORS = ["void"].concat(BOOLEAN_UNARY_OPERATORS, NUMBER_UNARY_OPERATORS, STRING_UNARY_OPERATORS); + case 48: + { + var next = this.input.charCodeAt(this.state.pos + 1); -var INHERIT_KEYS = exports.INHERIT_KEYS = { - optional: ["typeAnnotation", "typeParameters", "returnType"], - force: ["start", "loc", "end"] -}; + if (next === 120 || next === 88) { + this.readRadixNumber(16); + return; + } -var BLOCK_SCOPED_SYMBOL = exports.BLOCK_SCOPED_SYMBOL = (0, _for2.default)("var used to be block scoped"); -var NOT_LOCAL_BINDING = exports.NOT_LOCAL_BINDING = (0, _for2.default)("should not be considered a local binding"); -},{"babel-runtime/core-js/symbol/for":105}],141:[function(require,module,exports){ -"use strict"; + if (next === 111 || next === 79) { + this.readRadixNumber(8); + return; + } -exports.__esModule = true; + if (next === 98 || next === 66) { + this.readRadixNumber(2); + return; + } + } -var _maxSafeInteger = require("babel-runtime/core-js/number/max-safe-integer"); + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + this.readNumber(false); + return; -var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger); + case 34: + case 39: + this.readString(code); + return; -var _stringify = require("babel-runtime/core-js/json/stringify"); + case 47: + this.readToken_slash(); + return; -var _stringify2 = _interopRequireDefault(_stringify); + case 37: + case 42: + this.readToken_mult_modulo(code); + return; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + case 124: + case 38: + this.readToken_pipe_amp(code); + return; -var _getIterator3 = _interopRequireDefault(_getIterator2); + case 94: + this.readToken_caret(); + return; -exports.toComputedKey = toComputedKey; -exports.toSequenceExpression = toSequenceExpression; -exports.toKeyAlias = toKeyAlias; -exports.toIdentifier = toIdentifier; -exports.toBindingIdentifierName = toBindingIdentifierName; -exports.toStatement = toStatement; -exports.toExpression = toExpression; -exports.toBlock = toBlock; -exports.valueToNode = valueToNode; + case 43: + case 45: + this.readToken_plus_min(code); + return; -var _isPlainObject = require("lodash/isPlainObject"); + case 60: + case 62: + this.readToken_lt_gt(code); + return; -var _isPlainObject2 = _interopRequireDefault(_isPlainObject); + case 61: + case 33: + this.readToken_eq_excl(code); + return; -var _isRegExp = require("lodash/isRegExp"); + case 126: + this.finishOp(types.tilde, 1); + return; -var _isRegExp2 = _interopRequireDefault(_isRegExp); + case 64: + ++this.state.pos; + this.finishToken(types.at); + return; -var _index = require("./index"); + case 35: + this.readToken_numberSign(); + return; -var t = _interopRequireWildcard(_index); + case 92: + this.readWord(); + return; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + default: + if (isIdentifierStart(code)) { + this.readWord(); + return; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + } -function toComputedKey(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.key || node.property; + throw this.raise(this.state.pos, "Unexpected character '".concat(String.fromCodePoint(code), "'")); + } + }, { + key: "finishOp", + value: function finishOp(type, size) { + var str = this.input.slice(this.state.pos, this.state.pos + size); + this.state.pos += size; + this.finishToken(type, str); + } + }, { + key: "readRegexp", + value: function readRegexp() { + var start = this.state.pos; + var escaped, inClass; - if (!node.computed) { - if (t.isIdentifier(key)) key = t.stringLiteral(key.name); - } - return key; -} + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(start, "Unterminated regular expression"); + } -function gatherSequenceExpressions(nodes, scope, declars) { - var exprs = []; - var ensureLastUndefined = true; + var ch = this.input.charAt(this.state.pos); - for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (lineBreak.test(ch)) { + throw this.raise(start, "Unterminated regular expression"); + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (escaped) { + escaped = false; + } else { + if (ch === "[") { + inClass = true; + } else if (ch === "]" && inClass) { + inClass = false; + } else if (ch === "/" && !inClass) { + break; + } - var node = _ref; + escaped = ch === "\\"; + } - ensureLastUndefined = false; + ++this.state.pos; + } - if (t.isExpression(node)) { - exprs.push(node); - } else if (t.isExpressionStatement(node)) { - exprs.push(node.expression); - } else if (t.isVariableDeclaration(node)) { - if (node.kind !== "var") return; + var content = this.input.slice(start, this.state.pos); + ++this.state.pos; + var mods = ""; - for (var _iterator2 = node.declarations, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + while (this.state.pos < this.length) { + var char = this.input[this.state.pos]; + var charCode = this.input.codePointAt(this.state.pos); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; + if (VALID_REGEX_FLAGS.has(char)) { + if (mods.indexOf(char) > -1) { + this.raise(this.state.pos + 1, "Duplicate regular expression flag"); + } + } else if (isIdentifierChar(charCode) || charCode === 92) { + this.raise(this.state.pos + 1, "Invalid regular expression flag"); } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + break; } - var declar = _ref2; + ++this.state.pos; + mods += char; + } + + this.finishToken(types.regexp, { + pattern: content, + flags: mods + }); + } + }, { + key: "readInt", + value: function readInt(radix, len, forceLen) { + var allowNumSeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + var start = this.state.pos; + var forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + var allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin; + var invalid = false; + var total = 0; + + for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) { + var code = this.input.charCodeAt(this.state.pos); + var val = void 0; + + if (this.hasPlugin("numericSeparator")) { + if (code === 95) { + var prev = this.input.charCodeAt(this.state.pos - 1); + var next = this.input.charCodeAt(this.state.pos + 1); + + if (allowedSiblings.indexOf(next) === -1) { + this.raise(this.state.pos, "A numeric separator is only allowed between two digits"); + } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) { + this.raise(this.state.pos, "A numeric separator is only allowed between two digits"); + } + + if (!allowNumSeparator) { + this.raise(this.state.pos, "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences"); + } - var bindings = t.getBindingIdentifiers(declar); - for (var key in bindings) { - declars.push({ - kind: node.kind, - id: bindings[key] - }); + ++this.state.pos; + continue; + } } - if (declar.init) { - exprs.push(t.assignmentExpression("=", declar.id, declar.init)); + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + + if (val >= radix) { + if (this.options.errorRecovery && val <= 9) { + val = 0; + this.raise(this.state.start + i + 2, "Expected number in radix " + radix); + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } } - } - ensureLastUndefined = true; - } else if (t.isIfStatement(node)) { - var consequent = node.consequent ? gatherSequenceExpressions([node.consequent], scope, declars) : scope.buildUndefinedNode(); - var alternate = node.alternate ? gatherSequenceExpressions([node.alternate], scope, declars) : scope.buildUndefinedNode(); - if (!consequent || !alternate) return; + ++this.state.pos; + total = total * radix + val; + } - exprs.push(t.conditionalExpression(node.test, consequent, alternate)); - } else if (t.isBlockStatement(node)) { - var body = gatherSequenceExpressions(node.body, scope, declars); - if (!body) return; + if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) { + return null; + } - exprs.push(body); - } else if (t.isEmptyStatement(node)) { - ensureLastUndefined = true; - } else { - return; + return total; } - } - - if (ensureLastUndefined) { - exprs.push(scope.buildUndefinedNode()); - } + }, { + key: "readRadixNumber", + value: function readRadixNumber(radix) { + var start = this.state.pos; + var isBigInt = false; + this.state.pos += 2; + var val = this.readInt(radix); - if (exprs.length === 1) { - return exprs[0]; - } else { - return t.sequenceExpression(exprs); - } -} + if (val == null) { + this.raise(this.state.start + 2, "Expected number in radix " + radix); + } -function toSequenceExpression(nodes, scope) { - if (!nodes || !nodes.length) return; + if (this.hasPlugin("bigInt")) { + if (this.input.charCodeAt(this.state.pos) === 110) { + ++this.state.pos; + isBigInt = true; + } + } - var declars = []; - var result = gatherSequenceExpressions(nodes, scope, declars); - if (!result) return; + if (isIdentifierStart(this.input.codePointAt(this.state.pos))) { + throw this.raise(this.state.pos, "Identifier directly after number"); + } - for (var _iterator3 = declars, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + if (isBigInt) { + var str = this.input.slice(start, this.state.pos).replace(/[_n]/g, ""); + this.finishToken(types.bigint, str); + return; + } - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; + this.finishToken(types.num, val); } + }, { + key: "readNumber", + value: function readNumber(startsWithDot) { + var start = this.state.pos; + var isFloat = false; + var isBigInt = false; + var isNonOctalDecimalInt = false; - var declar = _ref3; - - scope.push(declar); - } - - return result; -} - -function toKeyAlias(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.key; + if (!startsWithDot && this.readInt(10) === null) { + this.raise(start, "Invalid number"); + } - var alias = void 0; + var octal = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; - if (node.kind === "method") { - return toKeyAlias.increment() + ""; - } else if (t.isIdentifier(key)) { - alias = key.name; - } else if (t.isStringLiteral(key)) { - alias = (0, _stringify2.default)(key.value); - } else { - alias = (0, _stringify2.default)(t.removePropertiesDeep(t.cloneDeep(key))); - } + if (octal) { + if (this.state.strict) { + this.raise(start, "Legacy octal literals are not allowed in strict mode"); + } - if (node.computed) { - alias = "[" + alias + "]"; - } + if (/[89]/.test(this.input.slice(start, this.state.pos))) { + octal = false; + isNonOctalDecimalInt = true; + } + } - if (node.static) { - alias = "static:" + alias; - } + var next = this.input.charCodeAt(this.state.pos); - return alias; -} + if (next === 46 && !octal) { + ++this.state.pos; + this.readInt(10); + isFloat = true; + next = this.input.charCodeAt(this.state.pos); + } -toKeyAlias.uid = 0; + if ((next === 69 || next === 101) && !octal) { + next = this.input.charCodeAt(++this.state.pos); -toKeyAlias.increment = function () { - if (toKeyAlias.uid >= _maxSafeInteger2.default) { - return toKeyAlias.uid = 0; - } else { - return toKeyAlias.uid++; - } -}; + if (next === 43 || next === 45) { + ++this.state.pos; + } -function toIdentifier(name) { - name = name + ""; + if (this.readInt(10) === null) this.raise(start, "Invalid number"); + isFloat = true; + next = this.input.charCodeAt(this.state.pos); + } - name = name.replace(/[^a-zA-Z0-9$_]/g, "-"); + if (this.hasPlugin("numericSeparator") && (octal || isNonOctalDecimalInt)) { + var underscorePos = this.input.slice(start, this.state.pos).indexOf("_"); - name = name.replace(/^[-0-9]+/, ""); + if (underscorePos > 0) { + this.raise(underscorePos + start, "Numeric separator can not be used after leading 0"); + } + } - name = name.replace(/[-\s]+(.)?/g, function (match, c) { - return c ? c.toUpperCase() : ""; - }); + if (this.hasPlugin("bigInt")) { + if (next === 110) { + if (isFloat || octal || isNonOctalDecimalInt) { + this.raise(start, "Invalid BigIntLiteral"); + } - if (!t.isValidIdentifier(name)) { - name = "_" + name; - } + ++this.state.pos; + isBigInt = true; + } + } - return name || "_"; -} + if (isIdentifierStart(this.input.codePointAt(this.state.pos))) { + throw this.raise(this.state.pos, "Identifier directly after number"); + } -function toBindingIdentifierName(name) { - name = toIdentifier(name); - if (name === "eval" || name === "arguments") name = "_" + name; - return name; -} + var str = this.input.slice(start, this.state.pos).replace(/[_n]/g, ""); -function toStatement(node, ignore) { - if (t.isStatement(node)) { - return node; - } + if (isBigInt) { + this.finishToken(types.bigint, str); + return; + } - var mustHaveId = false; - var newType = void 0; + var val = octal ? parseInt(str, 8) : parseFloat(str); + this.finishToken(types.num, val); + } + }, { + key: "readCodePoint", + value: function readCodePoint(throwOnInvalid) { + var ch = this.input.charCodeAt(this.state.pos); + var code; - if (t.isClass(node)) { - mustHaveId = true; - newType = "ClassDeclaration"; - } else if (t.isFunction(node)) { - mustHaveId = true; - newType = "FunctionDeclaration"; - } else if (t.isAssignmentExpression(node)) { - return t.expressionStatement(node); - } + if (ch === 123) { + var codePos = ++this.state.pos; + code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid); + ++this.state.pos; - if (mustHaveId && !node.id) { - newType = false; - } + if (code === null) { + --this.state.invalidTemplateEscapePosition; + } else if (code > 0x10ffff) { + if (throwOnInvalid) { + this.raise(codePos, "Code point out of bounds"); + } else { + this.state.invalidTemplateEscapePosition = codePos - 2; + return null; + } + } + } else { + code = this.readHexChar(4, false, throwOnInvalid); + } - if (!newType) { - if (ignore) { - return false; - } else { - throw new Error("cannot turn " + node.type + " to a statement"); + return code; } - } + }, { + key: "readString", + value: function readString(quote) { + var out = "", + chunkStart = ++this.state.pos; - node.type = newType; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(this.state.start, "Unterminated string constant"); + } - return node; -} + var ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; -function toExpression(node) { - if (t.isExpressionStatement(node)) { - node = node.expression; - } + if (ch === 92) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.readEscapedChar(false); + chunkStart = this.state.pos; + } else if (ch === 8232 || ch === 8233) { + ++this.state.pos; + ++this.state.curLine; + } else if (isNewLine(ch)) { + throw this.raise(this.state.start, "Unterminated string constant"); + } else { + ++this.state.pos; + } + } - if (t.isExpression(node)) { - return node; - } + out += this.input.slice(chunkStart, this.state.pos++); + this.finishToken(types.string, out); + } + }, { + key: "readTmplToken", + value: function readTmplToken() { + var out = "", + chunkStart = this.state.pos, + containsInvalid = false; - if (t.isClass(node)) { - node.type = "ClassExpression"; - } else if (t.isFunction(node)) { - node.type = "FunctionExpression"; - } + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(this.state.start, "Unterminated template"); + } - if (!t.isExpression(node)) { - throw new Error("cannot turn " + node.type + " to an expression"); - } + var ch = this.input.charCodeAt(this.state.pos); - return node; -} + if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) { + if (this.state.pos === this.state.start && this.match(types.template)) { + if (ch === 36) { + this.state.pos += 2; + this.finishToken(types.dollarBraceL); + return; + } else { + ++this.state.pos; + this.finishToken(types.backQuote); + return; + } + } -function toBlock(node, parent) { - if (t.isBlockStatement(node)) { - return node; - } + out += this.input.slice(chunkStart, this.state.pos); + this.finishToken(types.template, containsInvalid ? null : out); + return; + } - if (t.isEmptyStatement(node)) { - node = []; - } + if (ch === 92) { + out += this.input.slice(chunkStart, this.state.pos); + var escaped = this.readEscapedChar(true); - if (!Array.isArray(node)) { - if (!t.isStatement(node)) { - if (t.isFunction(parent)) { - node = t.returnStatement(node); - } else { - node = t.expressionStatement(node); + if (escaped === null) { + containsInvalid = true; + } else { + out += escaped; + } + + chunkStart = this.state.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + ++this.state.pos; + + switch (ch) { + case 13: + if (this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + } + + case 10: + out += "\n"; + break; + + default: + out += String.fromCharCode(ch); + break; + } + + ++this.state.curLine; + this.state.lineStart = this.state.pos; + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } } } + }, { + key: "readEscapedChar", + value: function readEscapedChar(inTemplate) { + var throwOnInvalid = !inTemplate; + var ch = this.input.charCodeAt(++this.state.pos); + ++this.state.pos; - node = [node]; - } + switch (ch) { + case 110: + return "\n"; - return t.blockStatement(node); -} + case 114: + return "\r"; -function valueToNode(value) { - if (value === undefined) { - return t.identifier("undefined"); - } + case 120: + { + var code = this.readHexChar(2, false, throwOnInvalid); + return code === null ? null : String.fromCharCode(code); + } - if (value === true || value === false) { - return t.booleanLiteral(value); - } + case 117: + { + var _code = this.readCodePoint(throwOnInvalid); - if (value === null) { - return t.nullLiteral(); - } + return _code === null ? null : String.fromCodePoint(_code); + } - if (typeof value === "string") { - return t.stringLiteral(value); - } + case 116: + return "\t"; - if (typeof value === "number") { - return t.numericLiteral(value); - } + case 98: + return "\b"; - if ((0, _isRegExp2.default)(value)) { - var pattern = value.source; - var flags = value.toString().match(/\/([a-z]+|)$/)[1]; - return t.regExpLiteral(pattern, flags); - } + case 118: + return "\x0B"; - if (Array.isArray(value)) { - return t.arrayExpression(value.map(t.valueToNode)); - } + case 102: + return "\f"; - if ((0, _isPlainObject2.default)(value)) { - var props = []; - for (var key in value) { - var nodeKey = void 0; - if (t.isValidIdentifier(key)) { - nodeKey = t.identifier(key); - } else { - nodeKey = t.stringLiteral(key); - } - props.push(t.objectProperty(nodeKey, t.valueToNode(value[key]))); - } - return t.objectExpression(props); - } + case 13: + if (this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + } - throw new Error("don't know how to turn this value into a node"); -} -},{"./index":151,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/core-js/number/max-safe-integer":98,"lodash/isPlainObject":493,"lodash/isRegExp":494}],142:[function(require,module,exports){ -"use strict"; + case 10: + this.state.lineStart = this.state.pos; + ++this.state.curLine; -var _index = require("../index"); + case 8232: + case 8233: + return ""; -var t = _interopRequireWildcard(_index); + case 56: + case 57: + if (inTemplate) { + var codePos = this.state.pos - 1; + this.state.invalidTemplateEscapePosition = codePos; + return null; + } -var _constants = require("../constants"); + default: + if (ch >= 48 && ch <= 55) { + var _codePos = this.state.pos - 1; -var _index2 = require("./index"); + var octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0]; + var octal = parseInt(octalStr, 8); -var _index3 = _interopRequireDefault(_index2); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this.state.pos += octalStr.length - 1; + var next = this.input.charCodeAt(this.state.pos); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + this.state.invalidTemplateEscapePosition = _codePos; + return null; + } else if (this.state.strict) { + this.raise(_codePos, "Octal literal in strict mode"); + } else if (!this.state.containsOctal) { + this.state.containsOctal = true; + this.state.octalPosition = _codePos; + } + } -(0, _index3.default)("ArrayExpression", { - fields: { - elements: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeOrValueType)("null", "Expression", "SpreadElement"))), - default: [] - } - }, - visitor: ["elements"], - aliases: ["Expression"] -}); + return String.fromCharCode(octal); + } -(0, _index3.default)("AssignmentExpression", { - fields: { - operator: { - validate: (0, _index2.assertValueType)("string") - }, - left: { - validate: (0, _index2.assertNodeType)("LVal") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") + return String.fromCharCode(ch); + } } - }, - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Expression"] -}); + }, { + key: "readHexChar", + value: function readHexChar(len, forceLen, throwOnInvalid) { + var codePos = this.state.pos; + var n = this.readInt(16, len, forceLen, false); -(0, _index3.default)("BinaryExpression", { - builder: ["operator", "left", "right"], - fields: { - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.BINARY_OPERATORS) - }, - left: { - validate: (0, _index2.assertNodeType)("Expression") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - visitor: ["left", "right"], - aliases: ["Binary", "Expression"] -}); + if (n === null) { + if (throwOnInvalid) { + this.raise(codePos, "Bad character escape sequence"); + } else { + this.state.pos = codePos - 1; + this.state.invalidTemplateEscapePosition = codePos - 1; + } + } -(0, _index3.default)("Directive", { - visitor: ["value"], - fields: { - value: { - validate: (0, _index2.assertNodeType)("DirectiveLiteral") + return n; } - } -}); + }, { + key: "readWord1", + value: function readWord1() { + var word = ""; + this.state.containsEsc = false; + var start = this.state.pos; + var chunkStart = this.state.pos; -(0, _index3.default)("DirectiveLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("string") - } - } -}); + while (this.state.pos < this.length) { + var ch = this.input.codePointAt(this.state.pos); -(0, _index3.default)("BlockStatement", { - builder: ["body", "directives"], - visitor: ["directives", "body"], - fields: { - directives: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block", "Statement"] -}); + if (isIdentifierChar(ch)) { + this.state.pos += ch <= 0xffff ? 1 : 2; + } else if (this.state.isIterator && ch === 64) { + ++this.state.pos; + } else if (ch === 92) { + this.state.containsEsc = true; + word += this.input.slice(chunkStart, this.state.pos); + var escStart = this.state.pos; + var identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; + + if (this.input.charCodeAt(++this.state.pos) !== 117) { + this.raise(this.state.pos, "Expecting Unicode escape sequence \\uXXXX"); + continue; + } -(0, _index3.default)("BreakStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); + ++this.state.pos; + var esc = this.readCodePoint(true); -(0, _index3.default)("CallExpression", { - visitor: ["callee", "arguments"], - fields: { - callee: { - validate: (0, _index2.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) - } - }, - aliases: ["Expression"] -}); + if (esc !== null) { + if (!identifierCheck(esc)) { + this.raise(escStart, "Invalid Unicode escape"); + } -(0, _index3.default)("CatchClause", { - visitor: ["param", "body"], - fields: { - param: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - } - }, - aliases: ["Scopable"] -}); + word += String.fromCodePoint(esc); + } -(0, _index3.default)("ConditionalExpression", { - visitor: ["test", "consequent", "alternate"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _index2.assertNodeType)("Expression") - }, - alternate: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - aliases: ["Expression", "Conditional"] -}); + chunkStart = this.state.pos; + } else { + break; + } + } -(0, _index3.default)("ContinueStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true + return word + this.input.slice(chunkStart, this.state.pos); } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); - -(0, _index3.default)("DebuggerStatement", { - aliases: ["Statement"] -}); - -(0, _index3.default)("DoWhileStatement", { - visitor: ["test", "body"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") + }, { + key: "isIterator", + value: function isIterator(word) { + return word === "@@iterator" || word === "@@asyncIterator"; } - }, - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] -}); + }, { + key: "readWord", + value: function readWord() { + var word = this.readWord1(); + var type = keywords.get(word) || types.name; -(0, _index3.default)("EmptyStatement", { - aliases: ["Statement"] -}); + if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) { + this.raise(this.state.pos, "Invalid identifier ".concat(word)); + } -(0, _index3.default)("ExpressionStatement", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _index2.assertNodeType)("Expression") + this.finishToken(type, word); } - }, - aliases: ["Statement", "ExpressionWrapper"] -}); + }, { + key: "checkKeywordEscapes", + value: function checkKeywordEscapes() { + var kw = this.state.type.keyword; -(0, _index3.default)("File", { - builder: ["program", "comments", "tokens"], - visitor: ["program"], - fields: { - program: { - validate: (0, _index2.assertNodeType)("Program") + if (kw && this.state.containsEsc) { + this.raise(this.state.start, "Escape sequence in keyword ".concat(kw)); + } } - } -}); + }, { + key: "braceIsBlock", + value: function braceIsBlock(prevType) { + var parent = this.curContext(); -(0, _index3.default)("ForInStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index2.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); + if (parent === types$1.functionExpression || parent === types$1.functionStatement) { + return true; + } -(0, _index3.default)("ForStatement", { - visitor: ["init", "test", "update", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], - fields: { - init: { - validate: (0, _index2.assertNodeType)("VariableDeclaration", "Expression"), - optional: true - }, - test: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - update: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); + if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) { + return !parent.isExpr; + } -(0, _index3.default)("FunctionDeclaration", { - builder: ["id", "params", "body", "generator", "async"], - visitor: ["id", "params", "body", "returnType", "typeParameters"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - params: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - }, - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"] -}); + if (prevType === types._return || prevType === types.name && this.state.exprAllowed) { + return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)); + } -(0, _index3.default)("FunctionExpression", { - inherits: "FunctionDeclaration", - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - }, - params: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - } -}); + if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) { + return true; + } -(0, _index3.default)("Identifier", { - builder: ["name"], - visitor: ["typeAnnotation"], - aliases: ["Expression", "LVal"], - fields: { - name: { - validate: function validate(node, key, val) { - if (!t.isValidIdentifier(val)) {} + if (prevType === types.braceL) { + return parent === types$1.braceStatement; } - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - } - } -}); -(0, _index3.default)("IfStatement", { - visitor: ["test", "consequent", "alternate"], - aliases: ["Statement", "Conditional"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _index2.assertNodeType)("Statement") - }, - alternate: { - optional: true, - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); + if (prevType === types._var || prevType === types._const || prevType === types.name) { + return false; + } -(0, _index3.default)("LabeledStatement", { - visitor: ["label", "body"], - aliases: ["Statement"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); + if (prevType === types.relational) { + return true; + } -(0, _index3.default)("StringLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("string") + return !this.state.exprAllowed; } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); + }, { + key: "updateContext", + value: function updateContext(prevType) { + var type = this.state.type; + var update; -(0, _index3.default)("NumericLiteral", { - builder: ["value"], - deprecatedAlias: "NumberLiteral", - fields: { - value: { - validate: (0, _index2.assertValueType)("number") + if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) { + this.state.exprAllowed = false; + } else if (update = type.updateContext) { + update.call(this, prevType); + } else { + this.state.exprAllowed = type.beforeExpr; + } } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); + }]); -(0, _index3.default)("NullLiteral", { - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); + return Tokenizer; +}(LocationParser); -(0, _index3.default)("BooleanLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("boolean") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); +var literal = /^('|")((?:\\?.)*?)\1/; -(0, _index3.default)("RegExpLiteral", { - builder: ["pattern", "flags"], - deprecatedAlias: "RegexLiteral", - aliases: ["Expression", "Literal"], - fields: { - pattern: { - validate: (0, _index2.assertValueType)("string") - }, - flags: { - validate: (0, _index2.assertValueType)("string"), - default: "" - } +var UtilParser = +/*#__PURE__*/ +function (_Tokenizer) { + _inherits(UtilParser, _Tokenizer); + + function UtilParser() { + _classCallCheck(this, UtilParser); + + return _possibleConstructorReturn(this, _getPrototypeOf(UtilParser).apply(this, arguments)); } -}); -(0, _index3.default)("LogicalExpression", { - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Binary", "Expression"], - fields: { - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.LOGICAL_OPERATORS) - }, - left: { - validate: (0, _index2.assertNodeType)("Expression") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") + _createClass(UtilParser, [{ + key: "addExtra", + value: function addExtra(node, key, val) { + if (!node) return; + var extra = node.extra = node.extra || {}; + extra[key] = val; } - } -}); + }, { + key: "isRelational", + value: function isRelational(op) { + return this.match(types.relational) && this.state.value === op; + } + }, { + key: "isLookaheadRelational", + value: function isLookaheadRelational(op) { + var next = this.nextTokenStart(); -(0, _index3.default)("MemberExpression", { - builder: ["object", "property", "computed"], - visitor: ["object", "property"], - aliases: ["Expression", "LVal"], - fields: { - object: { - validate: (0, _index2.assertNodeType)("Expression") - }, - property: { - validate: function validate(node, key, val) { - var expectedType = node.computed ? "Expression" : "Identifier"; - (0, _index2.assertNodeType)(expectedType)(node, key, val); + if (this.input.charAt(next) === op) { + if (next + 1 === this.input.length) { + return true; + } + + var afterNext = this.input.charCodeAt(next + 1); + return afterNext !== op.charCodeAt(0) && afterNext !== 61; } - }, - computed: { - default: false - } - } -}); -(0, _index3.default)("NewExpression", { - visitor: ["callee", "arguments"], - aliases: ["Expression"], - fields: { - callee: { - validate: (0, _index2.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) + return false; } - } -}); - -(0, _index3.default)("Program", { - visitor: ["directives", "body"], - builder: ["body", "directives"], - fields: { - directives: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) + }, { + key: "expectRelational", + value: function expectRelational(op) { + if (this.isRelational(op)) { + this.next(); + } else { + this.unexpected(null, types.relational); + } } - }, - aliases: ["Scopable", "BlockParent", "Block", "FunctionParent"] -}); + }, { + key: "eatRelational", + value: function eatRelational(op) { + if (this.isRelational(op)) { + this.next(); + return true; + } -(0, _index3.default)("ObjectExpression", { - visitor: ["properties"], - aliases: ["Expression"], - fields: { - properties: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadProperty"))) + return false; } - } -}); + }, { + key: "isContextual", + value: function isContextual(name) { + return this.match(types.name) && this.state.value === name && !this.state.containsEsc; + } + }, { + key: "isUnparsedContextual", + value: function isUnparsedContextual(nameStart, name) { + var nameEnd = nameStart + name.length; + return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd))); + } + }, { + key: "isLookaheadContextual", + value: function isLookaheadContextual(name) { + var next = this.nextTokenStart(); + return this.isUnparsedContextual(next, name); + } + }, { + key: "eatContextual", + value: function eatContextual(name) { + return this.isContextual(name) && this.eat(types.name); + } + }, { + key: "expectContextual", + value: function expectContextual(name, message) { + if (!this.eatContextual(name)) this.unexpected(null, message); + } + }, { + key: "canInsertSemicolon", + value: function canInsertSemicolon() { + return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak(); + } + }, { + key: "hasPrecedingLineBreak", + value: function hasPrecedingLineBreak() { + return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)); + } + }, { + key: "isLineTerminator", + value: function isLineTerminator() { + return this.eat(types.semi) || this.canInsertSemicolon(); + } + }, { + key: "semicolon", + value: function semicolon() { + if (!this.isLineTerminator()) this.unexpected(null, types.semi); + } + }, { + key: "expect", + value: function expect(type, pos) { + this.eat(type) || this.unexpected(pos, type); + } + }, { + key: "assertNoSpace", + value: function assertNoSpace() { + var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "Unexpected space."; -(0, _index3.default)("ObjectMethod", { - builder: ["kind", "key", "params", "body", "computed"], - fields: { - kind: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("method", "get", "set")), - default: "method" - }, - computed: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); + if (this.state.start > this.state.lastTokEnd) { + this.raise(this.state.lastTokEnd, message); } - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") } - }, - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] -}); + }, { + key: "unexpected", + value: function unexpected(pos) { + var messageOrType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "Unexpected token"; -(0, _index3.default)("ObjectProperty", { - builder: ["key", "value", "computed", "shorthand", "decorators"], - fields: { - computed: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); + if (typeof messageOrType !== "string") { + messageOrType = "Unexpected token, expected \"".concat(messageOrType.label, "\""); } - }, - value: { - validate: (0, _index2.assertNodeType)("Expression", "Pattern", "RestElement") - }, - shorthand: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))), - optional: true + + throw this.raise(pos != null ? pos : this.state.start, messageOrType); } - }, - visitor: ["key", "value", "decorators"], - aliases: ["UserWhitespacable", "Property", "ObjectMember"] -}); + }, { + key: "expectPlugin", + value: function expectPlugin(name, pos) { + if (!this.hasPlugin(name)) { + throw this.raise(pos != null ? pos : this.state.start, "This experimental syntax requires enabling the parser plugin: '".concat(name, "'"), { + missingPluginNames: [name] + }); + } -(0, _index3.default)("RestElement", { - visitor: ["argument", "typeAnnotation"], - aliases: ["LVal"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("LVal") - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) + return true; } - } -}); + }, { + key: "expectOnePlugin", + value: function expectOnePlugin(names, pos) { + var _this35 = this; -(0, _index3.default)("ReturnStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true + if (!names.some(function (n) { + return _this35.hasPlugin(n); + })) { + throw this.raise(pos != null ? pos : this.state.start, "This experimental syntax requires enabling one of the following parser plugin(s): '".concat(names.join(", "), "'"), { + missingPluginNames: names + }); + } } - } -}); + }, { + key: "checkYieldAwaitInDefaultParams", + value: function checkYieldAwaitInDefaultParams() { + if (this.state.yieldPos !== -1 && (this.state.awaitPos === -1 || this.state.yieldPos < this.state.awaitPos)) { + this.raise(this.state.yieldPos, "Yield cannot be used as name inside a generator function"); + } -(0, _index3.default)("SequenceExpression", { - visitor: ["expressions"], - fields: { - expressions: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression"))) + if (this.state.awaitPos !== -1) { + this.raise(this.state.awaitPos, "Await cannot be used as name inside an async function"); + } } - }, - aliases: ["Expression"] -}); + }, { + key: "strictDirective", + value: function strictDirective(start) { + for (;;) { + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) break; + if (match[2] === "use strict") return true; + start += match[0].length; + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; -(0, _index3.default)("SwitchCase", { - visitor: ["test", "consequent"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - consequent: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) + if (this.input[start] === ";") { + start++; + } + } + + return false; } - } -}); + }, { + key: "tryParse", + value: function tryParse(fn) { + var oldState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.state.clone(); + var abortSignal = { + node: null + }; -(0, _index3.default)("SwitchStatement", { - visitor: ["discriminant", "cases"], - aliases: ["Statement", "BlockParent", "Scopable"], - fields: { - discriminant: { - validate: (0, _index2.assertNodeType)("Expression") - }, - cases: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("SwitchCase"))) - } - } -}); + try { + var node = fn(function () { + var node = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + abortSignal.node = node; + throw abortSignal; + }); -(0, _index3.default)("ThisExpression", { - aliases: ["Expression"] -}); + if (this.state.errors.length > oldState.errors.length) { + var failState = this.state; + this.state = oldState; + return { + node: node, + error: failState.errors[oldState.errors.length], + thrown: false, + aborted: false, + failState: failState + }; + } -(0, _index3.default)("ThrowStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); + return { + node: node, + error: null, + thrown: false, + aborted: false, + failState: null + }; + } catch (error) { + var _failState = this.state; + this.state = oldState; + + if (error instanceof SyntaxError) { + return { + node: null, + error: error, + thrown: true, + aborted: false, + failState: _failState + }; + } -(0, _index3.default)("TryStatement", { - visitor: ["block", "handler", "finalizer"], - aliases: ["Statement"], - fields: { - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - handler: { - optional: true, - handler: (0, _index2.assertNodeType)("BlockStatement") - }, - finalizer: { - optional: true, - validate: (0, _index2.assertNodeType)("BlockStatement") - } - } -}); + if (error === abortSignal) { + return { + node: abortSignal.node, + error: null, + thrown: false, + aborted: true, + failState: _failState + }; + } -(0, _index3.default)("UnaryExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: true - }, - argument: { - validate: (0, _index2.assertNodeType)("Expression") - }, - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.UNARY_OPERATORS) + throw error; + } } - }, - visitor: ["argument"], - aliases: ["UnaryLike", "Expression"] -}); + }]); -(0, _index3.default)("UpdateExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: false - }, - argument: { - validate: (0, _index2.assertNodeType)("Expression") - }, - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.UPDATE_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["Expression"] -}); + return UtilParser; +}(Tokenizer); -(0, _index3.default)("VariableDeclaration", { - builder: ["kind", "declarations"], - visitor: ["declarations"], - aliases: ["Statement", "Declaration"], - fields: { - kind: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("var", "let", "const")) - }, - declarations: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("VariableDeclarator"))) - } - } -}); +var Node = +/*#__PURE__*/ +function () { + function Node(parser, pos, loc) { + _classCallCheck(this, Node); -(0, _index3.default)("VariableDeclarator", { - visitor: ["id", "init"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("LVal") - }, - init: { - optional: true, - validate: (0, _index2.assertNodeType)("Expression") - } + this.type = ""; + this.start = pos; + this.end = 0; + this.loc = new SourceLocation(loc); + if (parser && parser.options.ranges) this.range = [pos, 0]; + if (parser && parser.filename) this.loc.filename = parser.filename; } -}); -(0, _index3.default)("WhileStatement", { - visitor: ["test", "body"], - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") - } - } -}); + _createClass(Node, [{ + key: "__clone", + value: function __clone() { + var newNode = new Node(); + var keys = Object.keys(this); -(0, _index3.default)("WithStatement", { - visitor: ["object", "body"], - aliases: ["Statement"], - fields: { - object: { - object: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") - } - } -}); -},{"../constants":140,"../index":151,"./index":146}],143:[function(require,module,exports){ -"use strict"; + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; -var _index = require("./index"); + if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { + newNode[key] = this[key]; + } + } -var _index2 = _interopRequireDefault(_index); + return newNode; + } + }]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return Node; +}(); -(0, _index2.default)("AssignmentPattern", { - visitor: ["left", "right"], - aliases: ["Pattern", "LVal"], - fields: { - left: { - validate: (0, _index.assertNodeType)("Identifier") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) +var NodeUtils = +/*#__PURE__*/ +function (_UtilParser) { + _inherits(NodeUtils, _UtilParser); + + function NodeUtils() { + _classCallCheck(this, NodeUtils); + + return _possibleConstructorReturn(this, _getPrototypeOf(NodeUtils).apply(this, arguments)); + } + + _createClass(NodeUtils, [{ + key: "startNode", + value: function startNode() { + return new Node(this, this.state.start, this.state.startLoc); + } + }, { + key: "startNodeAt", + value: function startNodeAt(pos, loc) { + return new Node(this, pos, loc); + } + }, { + key: "startNodeAtNode", + value: function startNodeAtNode(type) { + return this.startNodeAt(type.start, type.loc.start); + } + }, { + key: "finishNode", + value: function finishNode(node, type) { + return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc); + } + }, { + key: "finishNodeAt", + value: function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + node.loc.end = loc; + if (this.options.ranges) node.range[1] = pos; + this.processComment(node); + return node; } - } -}); - -(0, _index2.default)("ArrayPattern", { - visitor: ["elements", "typeAnnotation"], - aliases: ["Pattern", "LVal"], - fields: { - elements: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Identifier", "Pattern", "RestElement"))) - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) + }, { + key: "resetStartLocation", + value: function resetStartLocation(node, start, startLoc) { + node.start = start; + node.loc.start = startLoc; + if (this.options.ranges) node.range[0] = start; + } + }, { + key: "resetEndLocation", + value: function resetEndLocation(node) { + var end = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.state.lastTokEnd; + var endLoc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.state.lastTokEndLoc; + node.end = end; + node.loc.end = endLoc; + if (this.options.ranges) node.range[1] = end; + } + }, { + key: "resetStartLocationFromNode", + value: function resetStartLocationFromNode(node, locationNode) { + this.resetStartLocation(node, locationNode.start, locationNode.loc.start); } - } -}); + }]); -(0, _index2.default)("ArrowFunctionExpression", { - builder: ["params", "body", "async"], - visitor: ["params", "body", "returnType", "typeParameters"], - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: { - params: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index.assertNodeType)("BlockStatement", "Expression") - }, - async: { - validate: (0, _index.assertValueType)("boolean"), - default: false - } - } -}); + return NodeUtils; +}(UtilParser); -(0, _index2.default)("ClassBody", { - visitor: ["body"], - fields: { - body: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ClassMethod", "ClassProperty"))) - } - } -}); +var LValParser = +/*#__PURE__*/ +function (_NodeUtils) { + _inherits(LValParser, _NodeUtils); -(0, _index2.default)("ClassDeclaration", { - builder: ["id", "superClass", "body", "decorators"], - visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], - aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"], - fields: { - id: { - validate: (0, _index.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); + function LValParser() { + _classCallCheck(this, LValParser); -(0, _index2.default)("ClassExpression", { - inherits: "ClassDeclaration", - aliases: ["Scopable", "Class", "Expression", "Pureish"], - fields: { - id: { - optional: true, - validate: (0, _index.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } + return _possibleConstructorReturn(this, _getPrototypeOf(LValParser).apply(this, arguments)); } -}); -(0, _index2.default)("ExportAllDeclaration", { - visitor: ["source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - source: { - validate: (0, _index.assertNodeType)("StringLiteral") - } - } -}); + _createClass(LValParser, [{ + key: "toAssignable", + value: function toAssignable(node, isBinding, contextDescription) { + var _node$extra2; -(0, _index2.default)("ExportDefaultDeclaration", { - visitor: ["declaration"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _index.assertNodeType)("FunctionDeclaration", "ClassDeclaration", "Expression") - } - } -}); + if (node) { + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + break; -(0, _index2.default)("ExportNamedDeclaration", { - visitor: ["declaration", "specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _index.assertNodeType)("Declaration"), - optional: true - }, - specifiers: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ExportSpecifier"))) - }, - source: { - validate: (0, _index.assertNodeType)("StringLiteral"), - optional: true - } - } -}); + case "ObjectExpression": + node.type = "ObjectPattern"; -(0, _index2.default)("ExportSpecifier", { - visitor: ["local", "exported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - }, - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + for (var i = 0, length = node.properties.length, _last2 = length - 1; i < length; i++) { + var _node$extra; -(0, _index2.default)("ForOfStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - body: { - validate: (0, _index.assertNodeType)("Statement") - } - } -}); + var prop = node.properties[i]; + var isLast = i === _last2; + this.toAssignableObjectExpressionProp(prop, isBinding, isLast); -(0, _index2.default)("ImportDeclaration", { - visitor: ["specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration"], - fields: { - specifiers: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) - }, - source: { - validate: (0, _index.assertNodeType)("StringLiteral") - } - } -}); + if (isLast && prop.type === "RestElement" && ((_node$extra = node.extra) === null || _node$extra === void 0 ? void 0 : _node$extra.trailingComma)) { + this.raiseRestNotLast(node.extra.trailingComma); + } + } -(0, _index2.default)("ImportDefaultSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + break; -(0, _index2.default)("ImportNamespaceSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + case "ObjectProperty": + this.toAssignable(node.value, isBinding, contextDescription); + break; -(0, _index2.default)("ImportSpecifier", { - visitor: ["local", "imported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - }, - imported: { - validate: (0, _index.assertNodeType)("Identifier") - }, - importKind: { - validate: (0, _index.assertOneOf)(null, "type", "typeof") - } - } -}); + case "SpreadElement": + { + this.checkToRestConversion(node); + node.type = "RestElement"; + var arg = node.argument; + this.toAssignable(arg, isBinding, contextDescription); + break; + } -(0, _index2.default)("MetaProperty", { - visitor: ["meta", "property"], - aliases: ["Expression"], - fields: { - meta: { - validate: (0, _index.assertValueType)("string") - }, - property: { - validate: (0, _index.assertValueType)("string") - } - } -}); + case "ArrayExpression": + node.type = "ArrayPattern"; + this.toAssignableList(node.elements, isBinding, contextDescription, (_node$extra2 = node.extra) === null || _node$extra2 === void 0 ? void 0 : _node$extra2.trailingComma); + break; -(0, _index2.default)("ClassMethod", { - aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], - builder: ["kind", "key", "params", "body", "computed", "static"], - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - fields: { - kind: { - validate: (0, _index.chain)((0, _index.assertValueType)("string"), (0, _index.assertOneOf)("get", "set", "method", "constructor")), - default: "method" - }, - computed: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - static: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - params: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index.assertValueType)("boolean") - } - } -}); + case "AssignmentExpression": + if (node.operator !== "=") { + this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); + } -(0, _index2.default)("ObjectPattern", { - visitor: ["properties", "typeAnnotation"], - aliases: ["Pattern", "LVal"], - fields: { - properties: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("RestProperty", "Property"))) - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding, contextDescription); + break; -(0, _index2.default)("SpreadElement", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + case "ParenthesizedExpression": + node.expression = this.toAssignable(node.expression, isBinding, contextDescription); + break; -(0, _index2.default)("Super", { - aliases: ["Expression"] -}); + case "MemberExpression": + if (!isBinding) break; -(0, _index2.default)("TaggedTemplateExpression", { - visitor: ["tag", "quasi"], - aliases: ["Expression"], - fields: { - tag: { - validate: (0, _index.assertNodeType)("Expression") - }, - quasi: { - validate: (0, _index.assertNodeType)("TemplateLiteral") - } - } -}); + default: + } + } -(0, _index2.default)("TemplateElement", { - builder: ["value", "tail"], - fields: { - value: {}, - tail: { - validate: (0, _index.assertValueType)("boolean"), - default: false + return node; } - } -}); - -(0, _index2.default)("TemplateLiteral", { - visitor: ["quasis", "expressions"], - aliases: ["Expression", "Literal"], - fields: { - quasis: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("TemplateElement"))) - }, - expressions: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Expression"))) + }, { + key: "toAssignableObjectExpressionProp", + value: function toAssignableObjectExpressionProp(prop, isBinding, isLast) { + if (prop.type === "ObjectMethod") { + var error = prop.kind === "get" || prop.kind === "set" ? "Object pattern can't contain getter or setter" : "Object pattern can't contain methods"; + this.raise(prop.key.start, error); + } else if (prop.type === "SpreadElement" && !isLast) { + this.raiseRestNotLast(prop.start); + } else { + this.toAssignable(prop, isBinding, "object destructuring pattern"); + } } - } -}); + }, { + key: "toAssignableList", + value: function toAssignableList(exprList, isBinding, contextDescription, trailingCommaPos) { + var end = exprList.length; -(0, _index2.default)("YieldExpression", { - builder: ["argument", "delegate"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - delegate: { - validate: (0, _index.assertValueType)("boolean"), - default: false - }, - argument: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":146}],144:[function(require,module,exports){ -"use strict"; + if (end) { + var _last3 = exprList[end - 1]; -var _index = require("./index"); + if (_last3 && _last3.type === "RestElement") { + --end; + } else if (_last3 && _last3.type === "SpreadElement") { + _last3.type = "RestElement"; + var arg = _last3.argument; + this.toAssignable(arg, isBinding, contextDescription); -var _index2 = _interopRequireDefault(_index); + if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") { + this.unexpected(arg.start); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (trailingCommaPos) { + this.raiseTrailingCommaAfterRest(trailingCommaPos); + } -(0, _index2.default)("AwaitExpression", { - builder: ["argument"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + --end; + } + } -(0, _index2.default)("ForAwaitStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - body: { - validate: (0, _index.assertNodeType)("Statement") - } - } -}); + for (var i = 0; i < end; i++) { + var elt = exprList[i]; -(0, _index2.default)("BindExpression", { - visitor: ["object", "callee"], - aliases: ["Expression"], - fields: {} -}); + if (elt) { + this.toAssignable(elt, isBinding, contextDescription); -(0, _index2.default)("Import", { - aliases: ["Expression"] -}); + if (elt.type === "RestElement") { + this.raiseRestNotLast(elt.start); + } + } + } -(0, _index2.default)("Decorator", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") + return exprList; } - } -}); - -(0, _index2.default)("DoExpression", { - visitor: ["body"], - aliases: ["Expression"], - fields: { - body: { - validate: (0, _index.assertNodeType)("BlockStatement") + }, { + key: "toReferencedList", + value: function toReferencedList(exprList, isParenthesizedExpr) { + return exprList; } - } -}); + }, { + key: "toReferencedListDeep", + value: function toReferencedListDeep(exprList, isParenthesizedExpr) { + this.toReferencedList(exprList, isParenthesizedExpr); -(0, _index2.default)("ExportDefaultSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + for (var _i = 0; _i < exprList.length; _i++) { + var expr = exprList[_i]; -(0, _index2.default)("ExportNamespaceSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + if (expr && expr.type === "ArrayExpression") { + this.toReferencedListDeep(expr.elements); + } + } -(0, _index2.default)("RestProperty", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("LVal") + return exprList; } - } -}); - -(0, _index2.default)("SpreadProperty", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") + }, { + key: "parseSpread", + value: function parseSpread(refShorthandDefaultPos, refNeedsArrowPos) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refShorthandDefaultPos, undefined, refNeedsArrowPos); + return this.finishNode(node, "SpreadElement"); } - } -}); -},{"./index":146}],145:[function(require,module,exports){ -"use strict"; + }, { + key: "parseRestBinding", + value: function parseRestBinding() { + var node = this.startNode(); + this.next(); + node.argument = this.parseBindingAtom(); + return this.finishNode(node, "RestElement"); + } + }, { + key: "parseBindingAtom", + value: function parseBindingAtom() { + switch (this.state.type) { + case types.bracketL: + { + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types.bracketR, 93, true); + return this.finishNode(node, "ArrayPattern"); + } -var _index = require("./index"); + case types.braceL: + return this.parseObj(true); + } -var _index2 = _interopRequireDefault(_index); + return this.parseIdentifier(); + } + }, { + key: "parseBindingList", + value: function parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) { + var elts = []; + var first = true; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(types.comma); + } -(0, _index2.default)("AnyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + if (allowEmpty && this.match(types.comma)) { + elts.push(null); + } else if (this.eat(close)) { + break; + } else if (this.match(types.ellipsis)) { + elts.push(this.parseAssignableListItemTypes(this.parseRestBinding())); + this.checkCommaAfterRest(closeCharCode); + this.expect(close); + break; + } else { + var decorators = []; -(0, _index2.default)("ArrayTypeAnnotation", { - visitor: ["elementType"], - aliases: ["Flow"], - fields: {} -}); + if (this.match(types.at) && this.hasPlugin("decorators")) { + this.raise(this.state.start, "Stage 2 decorators cannot be used to decorate parameters"); + } -(0, _index2.default)("BooleanTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + while (this.match(types.at)) { + decorators.push(this.parseDecorator()); + } -(0, _index2.default)("BooleanLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); + elts.push(this.parseAssignableListItem(allowModifiers, decorators)); + } + } -(0, _index2.default)("NullLiteralTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + return elts; + } + }, { + key: "parseAssignableListItem", + value: function parseAssignableListItem(allowModifiers, decorators) { + var left = this.parseMaybeDefault(); + this.parseAssignableListItemTypes(left); + var elt = this.parseMaybeDefault(left.start, left.loc.start, left); -(0, _index2.default)("ClassImplements", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); + if (decorators.length) { + left.decorators = decorators; + } -(0, _index2.default)("ClassProperty", { - visitor: ["key", "value", "typeAnnotation", "decorators"], - builder: ["key", "value", "typeAnnotation", "decorators", "computed"], - aliases: ["Property"], - fields: { - computed: { - validate: (0, _index.assertValueType)("boolean"), - default: false + return elt; } - } -}); + }, { + key: "parseAssignableListItemTypes", + value: function parseAssignableListItemTypes(param) { + return param; + } + }, { + key: "parseMaybeDefault", + value: function parseMaybeDefault(startPos, startLoc, left) { + startLoc = startLoc || this.state.startLoc; + startPos = startPos || this.state.start; + left = left || this.parseBindingAtom(); + if (!this.eat(types.eq)) return left; + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern"); + } + }, { + key: "checkLVal", + value: function checkLVal(expr) { + var bindingType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : BIND_NONE; + var checkClashes = arguments.length > 2 ? arguments[2] : undefined; + var contextDescription = arguments.length > 3 ? arguments[3] : undefined; + var disallowLetBinding = arguments.length > 4 ? arguments[4] : undefined; + var strictModeChanged = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; -(0, _index2.default)("DeclareClass", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + switch (expr.type) { + case "Identifier": + if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(expr.name, this.inModule) : isStrictBindOnlyReservedWord(expr.name))) { + this.raise(expr.start, "".concat(bindingType === BIND_NONE ? "Assigning to" : "Binding", " '").concat(expr.name, "' in strict mode")); + } -(0, _index2.default)("DeclareFunction", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + if (checkClashes) { + var key = "_".concat(expr.name); -(0, _index2.default)("DeclareInterface", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareModule", { - visitor: ["id", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + if (checkClashes[key]) { + this.raise(expr.start, "Argument name clash"); + } else { + checkClashes[key] = true; + } + } -(0, _index2.default)("DeclareModuleExports", { - visitor: ["typeAnnotation"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + if (disallowLetBinding && expr.name === "let") { + this.raise(expr.start, "'let' is not allowed to be used as a name in 'let' or 'const' declarations."); + } -(0, _index2.default)("DeclareTypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + if (!(bindingType & BIND_NONE)) { + this.scope.declareName(expr.name, bindingType, expr.start); + } -(0, _index2.default)("DeclareOpaqueType", { - visitor: ["id", "typeParameters", "supertype"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + break; -(0, _index2.default)("DeclareVariable", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + case "MemberExpression": + if (bindingType !== BIND_NONE) { + this.raise(expr.start, "Binding member expression"); + } -(0, _index2.default)("DeclareExportDeclaration", { - visitor: ["declaration", "specifiers", "source"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + break; -(0, _index2.default)("ExistentialTypeParam", { - aliases: ["Flow"] -}); + case "ObjectPattern": + for (var _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) { + var prop = _expr$properties[_i2]; + if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue; + this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern", disallowLetBinding); + } -(0, _index2.default)("FunctionTypeAnnotation", { - visitor: ["typeParameters", "params", "rest", "returnType"], - aliases: ["Flow"], - fields: {} -}); + break; -(0, _index2.default)("FunctionTypeParam", { - visitor: ["name", "typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); + case "ArrayPattern": + for (var _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) { + var elem = _expr$elements[_i3]; -(0, _index2.default)("GenericTypeAnnotation", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); + if (elem) { + this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern", disallowLetBinding); + } + } -(0, _index2.default)("InterfaceExtends", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); + break; -(0, _index2.default)("InterfaceDeclaration", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + case "AssignmentPattern": + this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern"); + break; -(0, _index2.default)("IntersectionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); + case "RestElement": + this.checkLVal(expr.argument, bindingType, checkClashes, "rest element"); + break; -(0, _index2.default)("MixedTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); + case "ParenthesizedExpression": + this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression"); + break; -(0, _index2.default)("EmptyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); + default: + { + var message = (bindingType === BIND_NONE ? "Invalid" : "Binding invalid") + " left-hand side" + (contextDescription ? " in " + contextDescription : "expression"); + this.raise(expr.start, message); + } + } + } + }, { + key: "checkToRestConversion", + value: function checkToRestConversion(node) { + if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") { + this.raise(node.argument.start, "Invalid rest operator's argument"); + } + } + }, { + key: "checkCommaAfterRest", + value: function checkCommaAfterRest(close) { + if (this.match(types.comma)) { + if (this.lookaheadCharCode() === close) { + this.raiseTrailingCommaAfterRest(this.state.start); + } else { + this.raiseRestNotLast(this.state.start); + } + } + } + }, { + key: "raiseRestNotLast", + value: function raiseRestNotLast(pos) { + throw this.raise(pos, "Rest element must be last element"); + } + }, { + key: "raiseTrailingCommaAfterRest", + value: function raiseTrailingCommaAfterRest(pos) { + this.raise(pos, "Unexpected trailing comma after rest element"); + } + }]); -(0, _index2.default)("NullableTypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); + return LValParser; +}(NodeUtils); -(0, _index2.default)("NumericLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); +var unwrapParenthesizedExpression = function unwrapParenthesizedExpression(node) { + return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; +}; -(0, _index2.default)("NumberTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); +var ExpressionParser = +/*#__PURE__*/ +function (_LValParser) { + _inherits(ExpressionParser, _LValParser); -(0, _index2.default)("StringLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); + function ExpressionParser() { + _classCallCheck(this, ExpressionParser); -(0, _index2.default)("StringTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + return _possibleConstructorReturn(this, _getPrototypeOf(ExpressionParser).apply(this, arguments)); + } -(0, _index2.default)("ThisTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + _createClass(ExpressionParser, [{ + key: "checkDuplicatedProto", + value: function checkDuplicatedProto(prop, protoRef) { + if (prop.type === "SpreadElement" || prop.computed || prop.kind || prop.shorthand) { + return; + } -(0, _index2.default)("TupleTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); + var key = prop.key; + var name = key.type === "Identifier" ? key.name : String(key.value); -(0, _index2.default)("TypeofTypeAnnotation", { - visitor: ["argument"], - aliases: ["Flow"], - fields: {} -}); + if (name === "__proto__") { + if (protoRef.used && !protoRef.start) { + protoRef.start = key.start; + } -(0, _index2.default)("TypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + protoRef.used = true; + } + } + }, { + key: "getExpression", + value: function getExpression() { + this.scope.enter(SCOPE_PROGRAM); + this.nextToken(); + var expr = this.parseExpression(); -(0, _index2.default)("OpaqueType", { - visitor: ["id", "typeParameters", "impltype", "supertype"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + if (!this.match(types.eof)) { + this.unexpected(); + } -(0, _index2.default)("TypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); + expr.comments = this.state.comments; + expr.errors = this.state.errors; + return expr; + } + }, { + key: "parseExpression", + value: function parseExpression(noIn, refShorthandDefaultPos) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos); -(0, _index2.default)("TypeCastExpression", { - visitor: ["expression", "typeAnnotation"], - aliases: ["Flow", "ExpressionWrapper", "Expression"], - fields: {} -}); + if (this.match(types.comma)) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; -(0, _index2.default)("TypeParameter", { - visitor: ["bound"], - aliases: ["Flow"], - fields: {} -}); + while (this.eat(types.comma)) { + node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos)); + } -(0, _index2.default)("TypeParameterDeclaration", { - visitor: ["params"], - aliases: ["Flow"], - fields: {} -}); + this.toReferencedList(node.expressions); + return this.finishNode(node, "SequenceExpression"); + } -(0, _index2.default)("TypeParameterInstantiation", { - visitor: ["params"], - aliases: ["Flow"], - fields: {} -}); + return expr; + } + }, { + key: "parseMaybeAssign", + value: function parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; -(0, _index2.default)("ObjectTypeAnnotation", { - visitor: ["properties", "indexers", "callProperties"], - aliases: ["Flow"], - fields: {} -}); + if (this.isContextual("yield")) { + if (this.scope.inGenerator) { + var _left = this.parseYield(noIn); -(0, _index2.default)("ObjectTypeCallProperty", { - visitor: ["value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); + if (afterLeftParse) { + _left = afterLeftParse.call(this, _left, startPos, startLoc); + } -(0, _index2.default)("ObjectTypeIndexer", { - visitor: ["id", "key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); + return _left; + } else { + this.state.exprAllowed = false; + } + } -(0, _index2.default)("ObjectTypeProperty", { - visitor: ["key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); + var failOnShorthandAssign; -(0, _index2.default)("ObjectTypeSpreadProperty", { - visitor: ["argument"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); + if (refShorthandDefaultPos) { + failOnShorthandAssign = false; + } else { + refShorthandDefaultPos = { + start: 0 + }; + failOnShorthandAssign = true; + } -(0, _index2.default)("QualifiedTypeIdentifier", { - visitor: ["id", "qualification"], - aliases: ["Flow"], - fields: {} -}); + if (this.match(types.parenL) || this.match(types.name)) { + this.state.potentialArrowAt = this.state.start; + } -(0, _index2.default)("UnionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); + var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos); -(0, _index2.default)("VoidTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -},{"./index":146}],146:[function(require,module,exports){ -"use strict"; + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startPos, startLoc); + } -exports.__esModule = true; -exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = undefined; + if (this.state.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + var operator = this.state.value; + node.operator = operator; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (operator === "??=") { + this.expectPlugin("nullishCoalescingOperator"); + this.expectPlugin("logicalAssignment"); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + if (operator === "||=" || operator === "&&=") { + this.expectPlugin("logicalAssignment"); + } -var _stringify = require("babel-runtime/core-js/json/stringify"); + node.left = this.match(types.eq) ? this.toAssignable(left, undefined, "assignment expression") : left; -var _stringify2 = _interopRequireDefault(_stringify); + if (refShorthandDefaultPos.start >= node.left.start) { + refShorthandDefaultPos.start = 0; + } -var _typeof2 = require("babel-runtime/helpers/typeof"); + this.checkLVal(left, undefined, undefined, "assignment expression"); + var maybePattern = unwrapParenthesizedExpression(left); + var patternErrorMsg; -var _typeof3 = _interopRequireDefault(_typeof2); + if (maybePattern.type === "ObjectPattern") { + patternErrorMsg = "`({a}) = 0` use `({a} = 0)`"; + } else if (maybePattern.type === "ArrayPattern") { + patternErrorMsg = "`([a]) = 0` use `([a] = 0)`"; + } -exports.assertEach = assertEach; -exports.assertOneOf = assertOneOf; -exports.assertNodeType = assertNodeType; -exports.assertNodeOrValueType = assertNodeOrValueType; -exports.assertValueType = assertValueType; -exports.chain = chain; -exports.default = defineType; + if (patternErrorMsg && (left.extra && left.extra.parenthesized || left.type === "ParenthesizedExpression")) { + this.raise(maybePattern.start, "You're trying to assign to a parenthesized expression, eg. instead of ".concat(patternErrorMsg)); + } -var _index = require("../index"); + this.next(); + node.right = this.parseMaybeAssign(noIn); + return this.finishNode(node, "AssignmentExpression"); + } else if (failOnShorthandAssign && refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); + } -var t = _interopRequireWildcard(_index); + return left; + } + }, { + key: "parseMaybeConditional", + value: function parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var potentialArrowAt = this.state.potentialArrowAt; + var expr = this.parseExprOps(noIn, refShorthandDefaultPos); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) { + return expr; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; + return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos); + } + }, { + key: "parseConditional", + value: function parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) { + if (this.eat(types.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types.colon); + node.alternate = this.parseMaybeAssign(noIn); + return this.finishNode(node, "ConditionalExpression"); + } -var VISITOR_KEYS = exports.VISITOR_KEYS = {}; -var ALIAS_KEYS = exports.ALIAS_KEYS = {}; -var NODE_FIELDS = exports.NODE_FIELDS = {}; -var BUILDER_KEYS = exports.BUILDER_KEYS = {}; -var DEPRECATED_KEYS = exports.DEPRECATED_KEYS = {}; + return expr; + } + }, { + key: "parseExprOps", + value: function parseExprOps(noIn, refShorthandDefaultPos) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var potentialArrowAt = this.state.potentialArrowAt; + var expr = this.parseMaybeUnary(refShorthandDefaultPos); -function getType(val) { - if (Array.isArray(val)) { - return "array"; - } else if (val === null) { - return "null"; - } else if (val === undefined) { - return "undefined"; - } else { - return typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val); - } -} + if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) { + return expr; + } -function assertEach(callback) { - function validator(node, key, val) { - if (!Array.isArray(val)) return; + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + return expr; + } - for (var i = 0; i < val.length; i++) { - callback(node, key + "[" + i + "]", val[i]); + return this.parseExprOp(expr, startPos, startLoc, -1, noIn); } - } - validator.each = callback; - return validator; -} + }, { + key: "parseExprOp", + value: function parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) { + var prec = this.state.type.binop; -function assertOneOf() { - for (var _len = arguments.length, vals = Array(_len), _key = 0; _key < _len; _key++) { - vals[_key] = arguments[_key]; - } + if (prec != null && (!noIn || !this.match(types._in))) { + if (prec > minPrec) { + var operator = this.state.value; - function validate(node, key, val) { - if (vals.indexOf(val) < 0) { - throw new TypeError("Property " + key + " expected value to be one of " + (0, _stringify2.default)(vals) + " but got " + (0, _stringify2.default)(val)); - } - } + if (operator === "|>" && this.state.inFSharpPipelineDirectBody) { + return left; + } - validate.oneOf = vals; + var node = this.startNodeAt(leftStartPos, leftStartLoc); + node.left = left; + node.operator = operator; - return validate; -} + if (operator === "**" && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) { + this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses."); + } -function assertNodeType() { - for (var _len2 = arguments.length, types = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - types[_key2] = arguments[_key2]; - } + var op = this.state.type; - function validate(node, key, val) { - var valid = false; + if (op === types.pipeline) { + this.expectPlugin("pipelineOperator"); + this.state.inPipeline = true; + this.checkPipelineAtInfixOperator(left, leftStartPos); + } else if (op === types.nullishCoalescing) { + this.expectPlugin("nullishCoalescingOperator"); + } - for (var _iterator = types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + this.next(); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") { + if (this.match(types.name) && this.state.value === "await" && this.scope.inAsync) { + throw this.raise(this.state.start, "Unexpected \"await\" after pipeline body; await must have parentheses in minimal proposal"); + } + } - var type = _ref; + node.right = this.parseExprOpRightExpr(op, prec, noIn); - if (t.is(type, val)) { - valid = true; - break; + if (op === types.nullishCoalescing) { + if (left.type === "LogicalExpression" && left.operator !== "??" && !(left.extra && left.extra.parenthesized)) { + throw this.raise(left.start, "Nullish coalescing operator(??) requires parens when mixing with logical operators"); + } else if (node.right.type === "LogicalExpression" && node.right.operator !== "??" && !(node.right.extra && node.right.extra.parenthesized)) { + throw this.raise(node.right.start, "Nullish coalescing operator(??) requires parens when mixing with logical operators"); + } + } + + this.finishNode(node, op === types.logicalOR || op === types.logicalAND || op === types.nullishCoalescing ? "LogicalExpression" : "BinaryExpression"); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); + } } + + return left; } + }, { + key: "parseExprOpRightExpr", + value: function parseExprOpRightExpr(op, prec, noIn) { + var _this36 = this; - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); + var startPos = this.state.start; + var startLoc = this.state.startLoc; + + switch (op) { + case types.pipeline: + switch (this.getPluginOption("pipelineOperator", "proposal")) { + case "smart": + return this.withTopicPermittingContext(function () { + return _this36.parseSmartPipelineBody(_this36.parseExprOpBaseRightExpr(op, prec, noIn), startPos, startLoc); + }); + + case "fsharp": + return this.withSoloAwaitPermittingContext(function () { + return _this36.parseFSharpPipelineBody(prec, noIn); + }); + } + + default: + return this.parseExprOpBaseRightExpr(op, prec, noIn); + } } - } + }, { + key: "parseExprOpBaseRightExpr", + value: function parseExprOpBaseRightExpr(op, prec, noIn) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn); + } + }, { + key: "parseMaybeUnary", + value: function parseMaybeUnary(refShorthandDefaultPos) { + if (this.isContextual("await") && this.isAwaitAllowed()) { + return this.parseAwait(); + } else if (this.state.type.prefix) { + var node = this.startNode(); + var update = this.match(types.incDec); + node.operator = this.state.value; + node.prefix = true; - validate.oneOfNodeTypes = types; + if (node.operator === "throw") { + this.expectPlugin("throwExpressions"); + } - return validate; -} + this.next(); + node.argument = this.parseMaybeUnary(); -function assertNodeOrValueType() { - for (var _len3 = arguments.length, types = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - types[_key3] = arguments[_key3]; - } + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); + } - function validate(node, key, val) { - var valid = false; + if (update) { + this.checkLVal(node.argument, undefined, undefined, "prefix operation"); + } else if (this.state.strict && node.operator === "delete") { + var arg = node.argument; - for (var _iterator2 = types, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + if (arg.type === "Identifier") { + this.raise(node.start, "Deleting local variable in strict mode"); + } else if (arg.type === "MemberExpression" && arg.property.type === "PrivateName") { + this.raise(node.start, "Deleting a private field is not allowed"); + } + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } - var type = _ref2; + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var expr = this.parseExprSubscripts(refShorthandDefaultPos); + if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; + + while (this.state.type.postfix && !this.canInsertSemicolon()) { + var _node9 = this.startNodeAt(startPos, startLoc); - if (getType(val) === type || t.is(type, val)) { - valid = true; - break; + _node9.operator = this.state.value; + _node9.prefix = false; + _node9.argument = expr; + this.checkLVal(expr, undefined, undefined, "postfix operation"); + this.next(); + expr = this.finishNode(_node9, "UpdateExpression"); } - } - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); + return expr; } - } + }, { + key: "parseExprSubscripts", + value: function parseExprSubscripts(refShorthandDefaultPos) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var potentialArrowAt = this.state.potentialArrowAt; + var expr = this.parseExprAtom(refShorthandDefaultPos); - validate.oneOfNodeOrValueTypes = types; + if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) { + return expr; + } - return validate; -} + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + return expr; + } -function assertValueType(type) { - function validate(node, key, val) { - var valid = getType(val) === type; + return this.parseSubscripts(expr, startPos, startLoc); + } + }, { + key: "parseSubscripts", + value: function parseSubscripts(base, startPos, startLoc, noCalls) { + var state = { + optionalChainMember: false, + maybeAsyncArrow: this.atPossibleAsync(base), + stop: false + }; - if (!valid) { - throw new TypeError("Property " + key + " expected type of " + type + " but got " + getType(val)); + do { + base = this.parseSubscript(base, startPos, startLoc, noCalls, state); + state.maybeAsyncArrow = false; + } while (!state.stop); + + return base; } - } + }, { + key: "parseSubscript", + value: function parseSubscript(base, startPos, startLoc, noCalls, state) { + if (!noCalls && this.eat(types.doubleColon)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + node.callee = this.parseNoCallExpr(); + state.stop = true; + return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls); + } else if (this.match(types.questionDot)) { + this.expectPlugin("optionalChaining"); + state.optionalChainMember = true; + + if (noCalls && this.lookaheadCharCode() === 40) { + state.stop = true; + return base; + } - validate.type = type; + this.next(); - return validate; -} + var _node10 = this.startNodeAt(startPos, startLoc); + + if (this.eat(types.bracketL)) { + _node10.object = base; + _node10.property = this.parseExpression(); + _node10.computed = true; + _node10.optional = true; + this.expect(types.bracketR); + return this.finishNode(_node10, "OptionalMemberExpression"); + } else if (this.eat(types.parenL)) { + _node10.callee = base; + _node10.arguments = this.parseCallExpressionArguments(types.parenR, false); + _node10.optional = true; + return this.finishCallExpression(_node10, true); + } else { + _node10.object = base; + _node10.property = this.parseIdentifier(true); + _node10.computed = false; + _node10.optional = true; + return this.finishNode(_node10, "OptionalMemberExpression"); + } + } else if (this.eat(types.dot)) { + var _node11 = this.startNodeAt(startPos, startLoc); -function chain() { - for (var _len4 = arguments.length, fns = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - fns[_key4] = arguments[_key4]; - } + _node11.object = base; + _node11.property = this.parseMaybePrivateName(); + _node11.computed = false; - function validate() { - for (var _iterator3 = fns, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + if (_node11.property.type === "PrivateName" && _node11.object.type === "Super") { + this.raise(startPos, "Private fields can't be accessed on super"); + } + + if (state.optionalChainMember) { + _node11.optional = false; + return this.finishNode(_node11, "OptionalMemberExpression"); + } + + return this.finishNode(_node11, "MemberExpression"); + } else if (this.eat(types.bracketL)) { + var _node12 = this.startNodeAt(startPos, startLoc); + + _node12.object = base; + _node12.property = this.parseExpression(); + _node12.computed = true; + this.expect(types.bracketR); - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; + if (state.optionalChainMember) { + _node12.optional = false; + return this.finishNode(_node12, "OptionalMemberExpression"); + } + + return this.finishNode(_node12, "MemberExpression"); + } else if (!noCalls && this.match(types.parenL)) { + var oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + var oldYieldPos = this.state.yieldPos; + var oldAwaitPos = this.state.awaitPos; + this.state.maybeInArrowParameters = true; + this.state.yieldPos = -1; + this.state.awaitPos = -1; + this.next(); + + var _node13 = this.startNodeAt(startPos, startLoc); + + _node13.callee = base; + _node13.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", _node13); + this.finishCallExpression(_node13, state.optionalChainMember); + + if (state.maybeAsyncArrow && this.shouldParseAsyncArrow()) { + state.stop = true; + _node13 = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), _node13); + this.checkYieldAwaitInDefaultParams(); + this.state.yieldPos = oldYieldPos; + this.state.awaitPos = oldAwaitPos; + } else { + this.toReferencedListDeep(_node13.arguments); + if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos; + + if (!this.isAwaitAllowed() && !oldMaybeInArrowParameters || oldAwaitPos !== -1) { + this.state.awaitPos = oldAwaitPos; + } + } + + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return _node13; + } else if (this.match(types.backQuote)) { + return this.parseTaggedTemplateExpression(startPos, startLoc, base, state); } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; + state.stop = true; + return base; } + } + }, { + key: "parseTaggedTemplateExpression", + value: function parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments) { + var node = this.startNodeAt(startPos, startLoc); + node.tag = base; + node.quasi = this.parseTemplate(true); + if (typeArguments) node.typeParameters = typeArguments; - var fn = _ref3; + if (state.optionalChainMember) { + this.raise(startPos, "Tagged Template Literals are not allowed in optionalChain"); + } - fn.apply(undefined, arguments); + return this.finishNode(node, "TaggedTemplateExpression"); } - } - validate.chainOf = fns; - return validate; -} + }, { + key: "atPossibleAsync", + value: function atPossibleAsync(base) { + return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"; + } + }, { + key: "finishCallExpression", + value: function finishCallExpression(node, optional) { + if (node.callee.type === "Import") { + if (node.arguments.length !== 1) { + this.raise(node.start, "import() requires exactly one argument"); + } else { + var importArg = node.arguments[0]; -function defineType(type) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (importArg && importArg.type === "SpreadElement") { + this.raise(importArg.start, "... is not allowed in import()"); + } + } + } - var inherits = opts.inherits && store[opts.inherits] || {}; + return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); + } + }, { + key: "parseCallExpressionArguments", + value: function parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) { + var elts = []; + var innerParenStart; + var first = true; + var oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; - opts.fields = opts.fields || inherits.fields || {}; - opts.visitor = opts.visitor || inherits.visitor || []; - opts.aliases = opts.aliases || inherits.aliases || []; - opts.builder = opts.builder || inherits.builder || opts.visitor || []; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(types.comma); - if (opts.deprecatedAlias) { - DEPRECATED_KEYS[opts.deprecatedAlias] = type; - } + if (this.match(close)) { + if (dynamicImport) { + this.raise(this.state.lastTokStart, "Trailing comma is disallowed inside import(...) arguments"); + } - for (var _iterator4 = opts.visitor.concat(opts.builder), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; + if (nodeForExtra) { + this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart); + } - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } + this.next(); + break; + } + } - var _key5 = _ref4; + if (this.match(types.parenL) && !innerParenStart) { + innerParenStart = this.state.start; + } - opts.fields[_key5] = opts.fields[_key5] || {}; - } + elts.push(this.parseExprListItem(false, possibleAsyncArrow ? { + start: 0 + } : undefined, possibleAsyncArrow ? { + start: 0 + } : undefined, allowPlaceholder)); + } - for (var key in opts.fields) { - var field = opts.fields[key]; + if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) { + this.unexpected(); + } - if (opts.builder.indexOf(key) === -1) { - field.optional = true; + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return elts; } - if (field.default === undefined) { - field.default = null; - } else if (!field.validate) { - field.validate = assertValueType(getType(field.default)); + }, { + key: "shouldParseAsyncArrow", + value: function shouldParseAsyncArrow() { + return this.match(types.arrow) && !this.canInsertSemicolon(); } - } + }, { + key: "parseAsyncArrowFromCallExpression", + value: function parseAsyncArrowFromCallExpression(node, call) { + var _call$extra; - VISITOR_KEYS[type] = opts.visitor; - BUILDER_KEYS[type] = opts.builder; - NODE_FIELDS[type] = opts.fields; - ALIAS_KEYS[type] = opts.aliases; + this.expect(types.arrow); + this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) === null || _call$extra === void 0 ? void 0 : _call$extra.trailingComma); + return node; + } + }, { + key: "parseNoCallExpr", + value: function parseNoCallExpr() { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); + } + }, { + key: "parseExprAtom", + value: function parseExprAtom(refShorthandDefaultPos) { + if (this.state.type === types.slash) this.readRegexp(); + var canBeArrow = this.state.potentialArrowAt === this.state.start; + var node; - store[type] = opts; -} + switch (this.state.type) { + case types._super: + node = this.startNode(); + this.next(); -var store = {}; -},{"../index":151,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/helpers/typeof":113}],147:[function(require,module,exports){ -"use strict"; + if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { + this.raise(node.start, "super() is only valid inside a class constructor of a subclass. " + "Maybe a typo in the method name ('constructor') or not extending another class?"); + } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { + this.raise(node.start, "super is only allowed in object methods and classes"); + } -require("./index"); + if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) { + this.raise(node.start, "super can only be used with function calls (i.e. super()) or " + "in property accesses (i.e. super.prop or super[prop])"); + } -require("./core"); + return this.finishNode(node, "Super"); -require("./es2015"); + case types._import: + node = this.startNode(); + this.next(); -require("./flow"); + if (this.match(types.dot)) { + return this.parseImportMetaProperty(node); + } -require("./jsx"); + this.expectPlugin("dynamicImport", node.start); -require("./misc"); + if (!this.match(types.parenL)) { + this.unexpected(null, types.parenL); + } -require("./experimental"); -},{"./core":142,"./es2015":143,"./experimental":144,"./flow":145,"./index":146,"./jsx":148,"./misc":149}],148:[function(require,module,exports){ -"use strict"; + return this.finishNode(node, "Import"); -var _index = require("./index"); + case types._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + + case types.name: + { + node = this.startNode(); + var containsEsc = this.state.containsEsc; + var id = this.parseIdentifier(); + + if (!containsEsc && id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) { + this.next(); + return this.parseFunction(node, undefined, true); + } else if (canBeArrow && !containsEsc && id.name === "async" && this.match(types.name) && !this.canInsertSemicolon()) { + var params = [this.parseIdentifier()]; + this.expect(types.arrow); + this.parseArrowExpression(node, params, true); + return node; + } -var _index2 = _interopRequireDefault(_index); + if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) { + this.next(); + this.parseArrowExpression(node, [id], false); + return node; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return id; + } -(0, _index2.default)("JSXAttribute", { - visitor: ["name", "value"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXNamespacedName") - }, - value: { - optional: true, - validate: (0, _index.assertNodeType)("JSXElement", "StringLiteral", "JSXExpressionContainer") - } - } -}); + case types._do: + { + this.expectPlugin("doExpressions"); -(0, _index2.default)("JSXClosingElement", { - visitor: ["name"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - } - } -}); + var _node14 = this.startNode(); -(0, _index2.default)("JSXElement", { - builder: ["openingElement", "closingElement", "children", "selfClosing"], - visitor: ["openingElement", "children", "closingElement"], - aliases: ["JSX", "Immutable", "Expression"], - fields: { - openingElement: { - validate: (0, _index.assertNodeType)("JSXOpeningElement") - }, - closingElement: { - optional: true, - validate: (0, _index.assertNodeType)("JSXClosingElement") - }, - children: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement"))) - } - } -}); + this.next(); + var oldLabels = this.state.labels; + this.state.labels = []; + _node14.body = this.parseBlock(); + this.state.labels = oldLabels; + return this.finishNode(_node14, "DoExpression"); + } -(0, _index2.default)("JSXEmptyExpression", { - aliases: ["JSX", "Expression"] -}); + case types.regexp: + { + var value = this.state.value; + node = this.parseLiteral(value.value, "RegExpLiteral"); + node.pattern = value.pattern; + node.flags = value.flags; + return node; + } -(0, _index2.default)("JSXExpressionContainer", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + case types.num: + return this.parseLiteral(this.state.value, "NumericLiteral"); -(0, _index2.default)("JSXSpreadChild", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + case types.bigint: + return this.parseLiteral(this.state.value, "BigIntLiteral"); -(0, _index2.default)("JSXIdentifier", { - builder: ["name"], - aliases: ["JSX", "Expression"], - fields: { - name: { - validate: (0, _index.assertValueType)("string") - } - } -}); + case types.string: + return this.parseLiteral(this.state.value, "StringLiteral"); -(0, _index2.default)("JSXMemberExpression", { - visitor: ["object", "property"], - aliases: ["JSX", "Expression"], - fields: { - object: { - validate: (0, _index.assertNodeType)("JSXMemberExpression", "JSXIdentifier") - }, - property: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - } - } -}); + case types._null: + node = this.startNode(); + this.next(); + return this.finishNode(node, "NullLiteral"); -(0, _index2.default)("JSXNamespacedName", { - visitor: ["namespace", "name"], - aliases: ["JSX"], - fields: { - namespace: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - }, - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - } - } -}); + case types._true: + case types._false: + return this.parseBooleanLiteral(); -(0, _index2.default)("JSXOpeningElement", { - builder: ["name", "attributes", "selfClosing"], - visitor: ["name", "attributes"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - }, - selfClosing: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - attributes: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXAttribute", "JSXSpreadAttribute"))) - } - } -}); + case types.parenL: + return this.parseParenAndDistinguishExpression(canBeArrow); -(0, _index2.default)("JSXSpreadAttribute", { - visitor: ["argument"], - aliases: ["JSX"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + case types.bracketL: + { + var oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types.bracketR, true, refShorthandDefaultPos, node); -(0, _index2.default)("JSXText", { - aliases: ["JSX", "Immutable"], - builder: ["value"], - fields: { - value: { - validate: (0, _index.assertValueType)("string") - } - } -}); -},{"./index":146}],149:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); + if (!this.state.maybeInArrowParameters) { + this.toReferencedList(node.elements); + } -var _index2 = _interopRequireDefault(_index); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return this.finishNode(node, "ArrayExpression"); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case types.braceL: + { + var _oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + var ret = this.parseObj(false, refShorthandDefaultPos); + this.state.inFSharpPipelineDirectBody = _oldInFSharpPipelineDirectBody; + return ret; + } -(0, _index2.default)("Noop", { - visitor: [] -}); + case types._function: + return this.parseFunctionExpression(); -(0, _index2.default)("ParenthesizedExpression", { - visitor: ["expression"], - aliases: ["Expression", "ExpressionWrapper"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":146}],150:[function(require,module,exports){ -"use strict"; + case types.at: + this.parseDecorators(); -exports.__esModule = true; -exports.createUnionTypeAnnotation = createUnionTypeAnnotation; -exports.removeTypeDuplicates = removeTypeDuplicates; -exports.createTypeAnnotationBasedOnTypeof = createTypeAnnotationBasedOnTypeof; + case types._class: + node = this.startNode(); + this.takeDecorators(node); + return this.parseClass(node, false); -var _index = require("./index"); + case types._new: + return this.parseNew(); -var t = _interopRequireWildcard(_index); + case types.backQuote: + return this.parseTemplate(false); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + case types.doubleColon: + { + node = this.startNode(); + this.next(); + node.object = null; + var callee = node.callee = this.parseNoCallExpr(); -function createUnionTypeAnnotation(types) { - var flattened = removeTypeDuplicates(types); + if (callee.type === "MemberExpression") { + return this.finishNode(node, "BindExpression"); + } else { + throw this.raise(callee.start, "Binding should be performed on object property."); + } + } - if (flattened.length === 1) { - return flattened[0]; - } else { - return t.unionTypeAnnotation(flattened); - } -} + case types.hash: + { + if (this.state.inPipeline) { + node = this.startNode(); -function removeTypeDuplicates(nodes) { - var generics = {}; - var bases = {}; + if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") { + this.raise(node.start, "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option."); + } - var typeGroups = []; + this.next(); - var types = []; + if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) { + this.raise(node.start, "Topic reference was used in a lexical context without topic binding"); + } - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (!node) continue; + this.registerTopicReference(); + return this.finishNode(node, "PipelinePrimaryTopicReference"); + } + } - if (types.indexOf(node) >= 0) { - continue; + default: + throw this.unexpected(); + } } - - if (t.isAnyTypeAnnotation(node)) { - return [node]; + }, { + key: "parseBooleanLiteral", + value: function parseBooleanLiteral() { + var node = this.startNode(); + node.value = this.match(types._true); + this.next(); + return this.finishNode(node, "BooleanLiteral"); } + }, { + key: "parseMaybePrivateName", + value: function parseMaybePrivateName() { + var isPrivate = this.match(types.hash); - if (t.isFlowBaseAnnotation(node)) { - bases[node.type] = node; - continue; + if (isPrivate) { + this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]); + var node = this.startNode(); + this.next(); + this.assertNoSpace("Unexpected space between # and identifier"); + node.id = this.parseIdentifier(true); + return this.finishNode(node, "PrivateName"); + } else { + return this.parseIdentifier(true); + } } + }, { + key: "parseFunctionExpression", + value: function parseFunctionExpression() { + var node = this.startNode(); + var meta = this.startNode(); + this.next(); + meta = this.createIdentifier(meta, "function"); - if (t.isUnionTypeAnnotation(node)) { - if (typeGroups.indexOf(node.types) < 0) { - nodes = nodes.concat(node.types); - typeGroups.push(node.types); + if (this.scope.inGenerator && this.eat(types.dot)) { + return this.parseMetaProperty(node, meta, "sent"); } - continue; - } - if (t.isGenericTypeAnnotation(node)) { - var name = node.id.name; + return this.parseFunction(node); + } + }, { + key: "parseMetaProperty", + value: function parseMetaProperty(node, meta, propertyName) { + node.meta = meta; - if (generics[name]) { - var existing = generics[name]; - if (existing.typeParameters) { - if (node.typeParameters) { - existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); - } - } else { - existing = node.typeParameters; + if (meta.name === "function" && propertyName === "sent") { + if (this.isContextual(propertyName)) { + this.expectPlugin("functionSent"); + } else if (!this.hasPlugin("functionSent")) { + this.unexpected(); } - } else { - generics[name] = node; } - continue; - } + var containsEsc = this.state.containsEsc; + node.property = this.parseIdentifier(true); - types.push(node); - } + if (node.property.name !== propertyName || containsEsc) { + this.raise(node.property.start, "The only valid meta property for ".concat(meta.name, " is ").concat(meta.name, ".").concat(propertyName)); + } - for (var type in bases) { - types.push(bases[type]); - } + return this.finishNode(node, "MetaProperty"); + } + }, { + key: "parseImportMetaProperty", + value: function parseImportMetaProperty(node) { + var id = this.createIdentifier(this.startNodeAtNode(node), "import"); + this.expect(types.dot); - for (var _name in generics) { - types.push(generics[_name]); - } + if (this.isContextual("meta")) { + this.expectPlugin("importMeta"); - return types; -} + if (!this.inModule) { + this.raise(id.start, "import.meta may appear only with 'sourceType: \"module\"'", { + code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" + }); + } -function createTypeAnnotationBasedOnTypeof(type) { - if (type === "string") { - return t.stringTypeAnnotation(); - } else if (type === "number") { - return t.numberTypeAnnotation(); - } else if (type === "undefined") { - return t.voidTypeAnnotation(); - } else if (type === "boolean") { - return t.booleanTypeAnnotation(); - } else if (type === "function") { - return t.genericTypeAnnotation(t.identifier("Function")); - } else if (type === "object") { - return t.genericTypeAnnotation(t.identifier("Object")); - } else if (type === "symbol") { - return t.genericTypeAnnotation(t.identifier("Symbol")); - } else { - throw new Error("Invalid typeof value"); - } -} -},{"./index":151}],151:[function(require,module,exports){ -"use strict"; + this.sawUnambiguousESM = true; + } else if (!this.hasPlugin("importMeta")) { + this.raise(id.start, "Dynamic imports require a parameter: import('a.js')"); + } -exports.__esModule = true; -exports.createTypeAnnotationBasedOnTypeof = exports.removeTypeDuplicates = exports.createUnionTypeAnnotation = exports.valueToNode = exports.toBlock = exports.toExpression = exports.toStatement = exports.toBindingIdentifierName = exports.toIdentifier = exports.toKeyAlias = exports.toSequenceExpression = exports.toComputedKey = exports.isNodesEquivalent = exports.isImmutable = exports.isScope = exports.isSpecifierDefault = exports.isVar = exports.isBlockScoped = exports.isLet = exports.isValidIdentifier = exports.isReferenced = exports.isBinding = exports.getOuterBindingIdentifiers = exports.getBindingIdentifiers = exports.TYPES = exports.react = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; + return this.parseMetaProperty(node, id, "meta"); + } + }, { + key: "parseLiteral", + value: function parseLiteral(value, type, startPos, startLoc) { + startPos = startPos || this.state.start; + startLoc = startLoc || this.state.startLoc; + var node = this.startNodeAt(startPos, startLoc); + this.addExtra(node, "rawValue", value); + this.addExtra(node, "raw", this.input.slice(startPos, this.state.end)); + node.value = value; + this.next(); + return this.finishNode(node, type); + } + }, { + key: "parseParenAndDistinguishExpression", + value: function parseParenAndDistinguishExpression(canBeArrow) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var val; + this.expect(types.parenL); + var oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + var oldYieldPos = this.state.yieldPos; + var oldAwaitPos = this.state.awaitPos; + var oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.maybeInArrowParameters = true; + this.state.yieldPos = -1; + this.state.awaitPos = -1; + this.state.inFSharpPipelineDirectBody = false; + var innerStartPos = this.state.start; + var innerStartLoc = this.state.startLoc; + var exprList = []; + var refShorthandDefaultPos = { + start: 0 + }; + var refNeedsArrowPos = { + start: 0 + }; + var first = true; + var spreadStart; + var optionalCommaStart; -var _getOwnPropertySymbols = require("babel-runtime/core-js/object/get-own-property-symbols"); + while (!this.match(types.parenR)) { + if (first) { + first = false; + } else { + this.expect(types.comma, refNeedsArrowPos.start || null); -var _getOwnPropertySymbols2 = _interopRequireDefault(_getOwnPropertySymbols); + if (this.match(types.parenR)) { + optionalCommaStart = this.state.start; + break; + } + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (this.match(types.ellipsis)) { + var spreadNodeStartPos = this.state.start; + var spreadNodeStartLoc = this.state.startLoc; + spreadStart = this.state.start; + exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc)); + this.checkCommaAfterRest(41); + break; + } else { + exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos)); + } + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + var innerEndPos = this.state.start; + var innerEndLoc = this.state.startLoc; + this.expect(types.parenR); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + var arrowNode = this.startNodeAt(startPos, startLoc); -var _keys = require("babel-runtime/core-js/object/keys"); + if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) { + this.checkYieldAwaitInDefaultParams(); + this.state.yieldPos = oldYieldPos; + this.state.awaitPos = oldAwaitPos; -var _keys2 = _interopRequireDefault(_keys); + for (var _i = 0; _i < exprList.length; _i++) { + var param = exprList[_i]; -var _stringify = require("babel-runtime/core-js/json/stringify"); + if (param.extra && param.extra.parenthesized) { + this.unexpected(param.extra.parenStart); + } + } -var _stringify2 = _interopRequireDefault(_stringify); + this.parseArrowExpression(arrowNode, exprList, false); + return arrowNode; + } -var _constants = require("./constants"); + if (oldYieldPos !== -1) this.state.yieldPos = oldYieldPos; + if (oldAwaitPos !== -1) this.state.awaitPos = oldAwaitPos; -Object.defineProperty(exports, "STATEMENT_OR_BLOCK_KEYS", { - enumerable: true, - get: function get() { - return _constants.STATEMENT_OR_BLOCK_KEYS; - } -}); -Object.defineProperty(exports, "FLATTENABLE_KEYS", { - enumerable: true, - get: function get() { - return _constants.FLATTENABLE_KEYS; - } -}); -Object.defineProperty(exports, "FOR_INIT_KEYS", { - enumerable: true, - get: function get() { - return _constants.FOR_INIT_KEYS; - } -}); -Object.defineProperty(exports, "COMMENT_KEYS", { - enumerable: true, - get: function get() { - return _constants.COMMENT_KEYS; - } -}); -Object.defineProperty(exports, "LOGICAL_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.LOGICAL_OPERATORS; - } -}); -Object.defineProperty(exports, "UPDATE_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.UPDATE_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_NUMBER_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_NUMBER_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "EQUALITY_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.EQUALITY_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "COMPARISON_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.COMPARISON_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "NUMBER_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.NUMBER_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "NUMBER_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.NUMBER_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "STRING_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.STRING_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "INHERIT_KEYS", { - enumerable: true, - get: function get() { - return _constants.INHERIT_KEYS; - } -}); -Object.defineProperty(exports, "BLOCK_SCOPED_SYMBOL", { - enumerable: true, - get: function get() { - return _constants.BLOCK_SCOPED_SYMBOL; - } -}); -Object.defineProperty(exports, "NOT_LOCAL_BINDING", { - enumerable: true, - get: function get() { - return _constants.NOT_LOCAL_BINDING; - } -}); -exports.is = is; -exports.isType = isType; -exports.validate = validate; -exports.shallowEqual = shallowEqual; -exports.appendToMemberExpression = appendToMemberExpression; -exports.prependToMemberExpression = prependToMemberExpression; -exports.ensureBlock = ensureBlock; -exports.clone = clone; -exports.cloneWithoutLoc = cloneWithoutLoc; -exports.cloneDeep = cloneDeep; -exports.buildMatchMemberExpression = buildMatchMemberExpression; -exports.removeComments = removeComments; -exports.inheritsComments = inheritsComments; -exports.inheritTrailingComments = inheritTrailingComments; -exports.inheritLeadingComments = inheritLeadingComments; -exports.inheritInnerComments = inheritInnerComments; -exports.inherits = inherits; -exports.assertNode = assertNode; -exports.isNode = isNode; -exports.traverseFast = traverseFast; -exports.removeProperties = removeProperties; -exports.removePropertiesDeep = removePropertiesDeep; - -var _retrievers = require("./retrievers"); + if (!exprList.length) { + this.unexpected(this.state.lastTokStart); + } -Object.defineProperty(exports, "getBindingIdentifiers", { - enumerable: true, - get: function get() { - return _retrievers.getBindingIdentifiers; - } -}); -Object.defineProperty(exports, "getOuterBindingIdentifiers", { - enumerable: true, - get: function get() { - return _retrievers.getOuterBindingIdentifiers; - } -}); + if (optionalCommaStart) this.unexpected(optionalCommaStart); + if (spreadStart) this.unexpected(spreadStart); -var _validators = require("./validators"); + if (refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); + } -Object.defineProperty(exports, "isBinding", { - enumerable: true, - get: function get() { - return _validators.isBinding; - } -}); -Object.defineProperty(exports, "isReferenced", { - enumerable: true, - get: function get() { - return _validators.isReferenced; - } -}); -Object.defineProperty(exports, "isValidIdentifier", { - enumerable: true, - get: function get() { - return _validators.isValidIdentifier; - } -}); -Object.defineProperty(exports, "isLet", { - enumerable: true, - get: function get() { - return _validators.isLet; - } -}); -Object.defineProperty(exports, "isBlockScoped", { - enumerable: true, - get: function get() { - return _validators.isBlockScoped; - } -}); -Object.defineProperty(exports, "isVar", { - enumerable: true, - get: function get() { - return _validators.isVar; - } -}); -Object.defineProperty(exports, "isSpecifierDefault", { - enumerable: true, - get: function get() { - return _validators.isSpecifierDefault; - } -}); -Object.defineProperty(exports, "isScope", { - enumerable: true, - get: function get() { - return _validators.isScope; - } -}); -Object.defineProperty(exports, "isImmutable", { - enumerable: true, - get: function get() { - return _validators.isImmutable; - } -}); -Object.defineProperty(exports, "isNodesEquivalent", { - enumerable: true, - get: function get() { - return _validators.isNodesEquivalent; - } -}); + if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start); + this.toReferencedListDeep(exprList, true); -var _converters = require("./converters"); + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } -Object.defineProperty(exports, "toComputedKey", { - enumerable: true, - get: function get() { - return _converters.toComputedKey; - } -}); -Object.defineProperty(exports, "toSequenceExpression", { - enumerable: true, - get: function get() { - return _converters.toSequenceExpression; - } -}); -Object.defineProperty(exports, "toKeyAlias", { - enumerable: true, - get: function get() { - return _converters.toKeyAlias; - } -}); -Object.defineProperty(exports, "toIdentifier", { - enumerable: true, - get: function get() { - return _converters.toIdentifier; - } -}); -Object.defineProperty(exports, "toBindingIdentifierName", { - enumerable: true, - get: function get() { - return _converters.toBindingIdentifierName; - } -}); -Object.defineProperty(exports, "toStatement", { - enumerable: true, - get: function get() { - return _converters.toStatement; - } -}); -Object.defineProperty(exports, "toExpression", { - enumerable: true, - get: function get() { - return _converters.toExpression; - } -}); -Object.defineProperty(exports, "toBlock", { - enumerable: true, - get: function get() { - return _converters.toBlock; - } -}); -Object.defineProperty(exports, "valueToNode", { - enumerable: true, - get: function get() { - return _converters.valueToNode; - } -}); + if (!this.options.createParenthesizedExpressions) { + this.addExtra(val, "parenthesized", true); + this.addExtra(val, "parenStart", startPos); + return val; + } -var _flow = require("./flow"); + var parenExpression = this.startNodeAt(startPos, startLoc); + parenExpression.expression = val; + this.finishNode(parenExpression, "ParenthesizedExpression"); + return parenExpression; + } + }, { + key: "shouldParseArrow", + value: function shouldParseArrow() { + return !this.canInsertSemicolon(); + } + }, { + key: "parseArrow", + value: function parseArrow(node) { + if (this.eat(types.arrow)) { + return node; + } + } + }, { + key: "parseParenItem", + value: function parseParenItem(node, startPos, startLoc) { + return node; + } + }, { + key: "parseNew", + value: function parseNew() { + var node = this.startNode(); + var meta = this.startNode(); + this.next(); + meta = this.createIdentifier(meta, "new"); -Object.defineProperty(exports, "createUnionTypeAnnotation", { - enumerable: true, - get: function get() { - return _flow.createUnionTypeAnnotation; - } -}); -Object.defineProperty(exports, "removeTypeDuplicates", { - enumerable: true, - get: function get() { - return _flow.removeTypeDuplicates; - } -}); -Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { - enumerable: true, - get: function get() { - return _flow.createTypeAnnotationBasedOnTypeof; - } -}); + if (this.eat(types.dot)) { + var metaProp = this.parseMetaProperty(node, meta, "target"); -var _toFastProperties = require("to-fast-properties"); + if (!this.scope.inNonArrowFunction && !this.state.inClassProperty) { + var error = "new.target can only be used in functions"; -var _toFastProperties2 = _interopRequireDefault(_toFastProperties); + if (this.hasPlugin("classProperties")) { + error += " or class properties"; + } -var _clone = require("lodash/clone"); + this.raise(metaProp.start, error); + } -var _clone2 = _interopRequireDefault(_clone); + return metaProp; + } -var _uniq = require("lodash/uniq"); + node.callee = this.parseNoCallExpr(); -var _uniq2 = _interopRequireDefault(_uniq); + if (node.callee.type === "Import") { + this.raise(node.callee.start, "Cannot use new with import(...)"); + } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") { + this.raise(this.state.lastTokEnd, "constructors in/after an Optional Chain are not allowed"); + } else if (this.eat(types.questionDot)) { + this.raise(this.state.start, "constructors in/after an Optional Chain are not allowed"); + } -require("./definitions/init"); + this.parseNewArguments(node); + return this.finishNode(node, "NewExpression"); + } + }, { + key: "parseNewArguments", + value: function parseNewArguments(node) { + if (this.eat(types.parenL)) { + var args = this.parseExprList(types.parenR); + this.toReferencedList(args); + node.arguments = args; + } else { + node.arguments = []; + } + } + }, { + key: "parseTemplateElement", + value: function parseTemplateElement(isTagged) { + var elem = this.startNode(); -var _definitions = require("./definitions"); + if (this.state.value === null) { + if (!isTagged) { + this.raise(this.state.invalidTemplateEscapePosition || 0, "Invalid escape sequence in template"); + } else { + this.state.invalidTemplateEscapePosition = null; + } + } -var _react2 = require("./react"); + elem.value = { + raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"), + cooked: this.state.value + }; + this.next(); + elem.tail = this.match(types.backQuote); + return this.finishNode(elem, "TemplateElement"); + } + }, { + key: "parseTemplate", + value: function parseTemplate(isTagged) { + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement(isTagged); + node.quasis = [curElt]; -var _react = _interopRequireWildcard(_react2); + while (!curElt.tail) { + this.expect(types.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types.braceR); + node.quasis.push(curElt = this.parseTemplateElement(isTagged)); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + this.next(); + return this.finishNode(node, "TemplateLiteral"); + } + }, { + key: "parseObj", + value: function parseObj(isPattern, refShorthandDefaultPos) { + var propHash = Object.create(null); + var first = true; + var node = this.startNode(); + node.properties = []; + this.next(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + while (!this.eat(types.braceR)) { + if (first) { + first = false; + } else { + this.expect(types.comma); -var t = exports; + if (this.match(types.braceR)) { + this.addExtra(node, "trailingComma", this.state.lastTokStart); + this.next(); + break; + } + } -function registerType(type) { - var is = t["is" + type]; - if (!is) { - is = t["is" + type] = function (node, opts) { - return t.is(type, node, opts); - }; - } + var prop = this.parseObjectMember(isPattern, refShorthandDefaultPos); + if (!isPattern) this.checkDuplicatedProto(prop, propHash); - t["assert" + type] = function (node, opts) { - opts = opts || {}; - if (!is(node, opts)) { - throw new Error("Expected type " + (0, _stringify2.default)(type) + " with option " + (0, _stringify2.default)(opts)); - } - }; -} + if (prop.shorthand) { + this.addExtra(prop, "shorthand", true); + } -exports.VISITOR_KEYS = _definitions.VISITOR_KEYS; -exports.ALIAS_KEYS = _definitions.ALIAS_KEYS; -exports.NODE_FIELDS = _definitions.NODE_FIELDS; -exports.BUILDER_KEYS = _definitions.BUILDER_KEYS; -exports.DEPRECATED_KEYS = _definitions.DEPRECATED_KEYS; -exports.react = _react; + node.properties.push(prop); + } + if (!this.match(types.eq) && propHash.start !== undefined) { + this.raise(propHash.start, "Redefinition of __proto__ property"); + } -for (var type in t.VISITOR_KEYS) { - registerType(type); -} + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); + } + }, { + key: "isAsyncProp", + value: function isAsyncProp(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.match(types.name) || this.match(types.num) || this.match(types.string) || this.match(types.bracketL) || this.state.type.keyword || this.match(types.star)) && !this.hasPrecedingLineBreak(); + } + }, { + key: "parseObjectMember", + value: function parseObjectMember(isPattern, refShorthandDefaultPos) { + var decorators = []; -t.FLIPPED_ALIAS_KEYS = {}; + if (this.match(types.at)) { + if (this.hasPlugin("decorators")) { + this.raise(this.state.start, "Stage 2 decorators disallow object literal property decorators"); + } -(0, _keys2.default)(t.ALIAS_KEYS).forEach(function (type) { - t.ALIAS_KEYS[type].forEach(function (alias) { - var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; - types.push(type); - }); -}); + while (this.match(types.at)) { + decorators.push(this.parseDecorator()); + } + } -(0, _keys2.default)(t.FLIPPED_ALIAS_KEYS).forEach(function (type) { - t[type.toUpperCase() + "_TYPES"] = t.FLIPPED_ALIAS_KEYS[type]; - registerType(type); -}); + var prop = this.startNode(); + var isGenerator = false; + var isAsync = false; + var startPos; + var startLoc; -var TYPES = exports.TYPES = (0, _keys2.default)(t.VISITOR_KEYS).concat((0, _keys2.default)(t.FLIPPED_ALIAS_KEYS)).concat((0, _keys2.default)(t.DEPRECATED_KEYS)); + if (this.match(types.ellipsis)) { + if (decorators.length) this.unexpected(); -function is(type, node, opts) { - if (!node) return false; + if (isPattern) { + this.next(); + prop.argument = this.parseIdentifier(); + this.checkCommaAfterRest(125); + return this.finishNode(prop, "RestElement"); + } - var matches = isType(node.type, type); - if (!matches) return false; + return this.parseSpread(); + } - if (typeof opts === "undefined") { - return true; - } else { - return t.shallowEqual(node, opts); - } -} + if (decorators.length) { + prop.decorators = decorators; + decorators = []; + } -function isType(nodeType, targetType) { - if (nodeType === targetType) return true; + prop.method = false; - if (t.ALIAS_KEYS[targetType]) return false; + if (isPattern || refShorthandDefaultPos) { + startPos = this.state.start; + startLoc = this.state.startLoc; + } - var aliases = t.FLIPPED_ALIAS_KEYS[targetType]; - if (aliases) { - if (aliases[0] === nodeType) return true; + if (!isPattern) { + isGenerator = this.eat(types.star); + } - for (var _iterator = aliases, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + var containsEsc = this.state.containsEsc; + this.parsePropertyName(prop); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; + if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.eat(types.star); + this.parsePropertyName(prop); } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + isAsync = false; } - var alias = _ref; - - if (nodeType === alias) return true; + this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc); + return prop; } - } + }, { + key: "isGetterOrSetterMethod", + value: function isGetterOrSetterMethod(prop, isPattern) { + return !isPattern && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.match(types.string) || this.match(types.num) || this.match(types.bracketL) || this.match(types.name) || !!this.state.type.keyword); + } + }, { + key: "getGetterSetterExpectedParamCount", + value: function getGetterSetterExpectedParamCount(method) { + return method.kind === "get" ? 0 : 1; + } + }, { + key: "checkGetterSetterParams", + value: function checkGetterSetterParams(method) { + var paramCount = this.getGetterSetterExpectedParamCount(method); + var start = method.start; - return false; -} + if (method.params.length !== paramCount) { + if (method.kind === "get") { + this.raise(start, "getter must not have any formal parameters"); + } else { + this.raise(start, "setter must have exactly one formal parameter"); + } + } -(0, _keys2.default)(t.BUILDER_KEYS).forEach(function (type) { - var keys = t.BUILDER_KEYS[type]; + if (method.kind === "set" && method.params[method.params.length - 1].type === "RestElement") { + this.raise(start, "setter function argument must not be a rest parameter"); + } + } + }, { + key: "parseObjectMethod", + value: function parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) { + if (isAsync || isGenerator || this.match(types.parenL)) { + if (isPattern) this.unexpected(); + prop.kind = "method"; + prop.method = true; + return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod"); + } - function builder() { - if (arguments.length > keys.length) { - throw new Error("t." + type + ": Too many arguments passed. Received " + arguments.length + " but can receive " + ("no more than " + keys.length)); + if (!containsEsc && this.isGetterOrSetterMethod(prop, isPattern)) { + if (isGenerator || isAsync) this.unexpected(); + prop.kind = prop.key.name; + this.parsePropertyName(prop); + this.parseMethod(prop, false, false, false, false, "ObjectMethod"); + this.checkGetterSetterParams(prop); + return prop; + } } + }, { + key: "parseObjectProperty", + value: function parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos) { + prop.shorthand = false; - var node = {}; - node.type = type; + if (this.eat(types.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos); + return this.finishNode(prop, "ObjectProperty"); + } - var i = 0; + if (!prop.computed && prop.key.type === "Identifier") { + this.checkReservedWord(prop.key.name, prop.key.start, true, true); - for (var _iterator2 = keys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); + } else if (this.match(types.eq) && refShorthandDefaultPos) { + if (!refShorthandDefaultPos.start) { + refShorthandDefaultPos.start = this.state.start; + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); + } else { + prop.value = prop.key.__clone(); + } - var _key = _ref2; + prop.shorthand = true; + return this.finishNode(prop, "ObjectProperty"); + } + } + }, { + key: "parseObjPropValue", + value: function parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc) { + var node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos); + if (!node) this.unexpected(); + return node; + } + }, { + key: "parsePropertyName", + value: function parsePropertyName(prop) { + if (this.eat(types.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types.bracketR); + } else { + var oldInPropertyName = this.state.inPropertyName; + this.state.inPropertyName = true; + prop.key = this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseMaybePrivateName(); - var field = t.NODE_FIELDS[type][_key]; + if (prop.key.type !== "PrivateName") { + prop.computed = false; + } - var arg = arguments[i++]; - if (arg === undefined) arg = (0, _clone2.default)(field.default); + this.state.inPropertyName = oldInPropertyName; + } - node[_key] = arg; + return prop.key; + } + }, { + key: "initFunction", + value: function initFunction(node, isAsync) { + node.id = null; + node.generator = false; + node.async = !!isAsync; + } + }, { + key: "parseMethod", + value: function parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type) { + var inClassScope = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; + var oldYieldPos = this.state.yieldPos; + var oldAwaitPos = this.state.awaitPos; + this.state.yieldPos = -1; + this.state.awaitPos = -1; + this.initFunction(node, isAsync); + node.generator = !!isGenerator; + var allowModifiers = isConstructor; + this.scope.enter(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + this.parseFunctionParams(node, allowModifiers); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBodyAndFinish(node, type, true); + this.scope.exit(); + this.state.yieldPos = oldYieldPos; + this.state.awaitPos = oldAwaitPos; + return node; } + }, { + key: "parseArrowExpression", + value: function parseArrowExpression(node, params, isAsync, trailingCommaPos) { + this.scope.enter(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node, isAsync); + var oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + var oldYieldPos = this.state.yieldPos; + var oldAwaitPos = this.state.awaitPos; + this.state.maybeInArrowParameters = false; + this.state.yieldPos = -1; + this.state.awaitPos = -1; + if (params) this.setArrowFunctionParameters(node, params, trailingCommaPos); + this.parseFunctionBody(node, true); + this.scope.exit(); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + this.state.yieldPos = oldYieldPos; + this.state.awaitPos = oldAwaitPos; + return this.finishNode(node, "ArrowFunctionExpression"); + } + }, { + key: "setArrowFunctionParameters", + value: function setArrowFunctionParameters(node, params, trailingCommaPos) { + node.params = this.toAssignableList(params, true, "arrow function parameters", trailingCommaPos); + } + }, { + key: "isStrictBody", + value: function isStrictBody(node) { + var isBlockStatement = node.body.type === "BlockStatement"; + + if (isBlockStatement && node.body.directives.length) { + for (var _i2 = 0, _node$body$directives = node.body.directives; _i2 < _node$body$directives.length; _i2++) { + var directive = _node$body$directives[_i2]; + + if (directive.value.value === "use strict") { + return true; + } + } + } - for (var key in node) { - validate(node, key, node[key]); + return false; } + }, { + key: "parseFunctionBodyAndFinish", + value: function parseFunctionBodyAndFinish(node, type) { + var isMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + this.parseFunctionBody(node, false, isMethod); + this.finishNode(node, type); + } + }, { + key: "parseFunctionBody", + value: function parseFunctionBody(node, allowExpression) { + var isMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var isExpression = allowExpression && !this.match(types.braceL); + var oldStrict = this.state.strict; + var useStrict = false; + var oldInParameters = this.state.inParameters; + this.state.inParameters = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(); + this.checkParams(node, false, allowExpression, false); + } else { + var nonSimple = !this.isSimpleParamList(node.params); - return node; - } + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.state.end); - t[type] = builder; - t[type[0].toLowerCase() + type.slice(1)] = builder; -}); + if (useStrict && nonSimple) { + var errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start; + this.raise(errorPos, "Illegal 'use strict' directive in function with non-simple parameter list"); + } + } -var _loop = function _loop(_type) { - var newType = t.DEPRECATED_KEYS[_type]; + var oldLabels = this.state.labels; + this.state.labels = []; + if (useStrict) this.state.strict = true; + this.checkParams(node, !oldStrict && !useStrict && !allowExpression && !isMethod && !nonSimple, allowExpression, !oldStrict && useStrict); + node.body = this.parseBlock(true, false); + this.state.labels = oldLabels; + } - function proxy(fn) { - return function () { - console.trace("The node type " + _type + " has been renamed to " + newType); - return fn.apply(this, arguments); - }; - } + this.state.inParameters = oldInParameters; - t[_type] = t[_type[0].toLowerCase() + _type.slice(1)] = proxy(t[newType]); - t["is" + _type] = proxy(t["is" + newType]); - t["assert" + _type] = proxy(t["assert" + newType]); -}; + if (this.state.strict && node.id) { + this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name", undefined, !oldStrict && useStrict); + } -for (var _type in t.DEPRECATED_KEYS) { - _loop(_type); -} + this.state.strict = oldStrict; + } + }, { + key: "isSimpleParamList", + value: function isSimpleParamList(params) { + for (var i = 0, len = params.length; i < len; i++) { + if (params[i].type !== "Identifier") return false; + } -function validate(node, key, val) { - if (!node) return; + return true; + } + }, { + key: "checkParams", + value: function checkParams(node, allowDuplicates, isArrowFunction) { + var strictModeChanged = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + var nameHash = Object.create(null); - var fields = t.NODE_FIELDS[node.type]; - if (!fields) return; + for (var i = 0; i < node.params.length; i++) { + this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function parameter list", undefined, strictModeChanged); + } + } + }, { + key: "parseExprList", + value: function parseExprList(close, allowEmpty, refShorthandDefaultPos, nodeForExtra) { + var elts = []; + var first = true; - var field = fields[key]; - if (!field || !field.validate) return; - if (field.optional && val == null) return; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(types.comma); - field.validate(node, key, val); -} + if (this.match(close)) { + if (nodeForExtra) { + this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart); + } -function shallowEqual(actual, expected) { - var keys = (0, _keys2.default)(expected); + this.next(); + break; + } + } - for (var _iterator3 = keys, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos)); + } - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; + return elts; } + }, { + key: "parseExprListItem", + value: function parseExprListItem(allowEmpty, refShorthandDefaultPos, refNeedsArrowPos, allowPlaceholder) { + var elt; - var key = _ref3; + if (allowEmpty && this.match(types.comma)) { + elt = null; + } else if (this.match(types.ellipsis)) { + var spreadNodeStartPos = this.state.start; + var spreadNodeStartLoc = this.state.startLoc; + elt = this.parseParenItem(this.parseSpread(refShorthandDefaultPos, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc); + } else if (this.match(types.question)) { + this.expectPlugin("partialApplication"); - if (actual[key] !== expected[key]) { - return false; - } - } - - return true; -} + if (!allowPlaceholder) { + this.raise(this.state.start, "Unexpected argument placeholder"); + } -function appendToMemberExpression(member, append, computed) { - member.object = t.memberExpression(member.object, member.property, member.computed); - member.property = append; - member.computed = !!computed; - return member; -} + var node = this.startNode(); + this.next(); + elt = this.finishNode(node, "ArgumentPlaceholder"); + } else { + elt = this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos); + } -function prependToMemberExpression(member, prepend) { - member.object = t.memberExpression(prepend, member.object); - return member; -} + return elt; + } + }, { + key: "parseIdentifier", + value: function parseIdentifier(liberal) { + var node = this.startNode(); + var name = this.parseIdentifierName(node.start, liberal); + return this.createIdentifier(node, name); + } + }, { + key: "createIdentifier", + value: function createIdentifier(node, name) { + node.name = name; + node.loc.identifierName = name; + return this.finishNode(node, "Identifier"); + } + }, { + key: "parseIdentifierName", + value: function parseIdentifierName(pos, liberal) { + var name; + + if (this.match(types.name)) { + name = this.state.value; + } else if (this.state.type.keyword) { + name = this.state.type.keyword; + + if ((name === "class" || name === "function") && (this.state.lastTokEnd !== this.state.lastTokStart + 1 || this.input.charCodeAt(this.state.lastTokStart) !== 46)) { + this.state.context.pop(); + } + } else { + throw this.unexpected(); + } -function ensureBlock(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "body"; + if (liberal) { + this.state.type = types.name; + } else { + this.checkReservedWord(name, this.state.start, !!this.state.type.keyword, false); + } - return node[key] = t.toBlock(node[key], node); -} + this.next(); + return name; + } + }, { + key: "checkReservedWord", + value: function checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (this.scope.inGenerator && word === "yield") { + this.raise(startLoc, "Can not use 'yield' as identifier inside a generator"); + return; + } -function clone(node) { - if (!node) return node; - var newNode = {}; - for (var key in node) { - if (key[0] === "_") continue; - newNode[key] = node[key]; - } - return newNode; -} + if (word === "await") { + if (this.scope.inAsync) { + this.raise(startLoc, "Can not use 'await' as identifier inside an async function"); + return; + } -function cloneWithoutLoc(node) { - var newNode = clone(node); - delete newNode.loc; - return newNode; -} + if (this.state.awaitPos === -1 && (this.state.maybeInArrowParameters || this.isAwaitAllowed())) { + this.state.awaitPos = this.state.start; + } + } -function cloneDeep(node) { - if (!node) return node; - var newNode = {}; + if (this.state.inClassProperty && word === "arguments") { + this.raise(startLoc, "'arguments' is not allowed in class field initializer"); + return; + } - for (var key in node) { - if (key[0] === "_") continue; + if (checkKeywords && isKeyword(word)) { + this.raise(startLoc, "Unexpected keyword '".concat(word, "'")); + return; + } - var val = node[key]; + var reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; - if (val) { - if (val.type) { - val = t.cloneDeep(val); - } else if (Array.isArray(val)) { - val = val.map(t.cloneDeep); + if (reservedTest(word, this.inModule)) { + if (!this.scope.inAsync && word === "await") { + this.raise(startLoc, "Can not use keyword 'await' outside an async function"); + } else { + this.raise(startLoc, "Unexpected reserved word '".concat(word, "'")); + } } } + }, { + key: "isAwaitAllowed", + value: function isAwaitAllowed() { + if (this.scope.inFunction) return this.scope.inAsync; + if (this.options.allowAwaitOutsideFunction) return true; + if (this.hasPlugin("topLevelAwait")) return this.inModule; + return false; + } + }, { + key: "parseAwait", + value: function parseAwait() { + var node = this.startNode(); + this.next(); - newNode[key] = val; - } - - return newNode; -} - -function buildMatchMemberExpression(match, allowPartial) { - var parts = match.split("."); - - return function (member) { - if (!t.isMemberExpression(member)) return false; - - var search = [member]; - var i = 0; - - while (search.length) { - var node = search.shift(); + if (this.state.inParameters) { + this.raise(node.start, "await is not allowed in async function parameters"); + } else if (this.state.awaitPos === -1) { + this.state.awaitPos = node.start; + } - if (allowPartial && i === parts.length) { - return true; + if (this.eat(types.star)) { + this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead."); } - if (t.isIdentifier(node)) { - if (parts[i] !== node.name) return false; - } else if (t.isStringLiteral(node)) { - if (parts[i] !== node.value) return false; - } else if (t.isMemberExpression(node)) { - if (node.computed && !t.isStringLiteral(node.property)) { - return false; + if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) { + if (this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo)) { + this.ambiguousScriptDifferentAst = true; } else { - search.push(node.object); - search.push(node.property); - continue; + this.sawUnambiguousESM = true; } - } else { - return false; } - if (++i > parts.length) { - return false; + if (!this.state.soloAwait) { + node.argument = this.parseMaybeUnary(); } + + return this.finishNode(node, "AwaitExpression"); } + }, { + key: "parseYield", + value: function parseYield(noIn) { + var node = this.startNode(); - return true; - }; -} + if (this.state.inParameters) { + this.raise(node.start, "yield is not allowed in generator parameters"); + } else if (this.state.yieldPos === -1) { + this.state.yieldPos = node.start; + } -function removeComments(node) { - for (var _iterator4 = t.COMMENT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; + this.next(); - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; + if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types.star); + node.argument = this.parseMaybeAssign(noIn); + } + + return this.finishNode(node, "YieldExpression"); + } + }, { + key: "checkPipelineAtInfixOperator", + value: function checkPipelineAtInfixOperator(left, leftStartPos) { + if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { + if (left.type === "SequenceExpression") { + this.raise(leftStartPos, "Pipeline head should not be a comma-separated sequence expression"); + } + } } + }, { + key: "parseSmartPipelineBody", + value: function parseSmartPipelineBody(childExpression, startPos, startLoc) { + var pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression); + this.checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos); + return this.parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc); + } + }, { + key: "checkSmartPipelineBodyEarlyErrors", + value: function checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos) { + if (this.match(types.arrow)) { + throw this.raise(this.state.start, "Unexpected arrow \"=>\" after pipeline body; arrow function in pipeline body must be parenthesized"); + } else if (pipelineStyle === "PipelineTopicExpression" && childExpression.type === "SequenceExpression") { + this.raise(startPos, "Pipeline body may not be a comma-separated sequence expression"); + } + } + }, { + key: "parseSmartPipelineBodyInStyle", + value: function parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc) { + var bodyNode = this.startNodeAt(startPos, startLoc); - var key = _ref4; + switch (pipelineStyle) { + case "PipelineBareFunction": + bodyNode.callee = childExpression; + break; - delete node[key]; - } - return node; -} + case "PipelineBareConstructor": + bodyNode.callee = childExpression.callee; + break; -function inheritsComments(child, parent) { - inheritTrailingComments(child, parent); - inheritLeadingComments(child, parent); - inheritInnerComments(child, parent); - return child; -} + case "PipelineBareAwaitedFunction": + bodyNode.callee = childExpression.argument; + break; -function inheritTrailingComments(child, parent) { - _inheritComments("trailingComments", child, parent); -} + case "PipelineTopicExpression": + if (!this.topicReferenceWasUsedInCurrentTopicContext()) { + this.raise(startPos, "Pipeline is in topic style but does not use topic reference"); + } -function inheritLeadingComments(child, parent) { - _inheritComments("leadingComments", child, parent); -} + bodyNode.expression = childExpression; + break; -function inheritInnerComments(child, parent) { - _inheritComments("innerComments", child, parent); -} + default: + throw new Error("Internal @babel/parser error: Unknown pipeline style (".concat(pipelineStyle, ")")); + } -function _inheritComments(key, child, parent) { - if (child && parent) { - child[key] = (0, _uniq2.default)([].concat(child[key], parent[key]).filter(Boolean)); - } -} + return this.finishNode(bodyNode, pipelineStyle); + } + }, { + key: "checkSmartPipelineBodyStyle", + value: function checkSmartPipelineBodyStyle(expression) { + switch (expression.type) { + default: + return this.isSimpleReference(expression) ? "PipelineBareFunction" : "PipelineTopicExpression"; + } + } + }, { + key: "isSimpleReference", + value: function isSimpleReference(expression) { + switch (expression.type) { + case "MemberExpression": + return !expression.computed && this.isSimpleReference(expression.object); -function inherits(child, parent) { - if (!child || !parent) return child; + case "Identifier": + return true; - for (var _iterator5 = t.INHERIT_KEYS.optional, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; + default: + return false; + } + } + }, { + key: "withTopicPermittingContext", + value: function withTopicPermittingContext(callback) { + var outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 1, + maxTopicIndex: null + }; - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } } + }, { + key: "withTopicForbiddingContext", + value: function withTopicForbiddingContext(callback) { + var outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; - var _key2 = _ref5; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } + }, { + key: "withSoloAwaitPermittingContext", + value: function withSoloAwaitPermittingContext(callback) { + var outerContextSoloAwaitState = this.state.soloAwait; + this.state.soloAwait = true; - if (child[_key2] == null) { - child[_key2] = parent[_key2]; + try { + return callback(); + } finally { + this.state.soloAwait = outerContextSoloAwaitState; + } } - } + }, { + key: "registerTopicReference", + value: function registerTopicReference() { + this.state.topicContext.maxTopicIndex = 0; + } + }, { + key: "primaryTopicReferenceIsAllowedInCurrentTopicContext", + value: function primaryTopicReferenceIsAllowedInCurrentTopicContext() { + return this.state.topicContext.maxNumOfResolvableTopics >= 1; + } + }, { + key: "topicReferenceWasUsedInCurrentTopicContext", + value: function topicReferenceWasUsedInCurrentTopicContext() { + return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; + } + }, { + key: "parseFSharpPipelineBody", + value: function parseFSharpPipelineBody(prec, noIn) { + var startPos = this.state.start; + var startLoc = this.state.startLoc; + this.state.potentialArrowAt = this.state.start; + var oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = true; + var ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return ret; + } + }]); - for (var key in parent) { - if (key[0] === "_") child[key] = parent[key]; - } + return ExpressionParser; +}(LValParser); - for (var _iterator6 = t.INHERIT_KEYS.force, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; +var loopLabel = { + kind: "loop" +}, + switchLabel = { + kind: "switch" +}; +var FUNC_NO_FLAGS = 0, + FUNC_STATEMENT = 1, + FUNC_HANGING_STATEMENT = 2, + FUNC_NULLABLE_ID = 4; - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } +var StatementParser = +/*#__PURE__*/ +function (_ExpressionParser) { + _inherits(StatementParser, _ExpressionParser); - var _key3 = _ref6; + function StatementParser() { + _classCallCheck(this, StatementParser); - child[_key3] = parent[_key3]; + return _possibleConstructorReturn(this, _getPrototypeOf(StatementParser).apply(this, arguments)); } - t.inheritsComments(child, parent); + _createClass(StatementParser, [{ + key: "parseTopLevel", + value: function parseTopLevel(file, program) { + program.sourceType = this.options.sourceType; + program.interpreter = this.parseInterpreterDirective(); + this.parseBlockBody(program, true, true, types.eof); - return child; -} + if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) { + for (var _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) { + var _Array$from$_i = _slicedToArray(_Array$from[_i], 1), + name = _Array$from$_i[0]; -function assertNode(node) { - if (!isNode(node)) { - throw new TypeError("Not a valid node " + (node && node.type)); - } -} + var pos = this.scope.undefinedExports.get(name); + this.raise(pos, "Export '".concat(name, "' is not defined")); + } + } -function isNode(node) { - return !!(node && _definitions.VISITOR_KEYS[node.type]); -} + file.program = this.finishNode(program, "Program"); + file.comments = this.state.comments; + if (this.options.tokens) file.tokens = this.state.tokens; + return this.finishNode(file, "File"); + } + }, { + key: "stmtToDirective", + value: function stmtToDirective(stmt) { + var expr = stmt.expression; + var directiveLiteral = this.startNodeAt(expr.start, expr.loc.start); + var directive = this.startNodeAt(stmt.start, stmt.loc.start); + var raw = this.input.slice(expr.start, expr.end); + var val = directiveLiteral.value = raw.slice(1, -1); + this.addExtra(directiveLiteral, "raw", raw); + this.addExtra(directiveLiteral, "rawValue", val); + directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end); + return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end); + } + }, { + key: "parseInterpreterDirective", + value: function parseInterpreterDirective() { + if (!this.match(types.interpreterDirective)) { + return null; + } -(0, _toFastProperties2.default)(t); -(0, _toFastProperties2.default)(t.VISITOR_KEYS); + var node = this.startNode(); + node.value = this.state.value; + this.next(); + return this.finishNode(node, "InterpreterDirective"); + } + }, { + key: "isLet", + value: function isLet(context) { + if (!this.isContextual("let")) { + return false; + } -function traverseFast(node, enter, opts) { - if (!node) return; + var next = this.nextTokenStart(); + var nextCh = this.input.charCodeAt(next); + if (nextCh === 91) return true; + if (context) return false; + if (nextCh === 123) return true; - var keys = t.VISITOR_KEYS[node.type]; - if (!keys) return; + if (isIdentifierStart(nextCh)) { + var pos = next + 1; - opts = opts || {}; - enter(node, opts); + while (isIdentifierChar(this.input.charCodeAt(pos))) { + ++pos; + } - for (var _iterator7 = keys, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) return true; + } - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; + return false; } + }, { + key: "parseStatement", + value: function parseStatement(context, topLevel) { + if (this.match(types.at)) { + this.parseDecorators(true); + } - var key = _ref7; + return this.parseStatementContent(context, topLevel); + } + }, { + key: "parseStatementContent", + value: function parseStatementContent(context, topLevel) { + var starttype = this.state.type; + var node = this.startNode(); + var kind; - var subNode = node[key]; + if (this.isLet(context)) { + starttype = types._var; + kind = "let"; + } - if (Array.isArray(subNode)) { - for (var _iterator8 = subNode, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; + switch (starttype) { + case types._break: + case types._continue: + return this.parseBreakContinueStatement(node, starttype.keyword); - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref8 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref8 = _i8.value; - } + case types._debugger: + return this.parseDebuggerStatement(node); - var _node = _ref8; + case types._do: + return this.parseDoStatement(node); - traverseFast(_node, enter, opts); - } - } else { - traverseFast(subNode, enter, opts); - } - } -} + case types._for: + return this.parseForStatement(node); -var CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; + case types._function: + if (this.lookaheadCharCode() === 46) break; -var CLEAR_KEYS_PLUS_COMMENTS = t.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); + if (context) { + if (this.state.strict) { + this.raise(this.state.start, "In strict mode code, functions can only be declared at top level or inside a block"); + } else if (context !== "if" && context !== "label") { + this.raise(this.state.start, "In non-strict mode code, functions can only be declared at top level, " + "inside a block, or as the body of an if statement"); + } + } -function removeProperties(node, opts) { - opts = opts || {}; - var map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; - for (var _iterator9 = map, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; + return this.parseFunctionStatement(node, false, !context); - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref9 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref9 = _i9.value; - } + case types._class: + if (context) this.unexpected(); + return this.parseClass(node, true); - var _key4 = _ref9; + case types._if: + return this.parseIfStatement(node); - if (node[_key4] != null) node[_key4] = undefined; - } + case types._return: + return this.parseReturnStatement(node); - for (var key in node) { - if (key[0] === "_" && node[key] != null) node[key] = undefined; - } + case types._switch: + return this.parseSwitchStatement(node); - var syms = (0, _getOwnPropertySymbols2.default)(node); - for (var _iterator10 = syms, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { - var _ref10; + case types._throw: + return this.parseThrowStatement(node); - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref10 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref10 = _i10.value; - } + case types._try: + return this.parseTryStatement(node); - var sym = _ref10; + case types._const: + case types._var: + kind = kind || this.state.value; - node[sym] = null; - } -} + if (context && kind !== "var") { + this.raise(this.state.start, "Lexical declaration cannot appear in a single-statement context"); + } -function removePropertiesDeep(tree, opts) { - traverseFast(tree, removeProperties, opts); - return tree; -} -},{"./constants":140,"./converters":141,"./definitions":146,"./definitions/init":147,"./flow":150,"./react":152,"./retrievers":153,"./validators":154,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/json/stringify":96,"babel-runtime/core-js/object/get-own-property-symbols":101,"babel-runtime/core-js/object/keys":102,"lodash/clone":466,"lodash/uniq":517,"to-fast-properties":555}],152:[function(require,module,exports){ -"use strict"; + return this.parseVarStatement(node, kind); -exports.__esModule = true; -exports.isReactComponent = undefined; -exports.isCompatTag = isCompatTag; -exports.buildChildren = buildChildren; + case types._while: + return this.parseWhileStatement(node); -var _index = require("./index"); + case types._with: + return this.parseWithStatement(node); -var t = _interopRequireWildcard(_index); + case types.braceL: + return this.parseBlock(); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + case types.semi: + return this.parseEmptyStatement(node); -var isReactComponent = exports.isReactComponent = t.buildMatchMemberExpression("React.Component"); + case types._export: + case types._import: + { + var nextTokenCharCode = this.lookaheadCharCode(); -function isCompatTag(tagName) { - return !!tagName && /^[a-z]|\-/.test(tagName); -} + if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { + break; + } -function cleanJSXElementLiteralChild(child, args) { - var lines = child.value.split(/\r\n|\n|\r/); + if (!this.options.allowImportExportEverywhere && !topLevel) { + this.raise(this.state.start, "'import' and 'export' may only appear at the top level"); + } - var lastNonEmptyLine = 0; + this.next(); + var result; - for (var i = 0; i < lines.length; i++) { - if (lines[i].match(/[^ \t]/)) { - lastNonEmptyLine = i; - } - } + if (starttype === types._import) { + result = this.parseImport(node); - var str = ""; + if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) { + this.sawUnambiguousESM = true; + } + } else { + result = this.parseExport(node); - for (var _i = 0; _i < lines.length; _i++) { - var line = lines[_i]; + if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") { + this.sawUnambiguousESM = true; + } + } - var isFirstLine = _i === 0; - var isLastLine = _i === lines.length - 1; - var isLastNonEmptyLine = _i === lastNonEmptyLine; + this.assertModuleNodeAllowed(node); + return result; + } - var trimmedLine = line.replace(/\t/g, " "); + default: + { + if (this.isAsyncFunction()) { + if (context) { + this.raise(this.state.start, "Async functions can only be declared at the top level or inside a block"); + } - if (!isFirstLine) { - trimmedLine = trimmedLine.replace(/^[ ]+/, ""); + this.next(); + return this.parseFunctionStatement(node, true, !context); + } + } + } + + var maybeName = this.state.value; + var expr = this.parseExpression(); + + if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) { + return this.parseLabeledStatement(node, maybeName, expr, context); + } else { + return this.parseExpressionStatement(node, expr); + } + } + }, { + key: "assertModuleNodeAllowed", + value: function assertModuleNodeAllowed(node) { + if (!this.options.allowImportExportEverywhere && !this.inModule) { + this.raise(node.start, "'import' and 'export' may appear only with 'sourceType: \"module\"'", { + code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" + }); + } } + }, { + key: "takeDecorators", + value: function takeDecorators(node) { + var decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; - if (!isLastLine) { - trimmedLine = trimmedLine.replace(/[ ]+$/, ""); + if (decorators.length) { + node.decorators = decorators; + this.resetStartLocationFromNode(node, decorators[0]); + this.state.decoratorStack[this.state.decoratorStack.length - 1] = []; + } } + }, { + key: "canHaveLeadingDecorator", + value: function canHaveLeadingDecorator() { + return this.match(types._class); + } + }, { + key: "parseDecorators", + value: function parseDecorators(allowExport) { + var currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; - if (trimmedLine) { - if (!isLastNonEmptyLine) { - trimmedLine += " "; + while (this.match(types.at)) { + var decorator = this.parseDecorator(); + currentContextDecorators.push(decorator); } - str += trimmedLine; + if (this.match(types._export)) { + if (!allowExport) { + this.unexpected(); + } + + if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) { + this.raise(this.state.start, "Using the export keyword between a decorator and a class is not allowed. " + "Please use `export @dec class` instead."); + } + } else if (!this.canHaveLeadingDecorator()) { + throw this.raise(this.state.start, "Leading decorators must be attached to a class declaration"); + } } - } + }, { + key: "parseDecorator", + value: function parseDecorator() { + this.expectOnePlugin(["decorators-legacy", "decorators"]); + var node = this.startNode(); + this.next(); - if (str) args.push(t.stringLiteral(str)); -} + if (this.hasPlugin("decorators")) { + this.state.decoratorStack.push([]); + var startPos = this.state.start; + var startLoc = this.state.startLoc; + var expr; -function buildChildren(node) { - var elems = []; + if (this.eat(types.parenL)) { + expr = this.parseExpression(); + this.expect(types.parenR); + } else { + expr = this.parseIdentifier(false); - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i]; + while (this.eat(types.dot)) { + var _node15 = this.startNodeAt(startPos, startLoc); - if (t.isJSXText(child)) { - cleanJSXElementLiteralChild(child, elems); - continue; + _node15.object = expr; + _node15.property = this.parseIdentifier(true); + _node15.computed = false; + expr = this.finishNode(_node15, "MemberExpression"); + } + } + + node.expression = this.parseMaybeDecoratorArguments(expr); + this.state.decoratorStack.pop(); + } else { + node.expression = this.parseExprSubscripts(); + } + + return this.finishNode(node, "Decorator"); } + }, { + key: "parseMaybeDecoratorArguments", + value: function parseMaybeDecoratorArguments(expr) { + if (this.eat(types.parenL)) { + var node = this.startNodeAtNode(expr); + node.callee = expr; + node.arguments = this.parseCallExpressionArguments(types.parenR, false); + this.toReferencedList(node.arguments); + return this.finishNode(node, "CallExpression"); + } - if (t.isJSXExpressionContainer(child)) child = child.expression; - if (t.isJSXEmptyExpression(child)) continue; + return expr; + } + }, { + key: "parseBreakContinueStatement", + value: function parseBreakContinueStatement(node, keyword) { + var isBreak = keyword === "break"; + this.next(); - elems.push(child); - } + if (this.isLineTerminator()) { + node.label = null; + } else { + node.label = this.parseIdentifier(); + this.semicolon(); + } - return elems; -} -},{"./index":151}],153:[function(require,module,exports){ -"use strict"; + this.verifyBreakContinue(node, keyword); + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); + } + }, { + key: "verifyBreakContinue", + value: function verifyBreakContinue(node, keyword) { + var isBreak = keyword === "break"; + var i; -exports.__esModule = true; + for (i = 0; i < this.state.labels.length; ++i) { + var lab = this.state.labels[i]; -var _create = require("babel-runtime/core-js/object/create"); + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) break; + if (node.label && isBreak) break; + } + } -var _create2 = _interopRequireDefault(_create); + if (i === this.state.labels.length) { + this.raise(node.start, "Unsyntactic " + keyword); + } + } + }, { + key: "parseDebuggerStatement", + value: function parseDebuggerStatement(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); + } + }, { + key: "parseHeaderExpression", + value: function parseHeaderExpression() { + this.expect(types.parenL); + var val = this.parseExpression(); + this.expect(types.parenR); + return val; + } + }, { + key: "parseDoStatement", + value: function parseDoStatement(node) { + var _this37 = this; -exports.getBindingIdentifiers = getBindingIdentifiers; -exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; + this.next(); + this.state.labels.push(loopLabel); + node.body = this.withTopicForbiddingContext(function () { + return _this37.parseStatement("do"); + }); + this.state.labels.pop(); + this.expect(types._while); + node.test = this.parseHeaderExpression(); + this.eat(types.semi); + return this.finishNode(node, "DoWhileStatement"); + } + }, { + key: "parseForStatement", + value: function parseForStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + var awaitAt = -1; -var _index = require("./index"); + if (this.isAwaitAllowed() && this.eatContextual("await")) { + awaitAt = this.state.lastTokStart; + } -var t = _interopRequireWildcard(_index); + this.scope.enter(SCOPE_OTHER); + this.expect(types.parenL); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (this.match(types.semi)) { + if (awaitAt > -1) { + this.unexpected(awaitAt); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return this.parseFor(node, null); + } -function getBindingIdentifiers(node, duplicates, outerOnly) { - var search = [].concat(node); - var ids = (0, _create2.default)(null); + var isLet = this.isLet(); - while (search.length) { - var id = search.shift(); - if (!id) continue; + if (this.match(types._var) || this.match(types._const) || isLet) { + var _init = this.startNode(); - var keys = t.getBindingIdentifiers.keys[id.type]; + var kind = isLet ? "let" : this.state.value; + this.next(); + this.parseVar(_init, true, kind); + this.finishNode(_init, "VariableDeclaration"); - if (t.isIdentifier(id)) { - if (duplicates) { - var _ids = ids[id.name] = ids[id.name] || []; - _ids.push(id); - } else { - ids[id.name] = id; + if ((this.match(types._in) || this.isContextual("of")) && _init.declarations.length === 1) { + return this.parseForIn(node, _init, awaitAt); + } + + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + + return this.parseFor(node, _init); } - continue; - } - if (t.isExportDeclaration(id)) { - if (t.isDeclaration(id.declaration)) { - search.push(id.declaration); + var refShorthandDefaultPos = { + start: 0 + }; + var init = this.parseExpression(true, refShorthandDefaultPos); + + if (this.match(types._in) || this.isContextual("of")) { + var description = this.isContextual("of") ? "for-of statement" : "for-in statement"; + this.toAssignable(init, undefined, description); + this.checkLVal(init, undefined, undefined, description); + return this.parseForIn(node, init, awaitAt); + } else if (refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); } - continue; - } - if (outerOnly) { - if (t.isFunctionDeclaration(id)) { - search.push(id.id); - continue; + if (awaitAt > -1) { + this.unexpected(awaitAt); } - if (t.isFunctionExpression(id)) { - continue; + return this.parseFor(node, init); + } + }, { + key: "parseFunctionStatement", + value: function parseFunctionStatement(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync); + } + }, { + key: "parseIfStatement", + value: function parseIfStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement"); + } + }, { + key: "parseReturnStatement", + value: function parseReturnStatement(node) { + if (!this.scope.inFunction && !this.options.allowReturnOutsideFunction) { + this.raise(this.state.start, "'return' outside of function"); + } + + this.next(); + + if (this.isLineTerminator()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); } + + return this.finishNode(node, "ReturnStatement"); } + }, { + key: "parseSwitchStatement", + value: function parseSwitchStatement(node) { + this.next(); + node.discriminant = this.parseHeaderExpression(); + var cases = node.cases = []; + this.expect(types.braceL); + this.state.labels.push(switchLabel); + this.scope.enter(SCOPE_OTHER); + var cur; + + for (var sawDefault; !this.match(types.braceR);) { + if (this.match(types._case) || this.match(types._default)) { + var isCase = this.match(types._case); + if (cur) this.finishNode(cur, "SwitchCase"); + cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (id[key]) { - search = search.concat(id[key]); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raise(this.state.lastTokStart, "Multiple default clauses"); + } + + sawDefault = true; + cur.test = null; + } + + this.expect(types.colon); + } else { + if (cur) { + cur.consequent.push(this.parseStatement(null)); + } else { + this.unexpected(); + } } } + + this.scope.exit(); + if (cur) this.finishNode(cur, "SwitchCase"); + this.next(); + this.state.labels.pop(); + return this.finishNode(node, "SwitchStatement"); } - } + }, { + key: "parseThrowStatement", + value: function parseThrowStatement(node) { + this.next(); - return ids; -} + if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) { + this.raise(this.state.lastTokEnd, "Illegal newline after throw"); + } -getBindingIdentifiers.keys = { - DeclareClass: ["id"], - DeclareFunction: ["id"], - DeclareModule: ["id"], - DeclareVariable: ["id"], - InterfaceDeclaration: ["id"], - TypeAlias: ["id"], - OpaqueType: ["id"], + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); + } + }, { + key: "parseTryStatement", + value: function parseTryStatement(node) { + var _this38 = this; - CatchClause: ["param"], - LabeledStatement: ["label"], - UnaryExpression: ["argument"], - AssignmentExpression: ["left"], + this.next(); + node.block = this.parseBlock(); + node.handler = null; - ImportSpecifier: ["local"], - ImportNamespaceSpecifier: ["local"], - ImportDefaultSpecifier: ["local"], - ImportDeclaration: ["specifiers"], + if (this.match(types._catch)) { + var clause = this.startNode(); + this.next(); - ExportSpecifier: ["exported"], - ExportNamespaceSpecifier: ["exported"], - ExportDefaultSpecifier: ["exported"], + if (this.match(types.parenL)) { + this.expect(types.parenL); + clause.param = this.parseBindingAtom(); + var simple = clause.param.type === "Identifier"; + this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause"); + this.expect(types.parenR); + } else { + clause.param = null; + this.scope.enter(SCOPE_OTHER); + } - FunctionDeclaration: ["id", "params"], - FunctionExpression: ["id", "params"], + clause.body = this.withTopicForbiddingContext(function () { + return _this38.parseBlock(false, false); + }); + this.scope.exit(); + node.handler = this.finishNode(clause, "CatchClause"); + } - ClassDeclaration: ["id"], - ClassExpression: ["id"], + node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; - RestElement: ["argument"], - UpdateExpression: ["argument"], + if (!node.handler && !node.finalizer) { + this.raise(node.start, "Missing catch or finally clause"); + } - RestProperty: ["argument"], - ObjectProperty: ["value"], + return this.finishNode(node, "TryStatement"); + } + }, { + key: "parseVarStatement", + value: function parseVarStatement(node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); + } + }, { + key: "parseWhileStatement", + value: function parseWhileStatement(node) { + var _this39 = this; - AssignmentPattern: ["left"], - ArrayPattern: ["elements"], - ObjectPattern: ["properties"], + this.next(); + node.test = this.parseHeaderExpression(); + this.state.labels.push(loopLabel); + node.body = this.withTopicForbiddingContext(function () { + return _this39.parseStatement("while"); + }); + this.state.labels.pop(); + return this.finishNode(node, "WhileStatement"); + } + }, { + key: "parseWithStatement", + value: function parseWithStatement(node) { + var _this40 = this; - VariableDeclaration: ["declarations"], - VariableDeclarator: ["id"] -}; + if (this.state.strict) { + this.raise(this.state.start, "'with' in strict mode"); + } -function getOuterBindingIdentifiers(node, duplicates) { - return getBindingIdentifiers(node, duplicates, true); -} -},{"./index":151,"babel-runtime/core-js/object/create":100}],154:[function(require,module,exports){ -"use strict"; + this.next(); + node.object = this.parseHeaderExpression(); + node.body = this.withTopicForbiddingContext(function () { + return _this40.parseStatement("with"); + }); + return this.finishNode(node, "WithStatement"); + } + }, { + key: "parseEmptyStatement", + value: function parseEmptyStatement(node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); + } + }, { + key: "parseLabeledStatement", + value: function parseLabeledStatement(node, maybeName, expr, context) { + for (var _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) { + var label = _this$state$labels[_i2]; -exports.__esModule = true; + if (label.name === maybeName) { + this.raise(expr.start, "Label '".concat(maybeName, "' is already declared")); + } + } -var _keys = require("babel-runtime/core-js/object/keys"); + var kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null; -var _keys2 = _interopRequireDefault(_keys); + for (var i = this.state.labels.length - 1; i >= 0; i--) { + var _label = this.state.labels[i]; -var _typeof2 = require("babel-runtime/helpers/typeof"); + if (_label.statementStart === node.start) { + _label.statementStart = this.state.start; + _label.kind = kind; + } else { + break; + } + } -var _typeof3 = _interopRequireDefault(_typeof2); + this.state.labels.push({ + name: maybeName, + kind: kind, + statementStart: this.state.start + }); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.state.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); + } + }, { + key: "parseExpressionStatement", + value: function parseExpressionStatement(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); + } + }, { + key: "parseBlock", + value: function parseBlock() { + var allowDirectives = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var createNewLexicalScope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + var node = this.startNode(); + this.expect(types.braceL); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (createNewLexicalScope) { + this.scope.enter(SCOPE_OTHER); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + this.parseBlockBody(node, allowDirectives, false, types.braceR); -exports.isBinding = isBinding; -exports.isReferenced = isReferenced; -exports.isValidIdentifier = isValidIdentifier; -exports.isLet = isLet; -exports.isBlockScoped = isBlockScoped; -exports.isVar = isVar; -exports.isSpecifierDefault = isSpecifierDefault; -exports.isScope = isScope; -exports.isImmutable = isImmutable; -exports.isNodesEquivalent = isNodesEquivalent; + if (createNewLexicalScope) { + this.scope.exit(); + } -var _retrievers = require("./retrievers"); + return this.finishNode(node, "BlockStatement"); + } + }, { + key: "isValidDirective", + value: function isValidDirective(stmt) { + return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; + } + }, { + key: "parseBlockBody", + value: function parseBlockBody(node, allowDirectives, topLevel, end) { + var body = node.body = []; + var directives = node.directives = []; + this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end); + } + }, { + key: "parseBlockOrModuleBlockBody", + value: function parseBlockOrModuleBlockBody(body, directives, topLevel, end) { + var parsedNonDirective = false; + var oldStrict; + var octalPosition; -var _esutils = require("esutils"); + while (!this.eat(end)) { + if (!parsedNonDirective && this.state.containsOctal && !octalPosition) { + octalPosition = this.state.octalPosition; + } -var _esutils2 = _interopRequireDefault(_esutils); + var stmt = this.parseStatement(null, topLevel); -var _index = require("./index"); + if (directives && !parsedNonDirective && this.isValidDirective(stmt)) { + var directive = this.stmtToDirective(stmt); + directives.push(directive); -var t = _interopRequireWildcard(_index); + if (oldStrict === undefined && directive.value.value === "use strict") { + oldStrict = this.state.strict; + this.setStrict(true); -var _constants = require("./constants"); + if (octalPosition) { + this.raise(octalPosition, "Octal literal in strict mode"); + } + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + continue; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + parsedNonDirective = true; + body.push(stmt); + } -function isBinding(node, parent) { - var keys = _retrievers.getBindingIdentifiers.keys[parent.type]; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var val = parent[key]; - if (Array.isArray(val)) { - if (val.indexOf(node) >= 0) return true; - } else { - if (val === node) return true; + if (oldStrict === false) { + this.setStrict(false); } } - } + }, { + key: "parseFor", + value: function parseFor(node, init) { + var _this41 = this; - return false; -} + node.init = init; + this.expect(types.semi); + node.test = this.match(types.semi) ? null : this.parseExpression(); + this.expect(types.semi); + node.update = this.match(types.parenR) ? null : this.parseExpression(); + this.expect(types.parenR); + node.body = this.withTopicForbiddingContext(function () { + return _this41.parseStatement("for"); + }); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, "ForStatement"); + } + }, { + key: "parseForIn", + value: function parseForIn(node, init, awaitAt) { + var _this42 = this; -function isReferenced(node, parent) { - switch (parent.type) { - case "BindExpression": - return parent.object === node || parent.callee === node; + var isForIn = this.match(types._in); + this.next(); - case "MemberExpression": - case "JSXMemberExpression": - if (parent.property === node && parent.computed) { - return true; - } else if (parent.object === node) { - return true; + if (isForIn) { + if (awaitAt > -1) this.unexpected(awaitAt); } else { - return false; + node.await = awaitAt > -1; } - case "MetaProperty": - return false; - - case "ObjectProperty": - if (parent.key === node) { - return parent.computed; + if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { + this.raise(init.start, "".concat(isForIn ? "for-in" : "for-of", " loop variable declaration may not have an initializer")); + } else if (init.type === "AssignmentPattern") { + this.raise(init.start, "Invalid left-hand side in for-loop"); } - case "VariableDeclarator": - return parent.id !== node; - - case "ArrowFunctionExpression": - case "FunctionDeclaration": - case "FunctionExpression": - for (var _iterator = parent.params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types.parenR); + node.body = this.withTopicForbiddingContext(function () { + return _this42.parseStatement("for"); + }); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); + } + }, { + key: "parseVar", + value: function parseVar(node, isFor, kind) { + var declarations = node.declarations = []; + var isTypescript = this.hasPlugin("typescript"); + node.kind = kind; + + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + + if (this.eat(types.eq)) { + decl.init = this.parseMaybeAssign(isFor); } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var param = _ref; - - if (param === node) return false; - } + if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) { + if (!isTypescript) { + this.unexpected(); + } + } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) { + this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value"); + } - return parent.id !== node; + decl.init = null; + } - case "ExportSpecifier": - if (parent.source) { - return false; - } else { - return parent.local === node; + declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types.comma)) break; } - case "ExportNamespaceSpecifier": - case "ExportDefaultSpecifier": - return false; + return node; + } + }, { + key: "parseVarId", + value: function parseVarId(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration", kind !== "var"); + } + }, { + key: "parseFunction", + value: function parseFunction(node) { + var _this43 = this; - case "JSXAttribute": - return parent.name !== node; + var statement = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : FUNC_NO_FLAGS; + var isAsync = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var isStatement = statement & FUNC_STATEMENT; + var isHangingStatement = statement & FUNC_HANGING_STATEMENT; + var requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID); + this.initFunction(node, isAsync); - case "ClassProperty": - if (parent.key === node) { - return parent.computed; - } else { - return parent.value === node; + if (this.match(types.star) && isHangingStatement) { + this.raise(this.state.start, "Generators can only be declared at the top level or inside a block"); } - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "ImportSpecifier": - return false; + node.generator = this.eat(types.star); - case "ClassDeclaration": - case "ClassExpression": - return parent.id !== node; + if (isStatement) { + node.id = this.parseFunctionId(requireId); + } - case "ClassMethod": - case "ObjectMethod": - return parent.key === node && parent.computed; + var oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + var oldInClassProperty = this.state.inClassProperty; + var oldYieldPos = this.state.yieldPos; + var oldAwaitPos = this.state.awaitPos; + this.state.maybeInArrowParameters = false; + this.state.inClassProperty = false; + this.state.yieldPos = -1; + this.state.awaitPos = -1; + this.scope.enter(functionFlags(node.async, node.generator)); - case "LabeledStatement": - return false; + if (!isStatement) { + node.id = this.parseFunctionId(); + } - case "CatchClause": - return parent.param !== node; + this.parseFunctionParams(node); + this.withTopicForbiddingContext(function () { + _this43.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); + }); + this.scope.exit(); - case "RestElement": - return false; + if (isStatement && !isHangingStatement) { + this.registerFunctionStatementId(node); + } - case "AssignmentExpression": - return parent.right === node; - - case "AssignmentPattern": - return parent.right === node; - - case "ObjectPattern": - case "ArrayPattern": - return false; - } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + this.state.inClassProperty = oldInClassProperty; + this.state.yieldPos = oldYieldPos; + this.state.awaitPos = oldAwaitPos; + return node; + } + }, { + key: "parseFunctionId", + value: function parseFunctionId(requireId) { + return requireId || this.match(types.name) ? this.parseIdentifier() : null; + } + }, { + key: "parseFunctionParams", + value: function parseFunctionParams(node, allowModifiers) { + var oldInParameters = this.state.inParameters; + this.state.inParameters = true; + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers); + this.state.inParameters = oldInParameters; + this.checkYieldAwaitInDefaultParams(); + } + }, { + key: "registerFunctionStatementId", + value: function registerFunctionStatementId(node) { + if (!node.id) return; + this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start); + } + }, { + key: "parseClass", + value: function parseClass(node, isStatement, optionalId) { + this.next(); + this.takeDecorators(node); + var oldStrict = this.state.strict; + this.state.strict = true; + this.parseClassId(node, isStatement, optionalId); + this.parseClassSuper(node); + node.body = this.parseClassBody(!!node.superClass); + this.state.strict = oldStrict; + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); + } + }, { + key: "isClassProperty", + value: function isClassProperty() { + return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR); + } + }, { + key: "isClassMethod", + value: function isClassMethod() { + return this.match(types.parenL); + } + }, { + key: "isNonstaticConstructor", + value: function isNonstaticConstructor(method) { + return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor"); + } + }, { + key: "parseClassBody", + value: function parseClassBody(constructorAllowsSuper) { + var _this44 = this; + + this.state.classLevel++; + var state = { + hadConstructor: false + }; + var decorators = []; + var classBody = this.startNode(); + classBody.body = []; + this.expect(types.braceL); + this.withTopicForbiddingContext(function () { + while (!_this44.eat(types.braceR)) { + if (_this44.eat(types.semi)) { + if (decorators.length > 0) { + throw _this44.raise(_this44.state.lastTokEnd, "Decorators must not be followed by a semicolon"); + } - return true; -} + continue; + } -function isValidIdentifier(name) { - if (typeof name !== "string" || _esutils2.default.keyword.isReservedWordES6(name, true)) { - return false; - } else if (name === "await") { - return false; - } else { - return _esutils2.default.keyword.isIdentifierNameES6(name); - } -} + if (_this44.match(types.at)) { + decorators.push(_this44.parseDecorator()); + continue; + } -function isLet(node) { - return t.isVariableDeclaration(node) && (node.kind !== "var" || node[_constants.BLOCK_SCOPED_SYMBOL]); -} + var member = _this44.startNode(); -function isBlockScoped(node) { - return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node); -} + if (decorators.length) { + member.decorators = decorators; -function isVar(node) { - return t.isVariableDeclaration(node, { kind: "var" }) && !node[_constants.BLOCK_SCOPED_SYMBOL]; -} + _this44.resetStartLocationFromNode(member, decorators[0]); -function isSpecifierDefault(specifier) { - return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" }); -} + decorators = []; + } -function isScope(node, parent) { - if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) { - return false; - } + _this44.parseClassMember(classBody, member, state, constructorAllowsSuper); - return t.isScopable(node); -} + if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { + _this44.raise(member.start, "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?"); + } + } + }); -function isImmutable(node) { - if (t.isType(node.type, "Immutable")) return true; + if (decorators.length) { + throw this.raise(this.state.start, "You have trailing decorators with no method"); + } - if (t.isIdentifier(node)) { - if (node.name === "undefined") { - return true; - } else { - return false; + this.state.classLevel--; + return this.finishNode(classBody, "ClassBody"); } - } - - return false; -} + }, { + key: "parseClassMember", + value: function parseClassMember(classBody, member, state, constructorAllowsSuper) { + var isStatic = false; + var containsEsc = this.state.containsEsc; -function isNodesEquivalent(a, b) { - if ((typeof a === "undefined" ? "undefined" : (0, _typeof3.default)(a)) !== "object" || (typeof a === "undefined" ? "undefined" : (0, _typeof3.default)(a)) !== "object" || a == null || b == null) { - return a === b; - } - - if (a.type !== b.type) { - return false; - } + if (this.match(types.name) && this.state.value === "static") { + var key = this.parseIdentifier(true); - var fields = (0, _keys2.default)(t.NODE_FIELDS[a.type] || a.type); + if (this.isClassMethod()) { + var method = member; + method.kind = "method"; + method.computed = false; + method.key = key; + method.static = false; + this.pushClassMethod(classBody, method, false, false, false, false); + return; + } else if (this.isClassProperty()) { + var prop = member; + prop.computed = false; + prop.key = key; + prop.static = false; + classBody.body.push(this.parseClassProperty(prop)); + return; + } else if (containsEsc) { + throw this.unexpected(); + } - for (var _iterator2 = fields, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + isStatic = true; + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + this.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper); } + }, { + key: "parseClassMemberWithIsStatic", + value: function parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) { + var publicMethod = member; + var privateMethod = member; + var publicProp = member; + var privateProp = member; + var method = publicMethod; + var publicMember = publicMethod; + member.static = isStatic; - var field = _ref2; - - if ((0, _typeof3.default)(a[field]) !== (0, _typeof3.default)(b[field])) { - return false; - } + if (this.eat(types.star)) { + method.kind = "method"; + this.parseClassPropertyName(method); - if (Array.isArray(a[field])) { - if (!Array.isArray(b[field])) { - return false; - } - if (a[field].length !== b[field].length) { - return false; - } + if (method.key.type === "PrivateName") { + this.pushClassPrivateMethod(classBody, privateMethod, true, false); + return; + } - for (var i = 0; i < a[field].length; i++) { - if (!isNodesEquivalent(a[field][i], b[field][i])) { - return false; + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(publicMethod.key.start, "Constructor can't be a generator"); } - } - continue; - } - if (!isNodesEquivalent(a[field], b[field])) { - return false; - } - } + this.pushClassMethod(classBody, publicMethod, true, false, false, false); + return; + } - return true; -} -},{"./constants":140,"./index":151,"./retrievers":153,"babel-runtime/core-js/get-iterator":95,"babel-runtime/core-js/object/keys":102,"babel-runtime/helpers/typeof":113,"esutils":287}],155:[function(require,module,exports){ -'use strict'; + var containsEsc = this.state.containsEsc; + var key = this.parseClassPropertyName(member); + var isPrivate = key.type === "PrivateName"; + var isSimple = key.type === "Identifier"; + var maybeQuestionTokenStart = this.state.start; + this.parsePostMemberNameModifiers(publicMember); -Object.defineProperty(exports, '__esModule', { value: true }); + if (this.isClassMethod()) { + method.kind = "method"; -/* eslint max-len: 0 */ + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + return; + } -// This is a trick taken from Esprima. It turns out that, on -// non-Chrome browsers, to check whether a string is in a set, a -// predicate containing a big ugly `switch` statement is faster than -// a regular expression, and on Chrome the two are about on par. -// This function uses `eval` (non-lexical) to produce such a -// predicate from a space-separated string of words. -// -// It starts by sorting the words by length. + var isConstructor = this.isNonstaticConstructor(publicMethod); + var allowsDirectSuper = false; -function makePredicate(words) { - words = words.split(" "); - return function (str) { - return words.indexOf(str) >= 0; - }; -} + if (isConstructor) { + publicMethod.kind = "constructor"; -// Reserved word lists for various dialects of the language + if (state.hadConstructor && !this.hasPlugin("typescript")) { + this.raise(key.start, "Duplicate constructor in the same class"); + } -var reservedWords = { - 6: makePredicate("enum await"), - strict: makePredicate("implements interface let package private protected public static yield"), - strictBind: makePredicate("eval arguments") -}; + state.hadConstructor = true; + allowsDirectSuper = constructorAllowsSuper; + } -// And the keywords + this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); + } else if (this.isClassProperty()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) { + var isGenerator = this.eat(types.star); -var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super"); + if (publicMember.optional) { + this.unexpected(maybeQuestionTokenStart); + } -// ## Character categories + method.kind = "method"; + this.parseClassPropertyName(method); -// Big ugly regular expressions that match characters in the -// whitespace, identifier, and identifier-start categories. These -// are only applied when a character is found to actually have a -// code point above 128. -// Generated by `bin/generate-identifier-regex.js`. + if (method.key.type === "PrivateName") { + this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(publicMethod.key.start, "Constructor can't be an async function"); + } -var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; -var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA900-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F"; + this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); + } + } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) { + method.kind = key.name; + this.parseClassPropertyName(publicMethod); -var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + if (method.key.type === "PrivateName") { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(publicMethod.key.start, "Constructor can't have get/set modifier"); + } -nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + this.pushClassMethod(classBody, publicMethod, false, false, false, false); + } -// These are a run-length and offset encoded representation of the -// >0xffff code points that are a valid part of identifiers. The -// offset starts at 0x10000, and each pair of numbers represents an -// offset to the next range, and then a size of the range. They were -// generated by `bin/generate-identifier-regex.js`. -// eslint-disable-next-line comma-spacing -var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 785, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 54, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 86, 25, 391, 63, 32, 0, 449, 56, 264, 8, 2, 36, 18, 0, 50, 29, 881, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 65, 0, 32, 6124, 20, 754, 9486, 1, 3071, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 60, 67, 1213, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 3, 5761, 10591, 541]; -// eslint-disable-next-line comma-spacing -var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 10, 2, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 87, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 423, 9, 838, 7, 2, 7, 17, 9, 57, 21, 2, 13, 19882, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 2214, 6, 110, 6, 6, 9, 792487, 239]; - -// This has a complexity linear to the value of the code. The -// assumption is that looking up astral identifier characters is -// rare. -function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) return false; + this.checkGetterSetterParams(publicMethod); + } else if (this.isLineTerminator()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else { + this.unexpected(); + } + } + }, { + key: "parseClassPropertyName", + value: function parseClassPropertyName(member) { + var key = this.parsePropertyName(member); - pos += set[i + 1]; - if (pos >= code) return true; - } -} + if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) { + this.raise(key.start, "Classes may not have static property named prototype"); + } -// Test whether a given character code starts an identifier. + if (key.type === "PrivateName" && key.id.name === "constructor") { + this.raise(key.start, "Classes may not have a private field named '#constructor'"); + } -function isIdentifierStart(code) { - if (code < 65) return code === 36; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); - return isInAstralSet(code, astralIdentifierStartCodes); -} + return key; + } + }, { + key: "pushClassProperty", + value: function pushClassProperty(classBody, prop) { + if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) { + this.raise(prop.key.start, "Classes may not have a field named 'constructor'"); + } + + classBody.body.push(this.parseClassProperty(prop)); + } + }, { + key: "pushClassPrivateProperty", + value: function pushClassPrivateProperty(classBody, prop) { + this.expectPlugin("classPrivateProperties", prop.key.start); + classBody.body.push(this.parseClassPrivateProperty(prop)); + } + }, { + key: "pushClassMethod", + value: function pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true)); + } + }, { + key: "pushClassPrivateMethod", + value: function pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + this.expectPlugin("classPrivateMethods", method.key.start); + classBody.body.push(this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true)); + } + }, { + key: "parsePostMemberNameModifiers", + value: function parsePostMemberNameModifiers(methodOrProp) {} + }, { + key: "parseAccessModifier", + value: function parseAccessModifier() { + return undefined; + } + }, { + key: "parseClassPrivateProperty", + value: function parseClassPrivateProperty(node) { + this.state.inClassProperty = true; + this.scope.enter(SCOPE_CLASS | SCOPE_SUPER); + node.value = this.eat(types.eq) ? this.parseMaybeAssign() : null; + this.semicolon(); + this.state.inClassProperty = false; + this.scope.exit(); + return this.finishNode(node, "ClassPrivateProperty"); + } + }, { + key: "parseClassProperty", + value: function parseClassProperty(node) { + if (!node.typeAnnotation) { + this.expectPlugin("classProperties"); + } + + this.state.inClassProperty = true; + this.scope.enter(SCOPE_CLASS | SCOPE_SUPER); + + if (this.match(types.eq)) { + this.expectPlugin("classProperties"); + this.next(); + node.value = this.parseMaybeAssign(); + } else { + node.value = null; + } -// Test whether a given character is part of an identifier. + this.semicolon(); + this.state.inClassProperty = false; + this.scope.exit(); + return this.finishNode(node, "ClassProperty"); + } + }, { + key: "parseClassId", + value: function parseClassId(node, isStatement, optionalId) { + var bindingType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : BIND_CLASS; -function isIdentifierChar(code) { - if (code < 48) return code === 36; - if (code < 58) return true; - if (code < 65) return false; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); -} + if (this.match(types.name)) { + node.id = this.parseIdentifier(); -// A second optional argument can be given to further configure -var defaultOptions = { - // Source type ("script" or "module") for different semantics - sourceType: "script", - // Source filename. - sourceFilename: undefined, - // Line from which to start counting source. Useful for - // integration with other tools. - startLine: 1, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program. - allowImportExportEverywhere: false, - // TODO - allowSuperOutsideMethod: false, - // An array of plugins to enable - plugins: [], - // TODO - strictMode: null -}; + if (isStatement) { + this.checkLVal(node.id, bindingType, undefined, "class name"); + } + } else { + if (optionalId || !isStatement) { + node.id = null; + } else { + this.unexpected(null, "A class name is required"); + } + } + } + }, { + key: "parseClassSuper", + value: function parseClassSuper(node) { + node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; + } + }, { + key: "parseExport", + value: function parseExport(node) { + var hasDefault = this.maybeParseExportDefaultSpecifier(node); + var parseAfterDefault = !hasDefault || this.eat(types.comma); + var hasStar = parseAfterDefault && this.eatExportStar(node); + var hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node); + var parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma)); + var isFromRequired = hasDefault || hasStar; -// Interpret and default an options object + if (hasStar && !hasNamespace) { + if (hasDefault) this.unexpected(); + this.parseExportFrom(node, true); + return this.finishNode(node, "ExportAllDeclaration"); + } -function getOptions(opts) { - var options = {}; - for (var key in defaultOptions) { - options[key] = opts && key in opts ? opts[key] : defaultOptions[key]; - } - return options; -} + var hasSpecifiers = this.maybeParseExportNamedSpecifiers(node); -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { - return typeof obj; -} : function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; -}; + if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) { + throw this.unexpected(null, types.braceL); + } + var hasDeclaration; + if (isFromRequired || hasSpecifiers) { + hasDeclaration = false; + this.parseExportFrom(node, isFromRequired); + } else { + hasDeclaration = this.maybeParseExportDeclaration(node); + } + if (isFromRequired || hasSpecifiers || hasDeclaration) { + this.checkExport(node, true, false, !!node.source); + return this.finishNode(node, "ExportNamedDeclaration"); + } + if (this.eat(types._default)) { + node.declaration = this.parseExportDefaultExpression(); + this.checkExport(node, true, true); + return this.finishNode(node, "ExportDefaultDeclaration"); + } + throw this.unexpected(null, types.braceL); + } + }, { + key: "eatExportStar", + value: function eatExportStar(node) { + return this.eat(types.star); + } + }, { + key: "maybeParseExportDefaultSpecifier", + value: function maybeParseExportDefaultSpecifier(node) { + if (this.isExportDefaultSpecifier()) { + this.expectPlugin("exportDefaultFrom"); + var specifier = this.startNode(); + specifier.exported = this.parseIdentifier(true); + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return true; + } + return false; + } + }, { + key: "maybeParseExportNamespaceSpecifier", + value: function maybeParseExportNamespaceSpecifier(node) { + if (this.isContextual("as")) { + if (!node.specifiers) node.specifiers = []; + var specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc); + this.next(); + specifier.exported = this.parseIdentifier(true); + node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); + return true; + } + return false; + } + }, { + key: "maybeParseExportNamedSpecifiers", + value: function maybeParseExportNamedSpecifiers(node) { + if (this.match(types.braceL)) { + var _node$specifiers2; + if (!node.specifiers) node.specifiers = []; + (_node$specifiers2 = node.specifiers).push.apply(_node$specifiers2, _toConsumableArray(this.parseExportSpecifiers())); + node.source = null; + node.declaration = null; + return true; + } -var classCallCheck = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; + return false; + } + }, { + key: "maybeParseExportDeclaration", + value: function maybeParseExportDeclaration(node) { + if (this.shouldParseExportDeclaration()) { + if (this.isContextual("async")) { + var next = this.nextTokenStart(); + if (!this.isUnparsedContextual(next, "function")) { + this.unexpected(next, "Unexpected token, expected \"function\""); + } + } + node.specifiers = []; + node.source = null; + node.declaration = this.parseExportDeclaration(node); + return true; + } + return false; + } + }, { + key: "isAsyncFunction", + value: function isAsyncFunction() { + if (!this.isContextual("async")) return false; + var next = this.nextTokenStart(); + return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function"); + } + }, { + key: "parseExportDefaultExpression", + value: function parseExportDefaultExpression() { + var expr = this.startNode(); + var isAsync = this.isAsyncFunction(); + if (this.match(types._function) || isAsync) { + this.next(); + if (isAsync) { + this.next(); + } + return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync); + } else if (this.match(types._class)) { + return this.parseClass(expr, true, true); + } else if (this.match(types.at)) { + if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) { + this.raise(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax"); + } + this.parseDecorators(false); + return this.parseClass(expr, true, true); + } else if (this.match(types._const) || this.match(types._var) || this.isLet()) { + throw this.raise(this.state.start, "Only expressions, functions or classes are allowed as the `default` export."); + } else { + var res = this.parseMaybeAssign(); + this.semicolon(); + return res; + } + } + }, { + key: "parseExportDeclaration", + value: function parseExportDeclaration(node) { + return this.parseStatement(null); + } + }, { + key: "isExportDefaultSpecifier", + value: function isExportDefaultSpecifier() { + if (this.match(types.name)) { + return this.state.value !== "async" && this.state.value !== "let"; + } + if (!this.match(types._default)) { + return false; + } + var next = this.nextTokenStart(); + return this.input.charCodeAt(next) === 44 || this.isUnparsedContextual(next, "from"); + } + }, { + key: "parseExportFrom", + value: function parseExportFrom(node, expect) { + if (this.eatContextual("from")) { + node.source = this.parseImportSource(); + this.checkExport(node); + } else { + if (expect) { + this.unexpected(); + } else { + node.source = null; + } + } + this.semicolon(); + } + }, { + key: "shouldParseExportDeclaration", + value: function shouldParseExportDeclaration() { + if (this.match(types.at)) { + this.expectOnePlugin(["decorators", "decorators-legacy"]); -var inherits = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); - } + if (this.hasPlugin("decorators")) { + if (this.getPluginOption("decorators", "decoratorsBeforeExport")) { + this.unexpected(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax"); + } else { + return true; + } + } + } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true + return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction(); } - }); - if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; -}; + }, { + key: "checkExport", + value: function checkExport(node, checkNames, isDefault, isFrom) { + if (checkNames) { + if (isDefault) { + this.checkDuplicateExports(node, "default"); + } else if (node.specifiers && node.specifiers.length) { + for (var _i3 = 0, _node$specifiers = node.specifiers; _i3 < _node$specifiers.length; _i3++) { + var specifier = _node$specifiers[_i3]; + this.checkDuplicateExports(specifier, specifier.exported.name); + if (!isFrom && specifier.local) { + this.checkReservedWord(specifier.local.name, specifier.local.start, true, false); + this.scope.checkLocalExport(specifier.local); + } + } + } else if (node.declaration) { + if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") { + var id = node.declaration.id; + if (!id) throw new Error("Assertion failure"); + this.checkDuplicateExports(node, id.name); + } else if (node.declaration.type === "VariableDeclaration") { + for (var _i4 = 0, _node$declaration$dec = node.declaration.declarations; _i4 < _node$declaration$dec.length; _i4++) { + var declaration = _node$declaration$dec[_i4]; + this.checkDeclaration(declaration.id); + } + } + } + } + var currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; + if (currentContextDecorators.length) { + var isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression"); + if (!node.declaration || !isClass) { + throw this.raise(node.start, "You can only use decorators on an export when exporting a class"); + } + this.takeDecorators(node.declaration); + } + } + }, { + key: "checkDeclaration", + value: function checkDeclaration(node) { + if (node.type === "Identifier") { + this.checkDuplicateExports(node, node.name); + } else if (node.type === "ObjectPattern") { + for (var _i5 = 0, _node$properties = node.properties; _i5 < _node$properties.length; _i5++) { + var prop = _node$properties[_i5]; + this.checkDeclaration(prop); + } + } else if (node.type === "ArrayPattern") { + for (var _i6 = 0, _node$elements = node.elements; _i6 < _node$elements.length; _i6++) { + var elem = _node$elements[_i6]; + if (elem) { + this.checkDeclaration(elem); + } + } + } else if (node.type === "ObjectProperty") { + this.checkDeclaration(node.value); + } else if (node.type === "RestElement") { + this.checkDeclaration(node.argument); + } else if (node.type === "AssignmentPattern") { + this.checkDeclaration(node.left); + } + } + }, { + key: "checkDuplicateExports", + value: function checkDuplicateExports(node, name) { + if (this.state.exportedIdentifiers.indexOf(name) > -1) { + this.raise(node.start, name === "default" ? "Only one default export allowed per module." : "`".concat(name, "` has already been exported. Exported identifiers must be unique.")); + } + this.state.exportedIdentifiers.push(name); + } + }, { + key: "parseExportSpecifiers", + value: function parseExportSpecifiers() { + var nodes = []; + var first = true; + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (first) { + first = false; + } else { + this.expect(types.comma); + if (this.eat(types.braceR)) break; + } + var node = this.startNode(); + node.local = this.parseIdentifier(true); + node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone(); + nodes.push(this.finishNode(node, "ExportSpecifier")); + } + + return nodes; + } + }, { + key: "parseImport", + value: function parseImport(node) { + node.specifiers = []; + + if (!this.match(types.string)) { + var hasDefault = this.maybeParseDefaultImportSpecifier(node); + var parseNext = !hasDefault || this.eat(types.comma); + var hasStar = parseNext && this.maybeParseStarImportSpecifier(node); + if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node); + this.expectContextual("from"); + } + + node.source = this.parseImportSource(); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + }, { + key: "parseImportSource", + value: function parseImportSource() { + if (!this.match(types.string)) this.unexpected(); + return this.parseExprAtom(); + } + }, { + key: "shouldParseDefaultImport", + value: function shouldParseDefaultImport(node) { + return this.match(types.name); + } + }, { + key: "parseImportSpecifierLocal", + value: function parseImportSpecifierLocal(node, specifier, type, contextDescription) { + specifier.local = this.parseIdentifier(); + this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription); + node.specifiers.push(this.finishNode(specifier, type)); + } + }, { + key: "maybeParseDefaultImportSpecifier", + value: function maybeParseDefaultImportSpecifier(node) { + if (this.shouldParseDefaultImport(node)) { + this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier"); + return true; + } + return false; + } + }, { + key: "maybeParseStarImportSpecifier", + value: function maybeParseStarImportSpecifier(node) { + if (this.match(types.star)) { + var specifier = this.startNode(); + this.next(); + this.expectContextual("as"); + this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier"); + return true; + } -var possibleConstructorReturn = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } + return false; + } + }, { + key: "parseNamedImportSpecifiers", + value: function parseNamedImportSpecifiers(node) { + var first = true; + this.expect(types.braceL); - return call && (typeof call === "object" || typeof call === "function") ? call : self; -}; + while (!this.eat(types.braceR)) { + if (first) { + first = false; + } else { + if (this.eat(types.colon)) { + throw this.raise(this.state.start, "ES2015 named imports do not destructure. " + "Use another statement for destructuring after the import."); + } -// ## Token types + this.expect(types.comma); + if (this.eat(types.braceR)) break; + } -// The assignment of fine-grained, information-carrying type objects -// allows the tokenizer to store the information it has about a -// token in a way that is very cheap for the parser to look up. + this.parseImportSpecifier(node); + } + } + }, { + key: "parseImportSpecifier", + value: function parseImportSpecifier(node) { + var specifier = this.startNode(); + specifier.imported = this.parseIdentifier(true); -// All token type variables start with an underscore, to make them -// easy to recognize. + if (this.eatContextual("as")) { + specifier.local = this.parseIdentifier(); + } else { + this.checkReservedWord(specifier.imported.name, specifier.start, true, true); + specifier.local = specifier.imported.__clone(); + } -// The `beforeExpr` property is used to disambiguate between regular -// expressions and divisions. It is set on all token types that can -// be followed by an expression (thus, a slash after them would be a -// regular expression). -// -// `isLoop` marks a keyword as starting a loop, which is important -// to know when parsing a label, in order to allow or disallow -// continue jumps to that label. + this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier"); + node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); + } + }]); -var beforeExpr = true; -var startsExpr = true; -var isLoop = true; -var isAssign = true; -var prefix = true; -var postfix = true; + return StatementParser; +}(ExpressionParser); -var TokenType = function TokenType(label) { - var conf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - classCallCheck(this, TokenType); +var Parser = +/*#__PURE__*/ +function (_StatementParser) { + _inherits(Parser, _StatementParser); - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.rightAssociative = !!conf.rightAssociative; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop || null; - this.updateContext = null; -}; + function Parser(options, input) { + var _this45; -var KeywordTokenType = function (_TokenType) { - inherits(KeywordTokenType, _TokenType); + _classCallCheck(this, Parser); - function KeywordTokenType(name) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - classCallCheck(this, KeywordTokenType); + options = getOptions(options); + _this45 = _possibleConstructorReturn(this, _getPrototypeOf(Parser).call(this, options, input)); + + var ScopeHandler = _this45.getScopeHandler(); + + _this45.options = options; + _this45.inModule = _this45.options.sourceType === "module"; + _this45.scope = new ScopeHandler(_this45.raise.bind(_assertThisInitialized(_this45)), _this45.inModule); + _this45.plugins = pluginsMap(_this45.options.plugins); + _this45.filename = options.sourceFilename; + return _this45; + } + + _createClass(Parser, [{ + key: "getScopeHandler", + value: function getScopeHandler() { + return ScopeHandler; + } + }, { + key: "parse", + value: function parse() { + this.scope.enter(SCOPE_PROGRAM); + var file = this.startNode(); + var program = this.startNode(); + this.nextToken(); + file.errors = null; + this.parseTopLevel(file, program); + file.errors = this.state.errors; + return file; + } + }]); - options.keyword = name; + return Parser; +}(StatementParser); - return possibleConstructorReturn(this, _TokenType.call(this, name, options)); - } +function pluginsMap(plugins) { + var pluginMap = new Map(); - return KeywordTokenType; -}(TokenType); + for (var _i = 0; _i < plugins.length; _i++) { + var plugin = plugins[_i]; -var BinopTokenType = function (_TokenType2) { - inherits(BinopTokenType, _TokenType2); + var _ref15 = Array.isArray(plugin) ? plugin : [plugin, {}], + _ref16 = _slicedToArray(_ref15, 2), + name = _ref16[0], + options = _ref16[1]; - function BinopTokenType(name, prec) { - classCallCheck(this, BinopTokenType); - return possibleConstructorReturn(this, _TokenType2.call(this, name, { beforeExpr: beforeExpr, binop: prec })); + if (!pluginMap.has(name)) pluginMap.set(name, options || {}); } - return BinopTokenType; -}(TokenType); - -var types = { - num: new TokenType("num", { startsExpr: startsExpr }), - regexp: new TokenType("regexp", { startsExpr: startsExpr }), - string: new TokenType("string", { startsExpr: startsExpr }), - name: new TokenType("name", { startsExpr: startsExpr }), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - bracketR: new TokenType("]"), - braceL: new TokenType("{", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - braceBarL: new TokenType("{|", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - braceR: new TokenType("}"), - braceBarR: new TokenType("|}"), - parenL: new TokenType("(", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - parenR: new TokenType(")"), - comma: new TokenType(",", { beforeExpr: beforeExpr }), - semi: new TokenType(";", { beforeExpr: beforeExpr }), - colon: new TokenType(":", { beforeExpr: beforeExpr }), - doubleColon: new TokenType("::", { beforeExpr: beforeExpr }), - dot: new TokenType("."), - question: new TokenType("?", { beforeExpr: beforeExpr }), - arrow: new TokenType("=>", { beforeExpr: beforeExpr }), - template: new TokenType("template"), - ellipsis: new TokenType("...", { beforeExpr: beforeExpr }), - backQuote: new TokenType("`", { startsExpr: startsExpr }), - dollarBraceL: new TokenType("${", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - at: new TokenType("@"), - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - eq: new TokenType("=", { beforeExpr: beforeExpr, isAssign: isAssign }), - assign: new TokenType("_=", { beforeExpr: beforeExpr, isAssign: isAssign }), - incDec: new TokenType("++/--", { prefix: prefix, postfix: postfix, startsExpr: startsExpr }), - prefix: new TokenType("prefix", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - logicalOR: new BinopTokenType("||", 1), - logicalAND: new BinopTokenType("&&", 2), - bitwiseOR: new BinopTokenType("|", 3), - bitwiseXOR: new BinopTokenType("^", 4), - bitwiseAND: new BinopTokenType("&", 5), - equality: new BinopTokenType("==/!=", 6), - relational: new BinopTokenType("", 7), - bitShift: new BinopTokenType("<>", 8), - plusMin: new TokenType("+/-", { beforeExpr: beforeExpr, binop: 9, prefix: prefix, startsExpr: startsExpr }), - modulo: new BinopTokenType("%", 10), - star: new BinopTokenType("*", 10), - slash: new BinopTokenType("/", 10), - exponent: new TokenType("**", { beforeExpr: beforeExpr, binop: 11, rightAssociative: true }) -}; - -var keywords = { - "break": new KeywordTokenType("break"), - "case": new KeywordTokenType("case", { beforeExpr: beforeExpr }), - "catch": new KeywordTokenType("catch"), - "continue": new KeywordTokenType("continue"), - "debugger": new KeywordTokenType("debugger"), - "default": new KeywordTokenType("default", { beforeExpr: beforeExpr }), - "do": new KeywordTokenType("do", { isLoop: isLoop, beforeExpr: beforeExpr }), - "else": new KeywordTokenType("else", { beforeExpr: beforeExpr }), - "finally": new KeywordTokenType("finally"), - "for": new KeywordTokenType("for", { isLoop: isLoop }), - "function": new KeywordTokenType("function", { startsExpr: startsExpr }), - "if": new KeywordTokenType("if"), - "return": new KeywordTokenType("return", { beforeExpr: beforeExpr }), - "switch": new KeywordTokenType("switch"), - "throw": new KeywordTokenType("throw", { beforeExpr: beforeExpr }), - "try": new KeywordTokenType("try"), - "var": new KeywordTokenType("var"), - "let": new KeywordTokenType("let"), - "const": new KeywordTokenType("const"), - "while": new KeywordTokenType("while", { isLoop: isLoop }), - "with": new KeywordTokenType("with"), - "new": new KeywordTokenType("new", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - "this": new KeywordTokenType("this", { startsExpr: startsExpr }), - "super": new KeywordTokenType("super", { startsExpr: startsExpr }), - "class": new KeywordTokenType("class"), - "extends": new KeywordTokenType("extends", { beforeExpr: beforeExpr }), - "export": new KeywordTokenType("export"), - "import": new KeywordTokenType("import", { startsExpr: startsExpr }), - "yield": new KeywordTokenType("yield", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - "null": new KeywordTokenType("null", { startsExpr: startsExpr }), - "true": new KeywordTokenType("true", { startsExpr: startsExpr }), - "false": new KeywordTokenType("false", { startsExpr: startsExpr }), - "in": new KeywordTokenType("in", { beforeExpr: beforeExpr, binop: 7 }), - "instanceof": new KeywordTokenType("instanceof", { beforeExpr: beforeExpr, binop: 7 }), - "typeof": new KeywordTokenType("typeof", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - "void": new KeywordTokenType("void", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - "delete": new KeywordTokenType("delete", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }) -}; - -// Map keyword names to token types. -Object.keys(keywords).forEach(function (name) { - types["_" + name] = keywords[name]; -}); - -// Matches a whole line break (where CRLF is considered a single -// line break). Used to count lines. - -var lineBreak = /\r\n?|\n|\u2028|\u2029/; -var lineBreakG = new RegExp(lineBreak.source, "g"); - -function isNewLine(code) { - return code === 10 || code === 13 || code === 0x2028 || code === 0x2029; + return pluginMap; } -var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - -// The algorithm used to determine whether a regexp can appear at a -// given point in the program is loosely based on sweet.js' approach. -// See https://github.com/mozilla/sweet.js/wiki/design - -var TokContext = function TokContext(token, isExpr, preserveSpace, override) { - classCallCheck(this, TokContext); +function parse(input, options) { + if (options && options.sourceType === "unambiguous") { + options = Object.assign({}, options); - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; -}; + try { + options.sourceType = "module"; + var parser = getParser(options, input); + var ast = parser.parse(); -var types$1 = { - braceStatement: new TokContext("{", false), - braceExpression: new TokContext("{", true), - templateQuasi: new TokContext("${", true), - parenStatement: new TokContext("(", false), - parenExpression: new TokContext("(", true), - template: new TokContext("`", true, true, function (p) { - return p.readTmplToken(); - }), - functionExpression: new TokContext("function", true) -}; + if (parser.sawUnambiguousESM) { + return ast; + } -// Token-specific context update code + if (parser.ambiguousScriptDifferentAst) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused) {} + } else { + ast.program.sourceType = "script"; + } -types.parenR.updateContext = types.braceR.updateContext = function () { - if (this.state.context.length === 1) { - this.state.exprAllowed = true; - return; - } + return ast; + } catch (moduleError) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused2) {} - var out = this.state.context.pop(); - if (out === types$1.braceStatement && this.curContext() === types$1.functionExpression) { - this.state.context.pop(); - this.state.exprAllowed = false; - } else if (out === types$1.templateQuasi) { - this.state.exprAllowed = true; + throw moduleError; + } } else { - this.state.exprAllowed = !out.isExpr; + return getParser(options, input).parse(); } -}; +} -types.name.updateContext = function (prevType) { - this.state.exprAllowed = false; +function parseExpression(input, options) { + var parser = getParser(options, input); - if (prevType === types._let || prevType === types._const || prevType === types._var) { - if (lineBreak.test(this.input.slice(this.state.end))) { - this.state.exprAllowed = true; - } + if (parser.options.strictMode) { + parser.state.strict = true; } -}; - -types.braceL.updateContext = function (prevType) { - this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression); - this.state.exprAllowed = true; -}; - -types.dollarBraceL.updateContext = function () { - this.state.context.push(types$1.templateQuasi); - this.state.exprAllowed = true; -}; - -types.parenL.updateContext = function (prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression); - this.state.exprAllowed = true; -}; - -types.incDec.updateContext = function () { - // tokExprAllowed stays unchanged -}; -types._function.updateContext = function () { - if (this.curContext() !== types$1.braceStatement) { - this.state.context.push(types$1.functionExpression); - } + return parser.getExpression(); +} - this.state.exprAllowed = false; -}; +function getParser(options, input) { + var cls = Parser; -types.backQuote.updateContext = function () { - if (this.curContext() === types$1.template) { - this.state.context.pop(); - } else { - this.state.context.push(types$1.template); + if (options && options.plugins) { + validatePlugins(options.plugins); + cls = getParserClass(options.plugins); } - this.state.exprAllowed = false; -}; -// These are used when `options.locations` is on, for the -// `startLoc` and `endLoc` properties. - -var Position = function Position(line, col) { - classCallCheck(this, Position); - - this.line = line; - this.column = col; -}; + return new cls(options, input); +} -var SourceLocation = function SourceLocation(start, end) { - classCallCheck(this, SourceLocation); +var parserClassCache = {}; - this.start = start; - this.end = end; -}; +function getParserClass(pluginsFromOptions) { + var pluginList = mixinPluginNames.filter(function (name) { + return hasPlugin(pluginsFromOptions, name); + }); + var key = pluginList.join("/"); + var cls = parserClassCache[key]; -// The `getLineInfo` function is mostly useful when the -// `locations` option is off (for performance reasons) and you -// want to find the line/column position for a given character -// offset. `input` should be the code string that the offset refers -// into. + if (!cls) { + cls = Parser; -function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur; - var match = lineBreakG.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else { - return new Position(line, offset - cur); + for (var _i = 0; _i < pluginList.length; _i++) { + var plugin = pluginList[_i]; + cls = mixinPlugins[plugin](cls); } - } -} -var State = function () { - function State() { - classCallCheck(this, State); + parserClassCache[key] = cls; } - State.prototype.init = function init(options, input) { - this.strict = options.strictMode === false ? false : options.sourceType === "module"; - - this.input = input; - - this.potentialArrowAt = -1; - - this.inMethod = this.inFunction = this.inGenerator = this.inAsync = this.inPropertyName = this.inType = this.inClassProperty = this.noAnonFunctionType = false; - - this.labels = []; - - this.decorators = []; - - this.tokens = []; - - this.comments = []; - - this.trailingComments = []; - this.leadingComments = []; - this.commentStack = []; - - this.pos = this.lineStart = 0; - this.curLine = options.startLine; + return cls; +} - this.type = types.eof; - this.value = null; - this.start = this.end = this.pos; - this.startLoc = this.endLoc = this.curPosition(); +exports.parse = parse; +exports.parseExpression = parseExpression; +exports.tokTypes = types; - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; +},{}],90:[function(require,module,exports){ +"use strict"; - this.context = [types$1.braceStatement]; - this.exprAllowed = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +var _core = require("@babel/core"); + +var buildForAwait = (0, _core.template)("\n async function wrapper() {\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY;\n try {\n for (\n var ITERATOR_KEY = GET_ITERATOR(OBJECT), STEP_KEY, STEP_VALUE;\n (\n STEP_KEY = await ITERATOR_KEY.next(),\n ITERATOR_COMPLETION = STEP_KEY.done,\n STEP_VALUE = await STEP_KEY.value,\n !ITERATOR_COMPLETION\n );\n ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return != null) {\n await ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n }\n"); + +function _default(path, _ref) { + var getAsyncIterator = _ref.getAsyncIterator; + var node = path.node, + scope = path.scope, + parent = path.parent; + var stepKey = scope.generateUidIdentifier("step"); + var stepValue = scope.generateUidIdentifier("value"); + var left = node.left; + var declar; + + if (_core.types.isIdentifier(left) || _core.types.isPattern(left) || _core.types.isMemberExpression(left)) { + declar = _core.types.expressionStatement(_core.types.assignmentExpression("=", left, stepValue)); + } else if (_core.types.isVariableDeclaration(left)) { + declar = _core.types.variableDeclaration(left.kind, [_core.types.variableDeclarator(left.declarations[0].id, stepValue)]); + } + + var template = buildForAwait({ + ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), + ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), + ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), + ITERATOR_KEY: scope.generateUidIdentifier("iterator"), + GET_ITERATOR: getAsyncIterator, + OBJECT: node.right, + STEP_VALUE: stepValue, + STEP_KEY: stepKey + }); + template = template.body.body; - this.containsEsc = this.containsOctal = false; - this.octalPosition = null; + var isLabeledParent = _core.types.isLabeledStatement(parent); - this.invalidTemplateEscapePosition = null; + var tryBody = template[3].block.body; + var loop = tryBody[0]; - this.exportedIdentifiers = []; + if (isLabeledParent) { + tryBody[0] = _core.types.labeledStatement(parent.label, loop); + } - return this; + return { + replaceParent: isLabeledParent, + node: template, + declar: declar, + loop: loop }; +} - // TODO - - - // TODO - - - // Used to signify the start of a potential arrow function - - - // Flags to track whether we are in a function, a generator. - - - // Labels in scope. - - - // Leading decorators. +},{"@babel/core":19}],91:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - // Token store. +var _helperPluginUtils = require("@babel/helper-plugin-utils"); +var _helperRemapAsyncToGenerator = _interopRequireDefault(require("@babel/helper-remap-async-to-generator")); - // Comment store. +var _pluginSyntaxAsyncGenerators = _interopRequireDefault(require("@babel/plugin-syntax-async-generators")); +var _core = require("@babel/core"); - // Comment attachment store +var _forAwait = _interopRequireDefault(require("./for-await")); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} - // The current position of the tokenizer in the input. +var _default = (0, _helperPluginUtils.declare)(function (api) { + api.assertVersion(7); + var yieldStarVisitor = { + Function: function Function(path) { + path.skip(); + }, + YieldExpression: function YieldExpression(_ref, state) { + var node = _ref.node; + if (!node.delegate) return; + var callee = state.addHelper("asyncGeneratorDelegate"); + node.argument = _core.types.callExpression(callee, [_core.types.callExpression(state.addHelper("asyncIterator"), [node.argument]), state.addHelper("awaitAsyncGenerator")]); + } + }; + var forAwaitVisitor = { + Function: function Function(path) { + path.skip(); + }, + ForOfStatement: function ForOfStatement(path, _ref2) { + var file = _ref2.file; + var node = path.node; + if (!node.await) return; + var build = (0, _forAwait.default)(path, { + getAsyncIterator: file.addHelper("asyncIterator") + }); + var declar = build.declar, + loop = build.loop; + var block = loop.body; + path.ensureBlock(); + if (declar) { + block.body.push(declar); + } - // Properties of the current token: - // Its type + block.body = block.body.concat(node.body.body); + _core.types.inherits(loop, node); - // For tokens that include more information than their type, the value + _core.types.inherits(loop.body, node.body); + if (build.replaceParent) { + path.parentPath.replaceWithMultiple(build.node); + } else { + path.replaceWithMultiple(build.node); + } + } + }; + var visitor = { + Function: function Function(path, state) { + if (!path.node.async) return; + path.traverse(forAwaitVisitor, state); + if (!path.node.generator) return; + path.traverse(yieldStarVisitor, state); + (0, _helperRemapAsyncToGenerator.default)(path, { + wrapAsync: state.addHelper("wrapAsyncGenerator"), + wrapAwait: state.addHelper("awaitAsyncGenerator") + }); + } + }; + return { + name: "proposal-async-generator-functions", + inherits: _pluginSyntaxAsyncGenerators.default, + visitor: { + Program: function Program(path, state) { + path.traverse(visitor, state); + } + } + }; +}); - // Its start and end offset +exports.default = _default; +},{"./for-await":90,"@babel/core":19,"@babel/helper-plugin-utils":79,"@babel/helper-remap-async-to-generator":81,"@babel/plugin-syntax-async-generators":98}],92:[function(require,module,exports){ +"use strict"; - // And, if locations are used, the {line, column} object - // corresponding to those offsets +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _helperPluginUtils = require("@babel/helper-plugin-utils"); - // Position information for the previous token +var _pluginSyntaxDynamicImport = _interopRequireDefault(require("@babel/plugin-syntax-dynamic-import")); +var _package = require("../package.json"); - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +var SUPPORTED_MODULES = ["commonjs", "amd", "systemjs"]; +var MODULES_NOT_FOUND = "@babel/plugin-proposal-dynamic-import depends on a modules\ntransform plugin. Supported plugins are:\n - @babel/plugin-transform-modules-commonjs ^7.4.0\n - @babel/plugin-transform-modules-amd ^7.4.0\n - @babel/plugin-transform-modules-systemjs ^7.4.0\n\nIf you are using Webpack or Rollup and thus don't want\nBabel to transpile your imports and exports, you can use\nthe @babel/plugin-syntax-dynamic-import plugin and let your\nbundler handle dynamic imports.\n"; - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. +var _default = (0, _helperPluginUtils.declare)(function (api) { + api.assertVersion(7); + return { + name: "proposal-dynamic-import", + inherits: _pluginSyntaxDynamicImport.default, + pre: function pre() { + this.file.set("@babel/plugin-proposal-dynamic-import", _package.version); + }, + visitor: { + Program: function Program() { + var modules = this.file.get("@babel/plugin-transform-modules-*"); + if (!SUPPORTED_MODULES.includes(modules)) { + throw new Error(MODULES_NOT_FOUND); + } + } + } + }; +}); - // TODO - - - // Names of exports store. `default` is stored as a name for both - // `export default foo;` and `export { foo as default };`. +exports.default = _default; +},{"../package.json":93,"@babel/helper-plugin-utils":79,"@babel/plugin-syntax-dynamic-import":99}],93:[function(require,module,exports){ +module.exports={ + "_from": "@babel/plugin-proposal-dynamic-import@^7.7.0", + "_id": "@babel/plugin-proposal-dynamic-import@7.7.0", + "_inBundle": false, + "_integrity": "sha512-7poL3Xi+QFPC7sGAzEIbXUyYzGJwbc2+gSD0AkiC5k52kH2cqHdqxm5hNFfLW3cRSTcx9bN0Fl7/6zWcLLnKAQ==", + "_location": "/@babel/plugin-proposal-dynamic-import", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@babel/plugin-proposal-dynamic-import@^7.7.0", + "name": "@babel/plugin-proposal-dynamic-import", + "escapedName": "@babel%2fplugin-proposal-dynamic-import", + "scope": "@babel", + "rawSpec": "^7.7.0", + "saveSpec": null, + "fetchSpec": "^7.7.0" + }, + "_requiredBy": [ + "/@babel/preset-env" + ], + "_resolved": "https://registry.npmjs.org/@babel/plugin-proposal-dynamic-import/-/plugin-proposal-dynamic-import-7.7.0.tgz", + "_shasum": "dc02a8bad8d653fb59daf085516fa416edd2aa7f", + "_spec": "@babel/plugin-proposal-dynamic-import@^7.7.0", + "_where": "/local/home/ossman/devel/noVNC/node_modules/@babel/preset-env", + "bundleDependencies": false, + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@babel/plugin-syntax-dynamic-import": "^7.2.0" + }, + "deprecated": false, + "description": "Transform import() expressions", + "devDependencies": { + "@babel/core": "^7.7.0", + "@babel/helper-plugin-test-runner": "^7.0.0" + }, + "gitHead": "97faa83953cb87e332554fa559a4956d202343ea", + "keywords": [ + "babel-plugin" + ], + "license": "MIT", + "main": "lib/index.js", + "name": "@babel/plugin-proposal-dynamic-import", + "peerDependencies": { + "@babel/core": "^7.0.0-0" + }, + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel/tree/master/packages/babel-plugin-proposal-dynamic-import" + }, + "version": "7.7.0" +} - State.prototype.curPosition = function curPosition() { - return new Position(this.curLine, this.pos - this.lineStart); - }; +},{}],94:[function(require,module,exports){ +"use strict"; - State.prototype.clone = function clone(skipArrays) { - var state = new State(); - for (var key in this) { - var val = this[key]; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - if ((!skipArrays || key === "context") && Array.isArray(val)) { - val = val.slice(); - } +function _helperPluginUtils() { + var data = require("@babel/helper-plugin-utils"); - state[key] = val; - } - return state; + _helperPluginUtils = function _helperPluginUtils() { + return data; }; - return State; -}(); - -// Object type used to represent tokens. Note that normally, tokens -// simply exist as properties on the parser object. This is only -// used for the onToken callback and the external tokenizer. + return data; +} -var Token = function Token(state) { - classCallCheck(this, Token); +function _pluginSyntaxJsonStrings() { + var data = _interopRequireDefault(require("@babel/plugin-syntax-json-strings")); - this.type = state.type; - this.value = state.value; - this.start = state.start; - this.end = state.end; - this.loc = new SourceLocation(state.startLoc, state.endLoc); -}; + _pluginSyntaxJsonStrings = function _pluginSyntaxJsonStrings() { + return data; + }; -// ## Tokenizer + return data; +} -function codePointToString(code) { - // UTF-16 Decoding - if (code <= 0xFFFF) { - return String.fromCharCode(code); - } else { - return String.fromCharCode((code - 0x10000 >> 10) + 0xD800, (code - 0x10000 & 1023) + 0xDC00); - } +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; } -var Tokenizer = function () { - function Tokenizer(options, input) { - classCallCheck(this, Tokenizer); +var _default = (0, _helperPluginUtils().declare)(function (api) { + api.assertVersion(7); + var regex = /(\\*)([\u2028\u2029])/g; - this.state = new State(); - this.state.init(options, input); + function replace(match, escapes, separator) { + var isEscaped = escapes.length % 2 === 1; + if (isEscaped) return match; + return "".concat(escapes, "\\u").concat(separator.charCodeAt(0).toString(16)); } - // Move to the next token - - Tokenizer.prototype.next = function next() { - if (!this.isLookahead) { - this.state.tokens.push(new Token(this.state)); + return { + name: "proposal-json-strings", + inherits: _pluginSyntaxJsonStrings().default, + visitor: { + "DirectiveLiteral|StringLiteral": function DirectiveLiteralStringLiteral(_ref) { + var node = _ref.node; + var extra = node.extra; + if (!extra || !extra.raw) return; + extra.raw = extra.raw.replace(regex, replace); + } } - - this.state.lastTokEnd = this.state.end; - this.state.lastTokStart = this.state.start; - this.state.lastTokEndLoc = this.state.endLoc; - this.state.lastTokStartLoc = this.state.startLoc; - this.nextToken(); }; +}); - // TODO - - Tokenizer.prototype.eat = function eat(type) { - if (this.match(type)) { - this.next(); - return true; - } else { - return false; - } - }; +exports.default = _default; - // TODO +},{"@babel/helper-plugin-utils":79,"@babel/plugin-syntax-json-strings":100}],95:[function(require,module,exports){ +"use strict"; - Tokenizer.prototype.match = function match(type) { - return this.state.type === type; - }; +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - // TODO +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - Tokenizer.prototype.isKeyword = function isKeyword$$1(word) { - return isKeyword(word); - }; +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - // TODO +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - Tokenizer.prototype.lookahead = function lookahead() { - var old = this.state; - this.state = old.clone(true); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; - this.isLookahead = true; - this.next(); - this.isLookahead = false; +function _helperPluginUtils() { + var data = require("@babel/helper-plugin-utils"); - var curr = this.state.clone(true); - this.state = old; - return curr; + _helperPluginUtils = function _helperPluginUtils() { + return data; }; - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). + return data; +} - Tokenizer.prototype.setStrict = function setStrict(strict) { - this.state.strict = strict; - if (!this.match(types.num) && !this.match(types.string)) return; - this.state.pos = this.state.start; - while (this.state.pos < this.state.lineStart) { - this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1; - --this.state.curLine; - } - this.nextToken(); - }; +function _pluginSyntaxObjectRestSpread() { + var data = _interopRequireDefault(require("@babel/plugin-syntax-object-rest-spread")); - Tokenizer.prototype.curContext = function curContext() { - return this.state.context[this.state.context.length - 1]; + _pluginSyntaxObjectRestSpread = function _pluginSyntaxObjectRestSpread() { + return data; }; - // Read a single token, updating the parser object's token-related - // properties. - - Tokenizer.prototype.nextToken = function nextToken() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) this.skipSpace(); - - this.state.containsOctal = false; - this.state.octalPosition = null; - this.state.start = this.state.pos; - this.state.startLoc = this.state.curPosition(); - if (this.state.pos >= this.input.length) return this.finishToken(types.eof); + return data; +} - if (curContext.override) { - return curContext.override(this); - } else { - return this.readToken(this.fullCharCodeAtPos()); - } - }; +function _core() { + var data = require("@babel/core"); - Tokenizer.prototype.readToken = function readToken(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code) || code === 92 /* '\' */) { - return this.readWord(); - } else { - return this.getTokenFromCode(code); - } + _core = function _core() { + return data; }; - Tokenizer.prototype.fullCharCodeAtPos = function fullCharCodeAtPos() { - var code = this.input.charCodeAt(this.state.pos); - if (code <= 0xd7ff || code >= 0xe000) return code; + return data; +} - var next = this.input.charCodeAt(this.state.pos + 1); - return (code << 10) + next - 0x35fdc00; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj }; +} - Tokenizer.prototype.pushComment = function pushComment(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "CommentBlock" : "CommentLine", - value: text, - start: start, - end: end, - loc: new SourceLocation(startLoc, endLoc) - }; - - if (!this.isLookahead) { - this.state.tokens.push(comment); - this.state.comments.push(comment); - this.addComment(comment); - } - }; +var ZERO_REFS = function () { + var node = _core().types.identifier("a"); - Tokenizer.prototype.skipBlockComment = function skipBlockComment() { - var startLoc = this.state.curPosition(); - var start = this.state.pos; - var end = this.input.indexOf("*/", this.state.pos += 2); - if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment"); + var property = _core().types.objectProperty(_core().types.identifier("key"), node); - this.state.pos = end + 2; - lineBreakG.lastIndex = start; - var match = void 0; - while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) { - ++this.state.curLine; - this.state.lineStart = match.index + match[0].length; - } + var pattern = _core().types.objectPattern([property]); - this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition()); - }; + return _core().types.isReferenced(node, property, pattern) ? 1 : 0; +}(); - Tokenizer.prototype.skipLineComment = function skipLineComment(startSkip) { - var start = this.state.pos; - var startLoc = this.state.curPosition(); - var ch = this.input.charCodeAt(this.state.pos += startSkip); - while (this.state.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { - ++this.state.pos; - ch = this.input.charCodeAt(this.state.pos); - } +var _default = (0, _helperPluginUtils().declare)(function (api, opts) { + api.assertVersion(7); + var _opts$useBuiltIns = opts.useBuiltIns, + useBuiltIns = _opts$useBuiltIns === void 0 ? false : _opts$useBuiltIns, + _opts$loose = opts.loose, + loose = _opts$loose === void 0 ? false : _opts$loose; - this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition()); - }; + if (typeof loose !== "boolean") { + throw new Error(".loose must be a boolean, or undefined"); + } - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. + function getExtendsHelper(file) { + return useBuiltIns ? _core().types.memberExpression(_core().types.identifier("Object"), _core().types.identifier("assign")) : file.addHelper("extends"); + } - Tokenizer.prototype.skipSpace = function skipSpace() { - loop: while (this.state.pos < this.input.length) { - var ch = this.input.charCodeAt(this.state.pos); - switch (ch) { - case 32:case 160: - // ' ' - ++this.state.pos; - break; + function hasRestElement(path) { + var foundRestElement = false; + visitRestElements(path, function (restElement) { + foundRestElement = true; + restElement.stop(); + }); + return foundRestElement; + } - case 13: - if (this.input.charCodeAt(this.state.pos + 1) === 10) { - ++this.state.pos; - } + function hasObjectPatternRestElement(path) { + var foundRestElement = false; + visitRestElements(path, function (restElement) { + if (restElement.parentPath.isObjectPattern()) { + foundRestElement = true; + restElement.stop(); + } + }); + return foundRestElement; + } - case 10:case 8232:case 8233: - ++this.state.pos; - ++this.state.curLine; - this.state.lineStart = this.state.pos; - break; + function visitRestElements(path, visitor) { + path.traverse({ + Expression: function Expression(path) { + var parentType = path.parent.type; - case 47: - // '/' - switch (this.input.charCodeAt(this.state.pos + 1)) { - case 42: - // '*' - this.skipBlockComment(); - break; + if (parentType === "AssignmentPattern" && path.key === "right" || parentType === "ObjectProperty" && path.parent.computed && path.key === "key") { + path.skip(); + } + }, + RestElement: visitor + }); + } - case 47: - this.skipLineComment(2); - break; + function hasSpread(node) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - default: - break loop; - } - break; + try { + for (var _iterator = node.properties[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var prop = _step.value; - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.state.pos; - } else { - break loop; - } + if (_core().types.isSpreadElement(prop)) { + return true; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } } - }; - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. + return false; + } - Tokenizer.prototype.finishToken = function finishToken(type, val) { - this.state.end = this.state.pos; - this.state.endLoc = this.state.curPosition(); - var prevType = this.state.type; - this.state.type = type; - this.state.value = val; + function extractNormalizedKeys(path) { + var props = path.node.properties; + var keys = []; + var allLiteral = true; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - this.updateContext(prevType); - }; + try { + for (var _iterator2 = props[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var prop = _step2.value; + + if (_core().types.isIdentifier(prop.key) && !prop.computed) { + keys.push(_core().types.stringLiteral(prop.key.name)); + } else if (_core().types.isTemplateLiteral(prop.key)) { + keys.push(_core().types.cloneNode(prop.key)); + } else if (_core().types.isLiteral(prop.key)) { + keys.push(_core().types.stringLiteral(String(prop.key.value))); + } else { + keys.push(_core().types.cloneNode(prop.key)); + allLiteral = false; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } - // ### Token reading + return { + keys: keys, + allLiteral: allLiteral + }; + } - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // + function replaceImpureComputedKeys(path) { + var impureComputedPropertyDeclarators = []; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + try { + for (var _iterator3 = path.get("properties")[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var propPath = _step3.value; + var key = propPath.get("key"); - Tokenizer.prototype.readToken_dot = function readToken_dot() { - var next = this.input.charCodeAt(this.state.pos + 1); - if (next >= 48 && next <= 57) { - return this.readNumber(true); - } + if (propPath.node.computed && !key.isPure()) { + var name = path.scope.generateUidBasedOnNode(key.node); - var next2 = this.input.charCodeAt(this.state.pos + 2); - if (next === 46 && next2 === 46) { - // 46 = dot '.' - this.state.pos += 3; - return this.finishToken(types.ellipsis); - } else { - ++this.state.pos; - return this.finishToken(types.dot); - } - }; + var declarator = _core().types.variableDeclarator(_core().types.identifier(name), key.node); - Tokenizer.prototype.readToken_slash = function readToken_slash() { - // '/' - if (this.state.exprAllowed) { - ++this.state.pos; - return this.readRegexp(); + impureComputedPropertyDeclarators.push(declarator); + key.replaceWith(_core().types.identifier(name)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } } - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.slash, 1); - } - }; + return impureComputedPropertyDeclarators; + } - Tokenizer.prototype.readToken_mult_modulo = function readToken_mult_modulo(code) { - // '%*' - var type = code === 42 ? types.star : types.modulo; - var width = 1; - var next = this.input.charCodeAt(this.state.pos + 1); + function removeUnusedExcludedKeys(path) { + var bindings = path.getOuterBindingIdentifierPaths(); + Object.keys(bindings).forEach(function (bindingName) { + var bindingParentPath = bindings[bindingName].parentPath; - if (next === 42) { - // '*' - width++; - next = this.input.charCodeAt(this.state.pos + 2); - type = types.exponent; - } + if (path.scope.getBinding(bindingName).references > ZERO_REFS || !bindingParentPath.isObjectProperty()) { + return; + } - if (next === 61) { - width++; - type = types.assign; - } + bindingParentPath.remove(); + }); + } - return this.finishOp(type, width); - }; + function createObjectSpread(path, file, objRef) { + var props = path.get("properties"); + var last = props[props.length - 1]; - Tokenizer.prototype.readToken_pipe_amp = function readToken_pipe_amp(code) { - // '|&' - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === code) return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2); - if (next === 61) return this.finishOp(types.assign, 2); - if (code === 124 && next === 125 && this.hasPlugin("flow")) return this.finishOp(types.braceBarR, 2); - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1); - }; + _core().types.assertRestElement(last.node); - Tokenizer.prototype.readToken_caret = function readToken_caret() { - // '^' - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.bitwiseXOR, 1); - } - }; + var restElement = _core().types.cloneNode(last.node); - Tokenizer.prototype.readToken_plus_min = function readToken_plus_min(code) { - // '+-' - var next = this.input.charCodeAt(this.state.pos + 1); + last.remove(); + var impureComputedPropertyDeclarators = replaceImpureComputedKeys(path); - if (next === code) { - if (next === 45 && this.input.charCodeAt(this.state.pos + 2) === 62 && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken(); - } - return this.finishOp(types.incDec, 2); + var _extractNormalizedKey = extractNormalizedKeys(path), + keys = _extractNormalizedKey.keys, + allLiteral = _extractNormalizedKey.allLiteral; + + if (keys.length === 0) { + return [impureComputedPropertyDeclarators, restElement.argument, _core().types.callExpression(getExtendsHelper(file), [_core().types.objectExpression([]), _core().types.cloneNode(objRef)])]; } - if (next === 61) { - return this.finishOp(types.assign, 2); + var keyExpression; + + if (!allLiteral) { + keyExpression = _core().types.callExpression(_core().types.memberExpression(_core().types.arrayExpression(keys), _core().types.identifier("map")), [file.addHelper("toPropertyKey")]); } else { - return this.finishOp(types.plusMin, 1); + keyExpression = _core().types.arrayExpression(keys); } - }; - Tokenizer.prototype.readToken_lt_gt = function readToken_lt_gt(code) { - // '<>' - var next = this.input.charCodeAt(this.state.pos + 1); - var size = 1; + return [impureComputedPropertyDeclarators, restElement.argument, _core().types.callExpression(file.addHelper("objectWithoutProperties".concat(loose ? "Loose" : "")), [_core().types.cloneNode(objRef), keyExpression])]; + } - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.state.pos + size) === 61) return this.finishOp(types.assign, size + 1); - return this.finishOp(types.bitShift, size); + function replaceRestElement(parentPath, paramPath) { + if (paramPath.isAssignmentPattern()) { + replaceRestElement(parentPath, paramPath.get("left")); + return; } - if (next === 33 && code === 60 && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { - if (this.inModule) this.unexpected(); - // ` * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 + + +function replaceTildes(comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options); + }).join(' '); +} + +function replaceTilde(comp, options) { + var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } else if (pr) { + debug('replaceTilde pr', pr); + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0'; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; + } + + debug('tilde return', ret); + return ret; + }); +} // ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 + + +function replaceCarets(comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options); + }).join(' '); +} + +function replaceCaret(comp, options) { + debug('caret', comp, options); + var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } + } else if (pr) { + debug('replaceCaret pr', pr); + + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1); + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0'; + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0'; + } + } else { + debug('no pr'); + + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1); + } else { + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; + } + } else { + ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0'; + } + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, options) { + debug('replaceXRanges', comp, options); + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options); + }).join(' '); +} + +function replaceXRange(comp, options) { + comp = comp.trim(); + var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + + + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + ret = gtlt + M + '.' + m + '.' + p + pr; + } else if (xm) { + ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr; + } + + debug('xRange return', ret); + return ret; + }); +} // Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. + + +function replaceStars(comp, options) { + debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets! + + return comp.trim().replace(re[t.STAR], ''); +} // This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 + + +function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = '>=' + fM + '.0.0'; + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0'; + } else { + from = '>=' + from; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0'; + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0'; + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + } else { + to = '<=' + to; + } + + return (from + ' ' + to).trim(); +} // if ANY of the sets match ALL of its comparators, then pass + + +Range.prototype.test = function (version) { + if (!version) { + return false; + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true; + } + } + + return false; +}; + +function testSet(set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false; + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver); + + if (set[i].semver === ANY) { + continue; + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; + } + } + } // Version has a -pre, but it's not one of the ones we like. + + + return false; + } + + return true; +} + +exports.satisfies = satisfies; + +function satisfies(version, range, options) { + try { + range = new Range(range, options); + } catch (er) { + return false; + } + + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; + +function maxSatisfying(versions, range, options) { + var max = null; + var maxSV = null; + + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null; + } + + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max; +} + +exports.minSatisfying = minSatisfying; + +function minSatisfying(versions, range, options) { + var min = null; + var minSV = null; + + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null; + } + + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer(min, options); + } + } + }); + return min; +} + +exports.minVersion = minVersion; + +function minVersion(range, loose) { + range = new Range(range, loose); + var minver = new SemVer('0.0.0'); + + if (range.test(minver)) { + return minver; + } + + minver = new SemVer('0.0.0-0'); + + if (range.test(minver)) { + return minver; + } + + minver = null; + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version); + + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + + compver.raw = compver.format(); + + /* fallthrough */ + + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver; + } + + break; + + case '<': + case '<=': + /* Ignore maximum versions */ + break; + + /* istanbul ignore next */ + + default: + throw new Error('Unexpected operation: ' + comparator.operator); + } + }); + } + + if (minver && range.test(minver)) { + return minver; + } + + return null; +} + +exports.validRange = validRange; + +function validRange(range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*'; + } catch (er) { + return null; + } +} // Determine if version is less than all the versions possible in the range + + +exports.ltr = ltr; + +function ltr(version, range, options) { + return outside(version, range, '<', options); +} // Determine if version is greater than all the versions possible in the range. + + +exports.gtr = gtr; + +function gtr(version, range, options) { + return outside(version, range, '>', options); +} + +exports.outside = outside; + +function outside(version, range, hilo, options) { + version = new SemVer(version, options); + range = new Range(range, options); + var gtfn, ltefn, ltfn, comp, ecomp; + + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } // If it satisifes the range it is not outside + + + if (satisfies(version, range, options)) { + return false; + } // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + var high = null; + var low = null; + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0'); + } + + high = high || comparator; + low = low || comparator; + + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); // If the edge version comparator has a operator then our version + // isn't outside it + + if (high.operator === comp || high.operator === ecomp) { + return false; + } // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + + + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + + return true; +} + +exports.prerelease = prerelease; + +function prerelease(version, options) { + var parsed = parse(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; +} + +exports.intersects = intersects; + +function intersects(r1, r2, options) { + r1 = new Range(r1, options); + r2 = new Range(r2, options); + return r1.intersects(r2); +} + +exports.coerce = coerce; + +function coerce(version, options) { + if (version instanceof SemVer) { + return version; + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null; + } + + options = options || {}; + var match = null; + + if (!options.rtl) { + match = version.match(re[t.COERCE]); + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + var next; + + while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } // leave it in a clean state + + + re[t.COERCERTL].lastIndex = -1; + } + + if (match === null) { + return null; + } + + return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options); +} + +}).call(this,require('_process')) +},{"_process":1054}],308:[function(require,module,exports){ +require('../modules/es.symbol'); +require('../modules/es.symbol.async-iterator'); +require('../modules/es.symbol.description'); +require('../modules/es.symbol.has-instance'); +require('../modules/es.symbol.is-concat-spreadable'); +require('../modules/es.symbol.iterator'); +require('../modules/es.symbol.match'); +require('../modules/es.symbol.match-all'); +require('../modules/es.symbol.replace'); +require('../modules/es.symbol.search'); +require('../modules/es.symbol.species'); +require('../modules/es.symbol.split'); +require('../modules/es.symbol.to-primitive'); +require('../modules/es.symbol.to-string-tag'); +require('../modules/es.symbol.unscopables'); +require('../modules/es.object.assign'); +require('../modules/es.object.create'); +require('../modules/es.object.define-property'); +require('../modules/es.object.define-properties'); +require('../modules/es.object.entries'); +require('../modules/es.object.freeze'); +require('../modules/es.object.from-entries'); +require('../modules/es.object.get-own-property-descriptor'); +require('../modules/es.object.get-own-property-descriptors'); +require('../modules/es.object.get-own-property-names'); +require('../modules/es.object.get-prototype-of'); +require('../modules/es.object.is'); +require('../modules/es.object.is-extensible'); +require('../modules/es.object.is-frozen'); +require('../modules/es.object.is-sealed'); +require('../modules/es.object.keys'); +require('../modules/es.object.prevent-extensions'); +require('../modules/es.object.seal'); +require('../modules/es.object.set-prototype-of'); +require('../modules/es.object.values'); +require('../modules/es.object.to-string'); +require('../modules/es.object.define-getter'); +require('../modules/es.object.define-setter'); +require('../modules/es.object.lookup-getter'); +require('../modules/es.object.lookup-setter'); +require('../modules/es.function.bind'); +require('../modules/es.function.name'); +require('../modules/es.function.has-instance'); +require('../modules/es.global-this'); +require('../modules/es.array.from'); +require('../modules/es.array.is-array'); +require('../modules/es.array.of'); +require('../modules/es.array.concat'); +require('../modules/es.array.copy-within'); +require('../modules/es.array.every'); +require('../modules/es.array.fill'); +require('../modules/es.array.filter'); +require('../modules/es.array.find'); +require('../modules/es.array.find-index'); +require('../modules/es.array.flat'); +require('../modules/es.array.flat-map'); +require('../modules/es.array.for-each'); +require('../modules/es.array.includes'); +require('../modules/es.array.index-of'); +require('../modules/es.array.join'); +require('../modules/es.array.last-index-of'); +require('../modules/es.array.map'); +require('../modules/es.array.reduce'); +require('../modules/es.array.reduce-right'); +require('../modules/es.array.reverse'); +require('../modules/es.array.slice'); +require('../modules/es.array.some'); +require('../modules/es.array.sort'); +require('../modules/es.array.splice'); +require('../modules/es.array.species'); +require('../modules/es.array.unscopables.flat'); +require('../modules/es.array.unscopables.flat-map'); +require('../modules/es.array.iterator'); +require('../modules/es.string.from-code-point'); +require('../modules/es.string.raw'); +require('../modules/es.string.code-point-at'); +require('../modules/es.string.ends-with'); +require('../modules/es.string.includes'); +require('../modules/es.string.match'); +require('../modules/es.string.match-all'); +require('../modules/es.string.pad-end'); +require('../modules/es.string.pad-start'); +require('../modules/es.string.repeat'); +require('../modules/es.string.replace'); +require('../modules/es.string.search'); +require('../modules/es.string.split'); +require('../modules/es.string.starts-with'); +require('../modules/es.string.trim'); +require('../modules/es.string.trim-start'); +require('../modules/es.string.trim-end'); +require('../modules/es.string.iterator'); +require('../modules/es.string.anchor'); +require('../modules/es.string.big'); +require('../modules/es.string.blink'); +require('../modules/es.string.bold'); +require('../modules/es.string.fixed'); +require('../modules/es.string.fontcolor'); +require('../modules/es.string.fontsize'); +require('../modules/es.string.italics'); +require('../modules/es.string.link'); +require('../modules/es.string.small'); +require('../modules/es.string.strike'); +require('../modules/es.string.sub'); +require('../modules/es.string.sup'); +require('../modules/es.regexp.constructor'); +require('../modules/es.regexp.exec'); +require('../modules/es.regexp.flags'); +require('../modules/es.regexp.to-string'); +require('../modules/es.parse-int'); +require('../modules/es.parse-float'); +require('../modules/es.number.constructor'); +require('../modules/es.number.epsilon'); +require('../modules/es.number.is-finite'); +require('../modules/es.number.is-integer'); +require('../modules/es.number.is-nan'); +require('../modules/es.number.is-safe-integer'); +require('../modules/es.number.max-safe-integer'); +require('../modules/es.number.min-safe-integer'); +require('../modules/es.number.parse-float'); +require('../modules/es.number.parse-int'); +require('../modules/es.number.to-fixed'); +require('../modules/es.number.to-precision'); +require('../modules/es.math.acosh'); +require('../modules/es.math.asinh'); +require('../modules/es.math.atanh'); +require('../modules/es.math.cbrt'); +require('../modules/es.math.clz32'); +require('../modules/es.math.cosh'); +require('../modules/es.math.expm1'); +require('../modules/es.math.fround'); +require('../modules/es.math.hypot'); +require('../modules/es.math.imul'); +require('../modules/es.math.log10'); +require('../modules/es.math.log1p'); +require('../modules/es.math.log2'); +require('../modules/es.math.sign'); +require('../modules/es.math.sinh'); +require('../modules/es.math.tanh'); +require('../modules/es.math.to-string-tag'); +require('../modules/es.math.trunc'); +require('../modules/es.date.now'); +require('../modules/es.date.to-json'); +require('../modules/es.date.to-iso-string'); +require('../modules/es.date.to-string'); +require('../modules/es.date.to-primitive'); +require('../modules/es.json.to-string-tag'); +require('../modules/es.promise'); +require('../modules/es.promise.all-settled'); +require('../modules/es.promise.finally'); +require('../modules/es.map'); +require('../modules/es.set'); +require('../modules/es.weak-map'); +require('../modules/es.weak-set'); +require('../modules/es.array-buffer.constructor'); +require('../modules/es.array-buffer.is-view'); +require('../modules/es.array-buffer.slice'); +require('../modules/es.data-view'); +require('../modules/es.typed-array.int8-array'); +require('../modules/es.typed-array.uint8-array'); +require('../modules/es.typed-array.uint8-clamped-array'); +require('../modules/es.typed-array.int16-array'); +require('../modules/es.typed-array.uint16-array'); +require('../modules/es.typed-array.int32-array'); +require('../modules/es.typed-array.uint32-array'); +require('../modules/es.typed-array.float32-array'); +require('../modules/es.typed-array.float64-array'); +require('../modules/es.typed-array.from'); +require('../modules/es.typed-array.of'); +require('../modules/es.typed-array.copy-within'); +require('../modules/es.typed-array.every'); +require('../modules/es.typed-array.fill'); +require('../modules/es.typed-array.filter'); +require('../modules/es.typed-array.find'); +require('../modules/es.typed-array.find-index'); +require('../modules/es.typed-array.for-each'); +require('../modules/es.typed-array.includes'); +require('../modules/es.typed-array.index-of'); +require('../modules/es.typed-array.iterator'); +require('../modules/es.typed-array.join'); +require('../modules/es.typed-array.last-index-of'); +require('../modules/es.typed-array.map'); +require('../modules/es.typed-array.reduce'); +require('../modules/es.typed-array.reduce-right'); +require('../modules/es.typed-array.reverse'); +require('../modules/es.typed-array.set'); +require('../modules/es.typed-array.slice'); +require('../modules/es.typed-array.some'); +require('../modules/es.typed-array.sort'); +require('../modules/es.typed-array.subarray'); +require('../modules/es.typed-array.to-locale-string'); +require('../modules/es.typed-array.to-string'); +require('../modules/es.reflect.apply'); +require('../modules/es.reflect.construct'); +require('../modules/es.reflect.define-property'); +require('../modules/es.reflect.delete-property'); +require('../modules/es.reflect.get'); +require('../modules/es.reflect.get-own-property-descriptor'); +require('../modules/es.reflect.get-prototype-of'); +require('../modules/es.reflect.has'); +require('../modules/es.reflect.is-extensible'); +require('../modules/es.reflect.own-keys'); +require('../modules/es.reflect.prevent-extensions'); +require('../modules/es.reflect.set'); +require('../modules/es.reflect.set-prototype-of'); + +module.exports = require('../internals/path'); + +},{"../internals/path":430,"../modules/es.array-buffer.constructor":476,"../modules/es.array-buffer.is-view":477,"../modules/es.array-buffer.slice":478,"../modules/es.array.concat":479,"../modules/es.array.copy-within":480,"../modules/es.array.every":481,"../modules/es.array.fill":482,"../modules/es.array.filter":483,"../modules/es.array.find":485,"../modules/es.array.find-index":484,"../modules/es.array.flat":487,"../modules/es.array.flat-map":486,"../modules/es.array.for-each":488,"../modules/es.array.from":489,"../modules/es.array.includes":490,"../modules/es.array.index-of":491,"../modules/es.array.is-array":492,"../modules/es.array.iterator":493,"../modules/es.array.join":494,"../modules/es.array.last-index-of":495,"../modules/es.array.map":496,"../modules/es.array.of":497,"../modules/es.array.reduce":499,"../modules/es.array.reduce-right":498,"../modules/es.array.reverse":500,"../modules/es.array.slice":501,"../modules/es.array.some":502,"../modules/es.array.sort":503,"../modules/es.array.species":504,"../modules/es.array.splice":505,"../modules/es.array.unscopables.flat":507,"../modules/es.array.unscopables.flat-map":506,"../modules/es.data-view":508,"../modules/es.date.now":509,"../modules/es.date.to-iso-string":510,"../modules/es.date.to-json":511,"../modules/es.date.to-primitive":512,"../modules/es.date.to-string":513,"../modules/es.function.bind":514,"../modules/es.function.has-instance":515,"../modules/es.function.name":516,"../modules/es.global-this":517,"../modules/es.json.to-string-tag":518,"../modules/es.map":519,"../modules/es.math.acosh":520,"../modules/es.math.asinh":521,"../modules/es.math.atanh":522,"../modules/es.math.cbrt":523,"../modules/es.math.clz32":524,"../modules/es.math.cosh":525,"../modules/es.math.expm1":526,"../modules/es.math.fround":527,"../modules/es.math.hypot":528,"../modules/es.math.imul":529,"../modules/es.math.log10":530,"../modules/es.math.log1p":531,"../modules/es.math.log2":532,"../modules/es.math.sign":533,"../modules/es.math.sinh":534,"../modules/es.math.tanh":535,"../modules/es.math.to-string-tag":536,"../modules/es.math.trunc":537,"../modules/es.number.constructor":538,"../modules/es.number.epsilon":539,"../modules/es.number.is-finite":540,"../modules/es.number.is-integer":541,"../modules/es.number.is-nan":542,"../modules/es.number.is-safe-integer":543,"../modules/es.number.max-safe-integer":544,"../modules/es.number.min-safe-integer":545,"../modules/es.number.parse-float":546,"../modules/es.number.parse-int":547,"../modules/es.number.to-fixed":548,"../modules/es.number.to-precision":549,"../modules/es.object.assign":550,"../modules/es.object.create":551,"../modules/es.object.define-getter":552,"../modules/es.object.define-properties":553,"../modules/es.object.define-property":554,"../modules/es.object.define-setter":555,"../modules/es.object.entries":556,"../modules/es.object.freeze":557,"../modules/es.object.from-entries":558,"../modules/es.object.get-own-property-descriptor":559,"../modules/es.object.get-own-property-descriptors":560,"../modules/es.object.get-own-property-names":561,"../modules/es.object.get-prototype-of":562,"../modules/es.object.is":566,"../modules/es.object.is-extensible":563,"../modules/es.object.is-frozen":564,"../modules/es.object.is-sealed":565,"../modules/es.object.keys":567,"../modules/es.object.lookup-getter":568,"../modules/es.object.lookup-setter":569,"../modules/es.object.prevent-extensions":570,"../modules/es.object.seal":571,"../modules/es.object.set-prototype-of":572,"../modules/es.object.to-string":573,"../modules/es.object.values":574,"../modules/es.parse-float":575,"../modules/es.parse-int":576,"../modules/es.promise":579,"../modules/es.promise.all-settled":577,"../modules/es.promise.finally":578,"../modules/es.reflect.apply":580,"../modules/es.reflect.construct":581,"../modules/es.reflect.define-property":582,"../modules/es.reflect.delete-property":583,"../modules/es.reflect.get":586,"../modules/es.reflect.get-own-property-descriptor":584,"../modules/es.reflect.get-prototype-of":585,"../modules/es.reflect.has":587,"../modules/es.reflect.is-extensible":588,"../modules/es.reflect.own-keys":589,"../modules/es.reflect.prevent-extensions":590,"../modules/es.reflect.set":592,"../modules/es.reflect.set-prototype-of":591,"../modules/es.regexp.constructor":593,"../modules/es.regexp.exec":594,"../modules/es.regexp.flags":595,"../modules/es.regexp.to-string":596,"../modules/es.set":597,"../modules/es.string.anchor":598,"../modules/es.string.big":599,"../modules/es.string.blink":600,"../modules/es.string.bold":601,"../modules/es.string.code-point-at":602,"../modules/es.string.ends-with":603,"../modules/es.string.fixed":604,"../modules/es.string.fontcolor":605,"../modules/es.string.fontsize":606,"../modules/es.string.from-code-point":607,"../modules/es.string.includes":608,"../modules/es.string.italics":609,"../modules/es.string.iterator":610,"../modules/es.string.link":611,"../modules/es.string.match":613,"../modules/es.string.match-all":612,"../modules/es.string.pad-end":614,"../modules/es.string.pad-start":615,"../modules/es.string.raw":616,"../modules/es.string.repeat":617,"../modules/es.string.replace":618,"../modules/es.string.search":619,"../modules/es.string.small":620,"../modules/es.string.split":621,"../modules/es.string.starts-with":622,"../modules/es.string.strike":623,"../modules/es.string.sub":624,"../modules/es.string.sup":625,"../modules/es.string.trim":628,"../modules/es.string.trim-end":626,"../modules/es.string.trim-start":627,"../modules/es.symbol":634,"../modules/es.symbol.async-iterator":629,"../modules/es.symbol.description":630,"../modules/es.symbol.has-instance":631,"../modules/es.symbol.is-concat-spreadable":632,"../modules/es.symbol.iterator":633,"../modules/es.symbol.match":636,"../modules/es.symbol.match-all":635,"../modules/es.symbol.replace":637,"../modules/es.symbol.search":638,"../modules/es.symbol.species":639,"../modules/es.symbol.split":640,"../modules/es.symbol.to-primitive":641,"../modules/es.symbol.to-string-tag":642,"../modules/es.symbol.unscopables":643,"../modules/es.typed-array.copy-within":644,"../modules/es.typed-array.every":645,"../modules/es.typed-array.fill":646,"../modules/es.typed-array.filter":647,"../modules/es.typed-array.find":649,"../modules/es.typed-array.find-index":648,"../modules/es.typed-array.float32-array":650,"../modules/es.typed-array.float64-array":651,"../modules/es.typed-array.for-each":652,"../modules/es.typed-array.from":653,"../modules/es.typed-array.includes":654,"../modules/es.typed-array.index-of":655,"../modules/es.typed-array.int16-array":656,"../modules/es.typed-array.int32-array":657,"../modules/es.typed-array.int8-array":658,"../modules/es.typed-array.iterator":659,"../modules/es.typed-array.join":660,"../modules/es.typed-array.last-index-of":661,"../modules/es.typed-array.map":662,"../modules/es.typed-array.of":663,"../modules/es.typed-array.reduce":665,"../modules/es.typed-array.reduce-right":664,"../modules/es.typed-array.reverse":666,"../modules/es.typed-array.set":667,"../modules/es.typed-array.slice":668,"../modules/es.typed-array.some":669,"../modules/es.typed-array.sort":670,"../modules/es.typed-array.subarray":671,"../modules/es.typed-array.to-locale-string":672,"../modules/es.typed-array.to-string":673,"../modules/es.typed-array.uint16-array":674,"../modules/es.typed-array.uint32-array":675,"../modules/es.typed-array.uint8-array":676,"../modules/es.typed-array.uint8-clamped-array":677,"../modules/es.weak-map":678,"../modules/es.weak-set":679}],309:[function(require,module,exports){ +require('./es'); +require('./proposals'); +require('./web'); + +module.exports = require('./internals/path'); + +},{"./es":308,"./internals/path":430,"./proposals":802,"./web":830}],310:[function(require,module,exports){ +module.exports = function (it) { + if (typeof it != 'function') { + throw TypeError(String(it) + ' is not a function'); + } return it; +}; + +},{}],311:[function(require,module,exports){ +var isObject = require('../internals/is-object'); + +module.exports = function (it) { + if (!isObject(it) && it !== null) { + throw TypeError("Can't set " + String(it) + ' as a prototype'); + } return it; +}; + +},{"../internals/is-object":392}],312:[function(require,module,exports){ +var wellKnownSymbol = require('../internals/well-known-symbol'); +var create = require('../internals/object-create'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); + +var UNSCOPABLES = wellKnownSymbol('unscopables'); +var ArrayPrototype = Array.prototype; + +// Array.prototype[@@unscopables] +// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables +if (ArrayPrototype[UNSCOPABLES] == undefined) { + createNonEnumerableProperty(ArrayPrototype, UNSCOPABLES, create(null)); +} + +// add a key to Array.prototype[@@unscopables] +module.exports = function (key) { + ArrayPrototype[UNSCOPABLES][key] = true; +}; + +},{"../internals/create-non-enumerable-property":350,"../internals/object-create":413,"../internals/well-known-symbol":473}],313:[function(require,module,exports){ +'use strict'; +var charAt = require('../internals/string-multibyte').charAt; + +// `AdvanceStringIndex` abstract operation +// https://tc39.github.io/ecma262/#sec-advancestringindex +module.exports = function (S, index, unicode) { + return index + (unicode ? charAt(S, index).length : 1); +}; + +},{"../internals/string-multibyte":451}],314:[function(require,module,exports){ +module.exports = function (it, Constructor, name) { + if (!(it instanceof Constructor)) { + throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation'); + } return it; +}; + +},{}],315:[function(require,module,exports){ +var isObject = require('../internals/is-object'); + +module.exports = function (it) { + if (!isObject(it)) { + throw TypeError(String(it) + ' is not an object'); + } return it; +}; + +},{"../internals/is-object":392}],316:[function(require,module,exports){ +'use strict'; +var DESCRIPTORS = require('../internals/descriptors'); +var global = require('../internals/global'); +var isObject = require('../internals/is-object'); +var has = require('../internals/has'); +var classof = require('../internals/classof'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefine = require('../internals/redefine'); +var defineProperty = require('../internals/object-define-property').f; +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var setPrototypeOf = require('../internals/object-set-prototype-of'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var uid = require('../internals/uid'); + +var DataView = global.DataView; +var DataViewPrototype = DataView && DataView.prototype; +var Int8Array = global.Int8Array; +var Int8ArrayPrototype = Int8Array && Int8Array.prototype; +var Uint8ClampedArray = global.Uint8ClampedArray; +var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; +var TypedArray = Int8Array && getPrototypeOf(Int8Array); +var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype); +var ObjectPrototype = Object.prototype; +var isPrototypeOf = ObjectPrototype.isPrototypeOf; + +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); +var NATIVE_ARRAY_BUFFER = !!(global.ArrayBuffer && DataView); +// Fixing native typed arrays in Opera Presto crashes the browser, see #595 +var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera'; +var TYPED_ARRAY_TAG_REQIRED = false; +var NAME; + +var TypedArrayConstructorsList = { + Int8Array: 1, + Uint8Array: 1, + Uint8ClampedArray: 1, + Int16Array: 2, + Uint16Array: 2, + Int32Array: 4, + Uint32Array: 4, + Float32Array: 4, + Float64Array: 8 +}; + +var isView = function isView(it) { + var klass = classof(it); + return klass === 'DataView' || has(TypedArrayConstructorsList, klass); +}; + +var isTypedArray = function (it) { + return isObject(it) && has(TypedArrayConstructorsList, classof(it)); +}; + +var aTypedArray = function (it) { + if (isTypedArray(it)) return it; + throw TypeError('Target is not a typed array'); +}; + +var aTypedArrayConstructor = function (C) { + if (setPrototypeOf) { + if (isPrototypeOf.call(TypedArray, C)) return C; + } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) { + var TypedArrayConstructor = global[ARRAY]; + if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) { + return C; + } + } throw TypeError('Target is not a typed array constructor'); +}; + +var exportProto = function (KEY, property, forced) { + if (!DESCRIPTORS) return; + if (forced) for (var ARRAY in TypedArrayConstructorsList) { + var TypedArrayConstructor = global[ARRAY]; + if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) { + delete TypedArrayConstructor.prototype[KEY]; + } + } + if (!TypedArrayPrototype[KEY] || forced) { + redefine(TypedArrayPrototype, KEY, forced ? property + : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property); + } +}; + +var exportStatic = function (KEY, property, forced) { + var ARRAY, TypedArrayConstructor; + if (!DESCRIPTORS) return; + if (setPrototypeOf) { + if (forced) for (ARRAY in TypedArrayConstructorsList) { + TypedArrayConstructor = global[ARRAY]; + if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) { + delete TypedArrayConstructor[KEY]; + } + } + if (!TypedArray[KEY] || forced) { + // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable + try { + return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property); + } catch (error) { /* empty */ } + } else return; + } + for (ARRAY in TypedArrayConstructorsList) { + TypedArrayConstructor = global[ARRAY]; + if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { + redefine(TypedArrayConstructor, KEY, property); + } + } +}; + +for (NAME in TypedArrayConstructorsList) { + if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false; +} + +// WebKit bug - typed arrays constructors prototype is Object.prototype +if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) { + // eslint-disable-next-line no-shadow + TypedArray = function TypedArray() { + throw TypeError('Incorrect invocation'); + }; + if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { + if (global[NAME]) setPrototypeOf(global[NAME], TypedArray); + } +} + +if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) { + TypedArrayPrototype = TypedArray.prototype; + if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { + if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype); + } +} + +// WebKit bug - one more object in Uint8ClampedArray prototype chain +if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { + setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); +} + +if (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) { + TYPED_ARRAY_TAG_REQIRED = true; + defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () { + return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; + } }); + for (NAME in TypedArrayConstructorsList) if (global[NAME]) { + createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME); + } +} + +// WebKit bug - the same parent prototype for typed arrays and data view +if (NATIVE_ARRAY_BUFFER && setPrototypeOf && getPrototypeOf(DataViewPrototype) !== ObjectPrototype) { + setPrototypeOf(DataViewPrototype, ObjectPrototype); +} + +module.exports = { + NATIVE_ARRAY_BUFFER: NATIVE_ARRAY_BUFFER, + NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, + TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG, + aTypedArray: aTypedArray, + aTypedArrayConstructor: aTypedArrayConstructor, + exportProto: exportProto, + exportStatic: exportStatic, + isView: isView, + isTypedArray: isTypedArray, + TypedArray: TypedArray, + TypedArrayPrototype: TypedArrayPrototype +}; + +},{"../internals/classof":334,"../internals/create-non-enumerable-property":350,"../internals/descriptors":357,"../internals/global":377,"../internals/has":378,"../internals/is-object":392,"../internals/object-define-property":415,"../internals/object-get-prototype-of":420,"../internals/object-set-prototype-of":424,"../internals/redefine":435,"../internals/uid":469,"../internals/well-known-symbol":473}],317:[function(require,module,exports){ +'use strict'; +var global = require('../internals/global'); +var DESCRIPTORS = require('../internals/descriptors'); +var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER; +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefineAll = require('../internals/redefine-all'); +var fails = require('../internals/fails'); +var anInstance = require('../internals/an-instance'); +var toInteger = require('../internals/to-integer'); +var toLength = require('../internals/to-length'); +var toIndex = require('../internals/to-index'); +var getOwnPropertyNames = require('../internals/object-get-own-property-names').f; +var defineProperty = require('../internals/object-define-property').f; +var arrayFill = require('../internals/array-fill'); +var setToStringTag = require('../internals/set-to-string-tag'); +var InternalStateModule = require('../internals/internal-state'); + +var getInternalState = InternalStateModule.get; +var setInternalState = InternalStateModule.set; +var ARRAY_BUFFER = 'ArrayBuffer'; +var DATA_VIEW = 'DataView'; +var PROTOTYPE = 'prototype'; +var WRONG_LENGTH = 'Wrong length'; +var WRONG_INDEX = 'Wrong index'; +var NativeArrayBuffer = global[ARRAY_BUFFER]; +var $ArrayBuffer = NativeArrayBuffer; +var $DataView = global[DATA_VIEW]; +var Math = global.Math; +var RangeError = global.RangeError; +// eslint-disable-next-line no-shadow-restricted-names +var Infinity = 1 / 0; +var abs = Math.abs; +var pow = Math.pow; +var floor = Math.floor; +var log = Math.log; +var LN2 = Math.LN2; + +// IEEE754 conversions based on https://github.com/feross/ieee754 +var packIEEE754 = function (number, mantissaLength, bytes) { + var buffer = new Array(bytes); + var exponentLength = bytes * 8 - mantissaLength - 1; + var eMax = (1 << exponentLength) - 1; + var eBias = eMax >> 1; + var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0; + var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0; + var index = 0; + var exponent, mantissa, c; + number = abs(number); + // eslint-disable-next-line no-self-compare + if (number != number || number === Infinity) { + // eslint-disable-next-line no-self-compare + mantissa = number != number ? 1 : 0; + exponent = eMax; + } else { + exponent = floor(log(number) / LN2); + if (number * (c = pow(2, -exponent)) < 1) { + exponent--; + c *= 2; + } + if (exponent + eBias >= 1) { + number += rt / c; + } else { + number += rt * pow(2, 1 - eBias); + } + if (number * c >= 2) { + exponent++; + c /= 2; + } + if (exponent + eBias >= eMax) { + mantissa = 0; + exponent = eMax; + } else if (exponent + eBias >= 1) { + mantissa = (number * c - 1) * pow(2, mantissaLength); + exponent = exponent + eBias; + } else { + mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength); + exponent = 0; + } + } + for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8); + exponent = exponent << mantissaLength | mantissa; + exponentLength += mantissaLength; + for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8); + buffer[--index] |= sign * 128; + return buffer; +}; + +var unpackIEEE754 = function (buffer, mantissaLength) { + var bytes = buffer.length; + var exponentLength = bytes * 8 - mantissaLength - 1; + var eMax = (1 << exponentLength) - 1; + var eBias = eMax >> 1; + var nBits = exponentLength - 7; + var index = bytes - 1; + var sign = buffer[index--]; + var exponent = sign & 127; + var mantissa; + sign >>= 7; + for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8); + mantissa = exponent & (1 << -nBits) - 1; + exponent >>= -nBits; + nBits += mantissaLength; + for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8); + if (exponent === 0) { + exponent = 1 - eBias; + } else if (exponent === eMax) { + return mantissa ? NaN : sign ? -Infinity : Infinity; + } else { + mantissa = mantissa + pow(2, mantissaLength); + exponent = exponent - eBias; + } return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength); +}; + +var unpackInt32 = function (buffer) { + return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]; +}; + +var packInt8 = function (number) { + return [number & 0xFF]; +}; + +var packInt16 = function (number) { + return [number & 0xFF, number >> 8 & 0xFF]; +}; + +var packInt32 = function (number) { + return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF]; +}; + +var packFloat32 = function (number) { + return packIEEE754(number, 23, 4); +}; + +var packFloat64 = function (number) { + return packIEEE754(number, 52, 8); +}; + +var addGetter = function (Constructor, key) { + defineProperty(Constructor[PROTOTYPE], key, { get: function () { return getInternalState(this)[key]; } }); +}; + +var get = function (view, count, index, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + var store = getInternalState(view); + if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX); + var bytes = getInternalState(store.buffer).bytes; + var start = intIndex + store.byteOffset; + var pack = bytes.slice(start, start + count); + return isLittleEndian ? pack : pack.reverse(); +}; + +var set = function (view, count, index, conversion, value, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + var store = getInternalState(view); + if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX); + var bytes = getInternalState(store.buffer).bytes; + var start = intIndex + store.byteOffset; + var pack = conversion(+value); + for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1]; +}; + +if (!NATIVE_ARRAY_BUFFER) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer, ARRAY_BUFFER); + var byteLength = toIndex(length); + setInternalState(this, { + bytes: arrayFill.call(new Array(byteLength), 0), + byteLength: byteLength + }); + if (!DESCRIPTORS) this.byteLength = byteLength; + }; + + $DataView = function DataView(buffer, byteOffset, byteLength) { + anInstance(this, $DataView, DATA_VIEW); + anInstance(buffer, $ArrayBuffer, DATA_VIEW); + var bufferLength = getInternalState(buffer).byteLength; + var offset = toInteger(byteOffset); + if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); + setInternalState(this, { + buffer: buffer, + byteLength: byteLength, + byteOffset: offset + }); + if (!DESCRIPTORS) { + this.buffer = buffer; + this.byteLength = byteLength; + this.byteOffset = offset; + } + }; + + if (DESCRIPTORS) { + addGetter($ArrayBuffer, 'byteLength'); + addGetter($DataView, 'buffer'); + addGetter($DataView, 'byteLength'); + addGetter($DataView, 'byteOffset'); + } + + redefineAll($DataView[PROTOTYPE], { + getInt8: function getInt8(byteOffset) { + return get(this, 1, byteOffset)[0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset) { + return get(this, 1, byteOffset)[0]; + }, + getInt16: function getInt16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /* , littleEndian */) { + return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)); + }, + getUint32: function getUint32(byteOffset /* , littleEndian */) { + return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23); + }, + getFloat64: function getFloat64(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52); + }, + setInt8: function setInt8(byteOffset, value) { + set(this, 1, byteOffset, packInt8, value); + }, + setUint8: function setUint8(byteOffset, value) { + set(this, 1, byteOffset, packInt8, value); + }, + setInt16: function setInt16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setUint16: function setUint16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setInt32: function setInt32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setUint32: function setUint32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined); + }, + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { + set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined); + } + }); +} else { + if (!fails(function () { + NativeArrayBuffer(1); + }) || !fails(function () { + new NativeArrayBuffer(-1); // eslint-disable-line no-new + }) || fails(function () { + new NativeArrayBuffer(); // eslint-disable-line no-new + new NativeArrayBuffer(1.5); // eslint-disable-line no-new + new NativeArrayBuffer(NaN); // eslint-disable-line no-new + return NativeArrayBuffer.name != ARRAY_BUFFER; + })) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer); + return new NativeArrayBuffer(toIndex(length)); + }; + var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE] = NativeArrayBuffer[PROTOTYPE]; + for (var keys = getOwnPropertyNames(NativeArrayBuffer), j = 0, key; keys.length > j;) { + if (!((key = keys[j++]) in $ArrayBuffer)) { + createNonEnumerableProperty($ArrayBuffer, key, NativeArrayBuffer[key]); + } + } + ArrayBufferPrototype.constructor = $ArrayBuffer; + } + // iOS Safari 7.x bug + var testView = new $DataView(new $ArrayBuffer(2)); + var nativeSetInt8 = $DataView[PROTOTYPE].setInt8; + testView.setInt8(0, 2147483648); + testView.setInt8(1, 2147483649); + if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataView[PROTOTYPE], { + setInt8: function setInt8(byteOffset, value) { + nativeSetInt8.call(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value) { + nativeSetInt8.call(this, byteOffset, value << 24 >> 24); + } + }, { unsafe: true }); +} + +setToStringTag($ArrayBuffer, ARRAY_BUFFER); +setToStringTag($DataView, DATA_VIEW); + +module.exports = { + ArrayBuffer: $ArrayBuffer, + DataView: $DataView +}; + +},{"../internals/an-instance":314,"../internals/array-buffer-view-core":316,"../internals/array-fill":319,"../internals/create-non-enumerable-property":350,"../internals/descriptors":357,"../internals/fails":362,"../internals/global":377,"../internals/internal-state":386,"../internals/object-define-property":415,"../internals/object-get-own-property-names":418,"../internals/redefine-all":434,"../internals/set-to-string-tag":445,"../internals/to-index":458,"../internals/to-integer":460,"../internals/to-length":461}],318:[function(require,module,exports){ +'use strict'; +var toObject = require('../internals/to-object'); +var toAbsoluteIndex = require('../internals/to-absolute-index'); +var toLength = require('../internals/to-length'); + +var min = Math.min; + +// `Array.prototype.copyWithin` method implementation +// https://tc39.github.io/ecma262/#sec-array.prototype.copywithin +module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { + var O = toObject(this); + var len = toLength(O.length); + var to = toAbsoluteIndex(target, len); + var from = toAbsoluteIndex(start, len); + var end = arguments.length > 2 ? arguments[2] : undefined; + var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); + var inc = 1; + if (from < to && to < from + count) { + inc = -1; + from += count - 1; + to += count - 1; + } + while (count-- > 0) { + if (from in O) O[to] = O[from]; + else delete O[to]; + to += inc; + from += inc; + } return O; +}; + +},{"../internals/to-absolute-index":457,"../internals/to-length":461,"../internals/to-object":462}],319:[function(require,module,exports){ +'use strict'; +var toObject = require('../internals/to-object'); +var toAbsoluteIndex = require('../internals/to-absolute-index'); +var toLength = require('../internals/to-length'); + +// `Array.prototype.fill` method implementation +// https://tc39.github.io/ecma262/#sec-array.prototype.fill +module.exports = function fill(value /* , start = 0, end = @length */) { + var O = toObject(this); + var length = toLength(O.length); + var argumentsLength = arguments.length; + var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length); + var end = argumentsLength > 2 ? arguments[2] : undefined; + var endPos = end === undefined ? length : toAbsoluteIndex(end, length); + while (endPos > index) O[index++] = value; + return O; +}; + +},{"../internals/to-absolute-index":457,"../internals/to-length":461,"../internals/to-object":462}],320:[function(require,module,exports){ +'use strict'; +var $forEach = require('../internals/array-iteration').forEach; +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +// `Array.prototype.forEach` method implementation +// https://tc39.github.io/ecma262/#sec-array.prototype.foreach +module.exports = sloppyArrayMethod('forEach') ? function forEach(callbackfn /* , thisArg */) { + return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); +} : [].forEach; + +},{"../internals/array-iteration":323,"../internals/sloppy-array-method":449}],321:[function(require,module,exports){ +'use strict'; +var bind = require('../internals/bind-context'); +var toObject = require('../internals/to-object'); +var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing'); +var isArrayIteratorMethod = require('../internals/is-array-iterator-method'); +var toLength = require('../internals/to-length'); +var createProperty = require('../internals/create-property'); +var getIteratorMethod = require('../internals/get-iterator-method'); + +// `Array.from` method implementation +// https://tc39.github.io/ecma262/#sec-array.from +module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var argumentsLength = arguments.length; + var mapfn = argumentsLength > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iteratorMethod = getIteratorMethod(O); + var length, result, step, iterator, next; + if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); + // if the target is not iterable or it's an array with the default iterator - use a simple case + if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { + iterator = iteratorMethod.call(O); + next = iterator.next; + result = new C(); + for (;!(step = next.call(iterator)).done; index++) { + createProperty(result, index, mapping + ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) + : step.value + ); + } + } else { + length = toLength(O.length); + result = new C(length); + for (;length > index; index++) { + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; +}; + +},{"../internals/bind-context":330,"../internals/call-with-safe-iteration-closing":331,"../internals/create-property":352,"../internals/get-iterator-method":373,"../internals/is-array-iterator-method":387,"../internals/to-length":461,"../internals/to-object":462}],322:[function(require,module,exports){ +var toIndexedObject = require('../internals/to-indexed-object'); +var toLength = require('../internals/to-length'); +var toAbsoluteIndex = require('../internals/to-absolute-index'); + +// `Array.prototype.{ indexOf, includes }` methods implementation +var createMethod = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIndexedObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) { + if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; + +module.exports = { + // `Array.prototype.includes` method + // https://tc39.github.io/ecma262/#sec-array.prototype.includes + includes: createMethod(true), + // `Array.prototype.indexOf` method + // https://tc39.github.io/ecma262/#sec-array.prototype.indexof + indexOf: createMethod(false) +}; + +},{"../internals/to-absolute-index":457,"../internals/to-indexed-object":459,"../internals/to-length":461}],323:[function(require,module,exports){ +var bind = require('../internals/bind-context'); +var IndexedObject = require('../internals/indexed-object'); +var toObject = require('../internals/to-object'); +var toLength = require('../internals/to-length'); +var arraySpeciesCreate = require('../internals/array-species-create'); + +var push = [].push; + +// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation +var createMethod = function (TYPE) { + var IS_MAP = TYPE == 1; + var IS_FILTER = TYPE == 2; + var IS_SOME = TYPE == 3; + var IS_EVERY = TYPE == 4; + var IS_FIND_INDEX = TYPE == 6; + var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; + return function ($this, callbackfn, that, specificCreate) { + var O = toObject($this); + var self = IndexedObject(O); + var boundFunction = bind(callbackfn, that, 3); + var length = toLength(self.length); + var index = 0; + var create = specificCreate || arraySpeciesCreate; + var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; + var value, result; + for (;length > index; index++) if (NO_HOLES || index in self) { + value = self[index]; + result = boundFunction(value, index, O); + if (TYPE) { + if (IS_MAP) target[index] = result; // map + else if (result) switch (TYPE) { + case 3: return true; // some + case 5: return value; // find + case 6: return index; // findIndex + case 2: push.call(target, value); // filter + } else if (IS_EVERY) return false; // every + } + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target; + }; +}; + +module.exports = { + // `Array.prototype.forEach` method + // https://tc39.github.io/ecma262/#sec-array.prototype.foreach + forEach: createMethod(0), + // `Array.prototype.map` method + // https://tc39.github.io/ecma262/#sec-array.prototype.map + map: createMethod(1), + // `Array.prototype.filter` method + // https://tc39.github.io/ecma262/#sec-array.prototype.filter + filter: createMethod(2), + // `Array.prototype.some` method + // https://tc39.github.io/ecma262/#sec-array.prototype.some + some: createMethod(3), + // `Array.prototype.every` method + // https://tc39.github.io/ecma262/#sec-array.prototype.every + every: createMethod(4), + // `Array.prototype.find` method + // https://tc39.github.io/ecma262/#sec-array.prototype.find + find: createMethod(5), + // `Array.prototype.findIndex` method + // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex + findIndex: createMethod(6) +}; + +},{"../internals/array-species-create":327,"../internals/bind-context":330,"../internals/indexed-object":383,"../internals/to-length":461,"../internals/to-object":462}],324:[function(require,module,exports){ +'use strict'; +var toIndexedObject = require('../internals/to-indexed-object'); +var toInteger = require('../internals/to-integer'); +var toLength = require('../internals/to-length'); +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +var min = Math.min; +var nativeLastIndexOf = [].lastIndexOf; +var NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0; +var SLOPPY_METHOD = sloppyArrayMethod('lastIndexOf'); + +// `Array.prototype.lastIndexOf` method implementation +// https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof +module.exports = (NEGATIVE_ZERO || SLOPPY_METHOD) ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { + // convert -0 to +0 + if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0; + var O = toIndexedObject(this); + var length = toLength(O.length); + var index = length - 1; + if (arguments.length > 1) index = min(index, toInteger(arguments[1])); + if (index < 0) index = length + index; + for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0; + return -1; +} : nativeLastIndexOf; + +},{"../internals/sloppy-array-method":449,"../internals/to-indexed-object":459,"../internals/to-integer":460,"../internals/to-length":461}],325:[function(require,module,exports){ +var fails = require('../internals/fails'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var V8_VERSION = require('../internals/v8-version'); + +var SPECIES = wellKnownSymbol('species'); + +module.exports = function (METHOD_NAME) { + // We can't use this feature detection in V8 since it causes + // deoptimization and serious performance degradation + // https://github.com/zloirock/core-js/issues/677 + return V8_VERSION >= 51 || !fails(function () { + var array = []; + var constructor = array.constructor = {}; + constructor[SPECIES] = function () { + return { foo: 1 }; + }; + return array[METHOD_NAME](Boolean).foo !== 1; + }); +}; + +},{"../internals/fails":362,"../internals/v8-version":471,"../internals/well-known-symbol":473}],326:[function(require,module,exports){ +var aFunction = require('../internals/a-function'); +var toObject = require('../internals/to-object'); +var IndexedObject = require('../internals/indexed-object'); +var toLength = require('../internals/to-length'); + +// `Array.prototype.{ reduce, reduceRight }` methods implementation +var createMethod = function (IS_RIGHT) { + return function (that, callbackfn, argumentsLength, memo) { + aFunction(callbackfn); + var O = toObject(that); + var self = IndexedObject(O); + var length = toLength(O.length); + var index = IS_RIGHT ? length - 1 : 0; + var i = IS_RIGHT ? -1 : 1; + if (argumentsLength < 2) while (true) { + if (index in self) { + memo = self[index]; + index += i; + break; + } + index += i; + if (IS_RIGHT ? index < 0 : length <= index) { + throw TypeError('Reduce of empty array with no initial value'); + } + } + for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) { + memo = callbackfn(memo, self[index], index, O); + } + return memo; + }; +}; + +module.exports = { + // `Array.prototype.reduce` method + // https://tc39.github.io/ecma262/#sec-array.prototype.reduce + left: createMethod(false), + // `Array.prototype.reduceRight` method + // https://tc39.github.io/ecma262/#sec-array.prototype.reduceright + right: createMethod(true) +}; + +},{"../internals/a-function":310,"../internals/indexed-object":383,"../internals/to-length":461,"../internals/to-object":462}],327:[function(require,module,exports){ +var isObject = require('../internals/is-object'); +var isArray = require('../internals/is-array'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var SPECIES = wellKnownSymbol('species'); + +// `ArraySpeciesCreate` abstract operation +// https://tc39.github.io/ecma262/#sec-arrayspeciescreate +module.exports = function (originalArray, length) { + var C; + if (isArray(originalArray)) { + C = originalArray.constructor; + // cross-realm fallback + if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; + else if (isObject(C)) { + C = C[SPECIES]; + if (C === null) C = undefined; + } + } return new (C === undefined ? Array : C)(length === 0 ? 0 : length); +}; + +},{"../internals/is-array":388,"../internals/is-object":392,"../internals/well-known-symbol":473}],328:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var getBuiltIn = require('../internals/get-built-in'); + +var Promise = getBuiltIn('Promise'); +var push = [].push; + +var createMethod = function (TYPE) { + var IS_TO_ARRAY = TYPE == 0; + var IS_FOR_EACH = TYPE == 1; + var IS_EVERY = TYPE == 2; + var IS_SOME = TYPE == 3; + return function (iterator, fn) { + anObject(iterator); + var next = aFunction(iterator.next); + var array = IS_TO_ARRAY ? [] : undefined; + if (!IS_TO_ARRAY) aFunction(fn); + + return new Promise(function (resolve, reject) { + var loop = function () { + try { + Promise.resolve(anObject(next.call(iterator))).then(function (step) { + try { + if (anObject(step).done) { + resolve(IS_TO_ARRAY ? array : IS_SOME ? false : IS_EVERY || undefined); + } else { + var value = step.value; + if (IS_TO_ARRAY) { + push.call(array, value); + loop(); + } else { + Promise.resolve(fn(value)).then(function (result) { + if (IS_FOR_EACH) { + loop(); + } else if (IS_EVERY) { + result ? loop() : resolve(false); + } else { + result ? resolve(IS_SOME || value) : loop(); + } + }, reject); + } + } + } catch (err) { reject(err); } + }, reject); + } catch (error) { reject(error); } + }; + + loop(); + }); + }; +}; + +module.exports = { + toArray: createMethod(0), + forEach: createMethod(1), + every: createMethod(2), + some: createMethod(3), + find: createMethod(4) +}; + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/get-built-in":372}],329:[function(require,module,exports){ +var global = require('../internals/global'); +var shared = require('../internals/shared-store'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var has = require('../internals/has'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var IS_PURE = require('../internals/is-pure'); + +var USE_FUNCTION_CONSTRUCTOR = 'USE_FUNCTION_CONSTRUCTOR'; +var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator'); +var AsyncIterator = global.AsyncIterator; +var PassedAsyncIteratorPrototype = shared.AsyncIteratorPrototype; +var AsyncIteratorPrototype, prototype; + +if (!IS_PURE) { + if (PassedAsyncIteratorPrototype) { + AsyncIteratorPrototype = PassedAsyncIteratorPrototype; + } else if (typeof AsyncIterator == 'function') { + AsyncIteratorPrototype = AsyncIterator.prototype; + } else if (shared[USE_FUNCTION_CONSTRUCTOR] || global[USE_FUNCTION_CONSTRUCTOR]) { + try { + // eslint-disable-next-line no-new-func + prototype = getPrototypeOf(getPrototypeOf(getPrototypeOf(Function('return async function*(){}()')()))); + if (getPrototypeOf(prototype) === Object.prototype) AsyncIteratorPrototype = prototype; + } catch (error) { /* empty */ } + } +} + +if (!AsyncIteratorPrototype) AsyncIteratorPrototype = {}; + +if (!has(AsyncIteratorPrototype, ASYNC_ITERATOR)) { + createNonEnumerableProperty(AsyncIteratorPrototype, ASYNC_ITERATOR, function () { + return this; + }); +} + +module.exports = AsyncIteratorPrototype; + +},{"../internals/create-non-enumerable-property":350,"../internals/global":377,"../internals/has":378,"../internals/is-pure":393,"../internals/object-get-prototype-of":420,"../internals/shared-store":447,"../internals/well-known-symbol":473}],330:[function(require,module,exports){ +var aFunction = require('../internals/a-function'); + +// optional / simple context binding +module.exports = function (fn, that, length) { + aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 0: return function () { + return fn.call(that); + }; + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; +}; + +},{"../internals/a-function":310}],331:[function(require,module,exports){ +var anObject = require('../internals/an-object'); + +// call something on iterator step with safe closing on error +module.exports = function (iterator, fn, value, ENTRIES) { + try { + return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (error) { + var returnMethod = iterator['return']; + if (returnMethod !== undefined) anObject(returnMethod.call(iterator)); + throw error; + } +}; + +},{"../internals/an-object":315}],332:[function(require,module,exports){ +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var ITERATOR = wellKnownSymbol('iterator'); +var SAFE_CLOSING = false; + +try { + var called = 0; + var iteratorWithReturn = { + next: function () { + return { done: !!called++ }; + }, + 'return': function () { + SAFE_CLOSING = true; + } + }; + iteratorWithReturn[ITERATOR] = function () { + return this; + }; + // eslint-disable-next-line no-throw-literal + Array.from(iteratorWithReturn, function () { throw 2; }); +} catch (error) { /* empty */ } + +module.exports = function (exec, SKIP_CLOSING) { + if (!SKIP_CLOSING && !SAFE_CLOSING) return false; + var ITERATION_SUPPORT = false; + try { + var object = {}; + object[ITERATOR] = function () { + return { + next: function () { + return { done: ITERATION_SUPPORT = true }; + } + }; + }; + exec(object); + } catch (error) { /* empty */ } + return ITERATION_SUPPORT; +}; + +},{"../internals/well-known-symbol":473}],333:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = function (it) { + return toString.call(it).slice(8, -1); +}; + +},{}],334:[function(require,module,exports){ +var classofRaw = require('../internals/classof-raw'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +// ES3 wrong here +var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments'; + +// fallback for IE11 Script Access Denied error +var tryGet = function (it, key) { + try { + return it[key]; + } catch (error) { /* empty */ } +}; + +// getting tag from ES6+ `Object.prototype.toString` +module.exports = function (it) { + var O, tag, result; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag + // builtinTag case + : CORRECT_ARGUMENTS ? classofRaw(O) + // ES3 arguments fallback + : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result; +}; + +},{"../internals/classof-raw":333,"../internals/well-known-symbol":473}],335:[function(require,module,exports){ +'use strict'; +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); + +// https://github.com/tc39/collection-methods +module.exports = function (/* ...elements */) { + var set = anObject(this); + var adder = aFunction(set.add); + for (var k = 0, len = arguments.length; k < len; k++) { + adder.call(set, arguments[k]); + } + return set; +}; + +},{"../internals/a-function":310,"../internals/an-object":315}],336:[function(require,module,exports){ +'use strict'; +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); + +// https://github.com/tc39/collection-methods +module.exports = function (/* ...elements */) { + var collection = anObject(this); + var remover = aFunction(collection['delete']); + var allDeleted = true; + var wasDeleted; + for (var k = 0, len = arguments.length; k < len; k++) { + wasDeleted = remover.call(collection, arguments[k]); + allDeleted = allDeleted && wasDeleted; + } + return !!allDeleted; +}; + +},{"../internals/a-function":310,"../internals/an-object":315}],337:[function(require,module,exports){ +'use strict'; +// https://tc39.github.io/proposal-setmap-offrom/ +var aFunction = require('../internals/a-function'); +var bind = require('../internals/bind-context'); +var iterate = require('../internals/iterate'); + +module.exports = function from(source /* , mapFn, thisArg */) { + var length = arguments.length; + var mapFn = length > 1 ? arguments[1] : undefined; + var mapping, A, n, boundFunction; + aFunction(this); + mapping = mapFn !== undefined; + if (mapping) aFunction(mapFn); + if (source == undefined) return new this(); + A = []; + if (mapping) { + n = 0; + boundFunction = bind(mapFn, length > 2 ? arguments[2] : undefined, 2); + iterate(source, function (nextItem) { + A.push(boundFunction(nextItem, n++)); + }); + } else { + iterate(source, A.push, A); + } + return new this(A); +}; + +},{"../internals/a-function":310,"../internals/bind-context":330,"../internals/iterate":395}],338:[function(require,module,exports){ +'use strict'; +// https://tc39.github.io/proposal-setmap-offrom/ +module.exports = function of() { + var length = arguments.length; + var A = new Array(length); + while (length--) A[length] = arguments[length]; + return new this(A); +}; + +},{}],339:[function(require,module,exports){ +'use strict'; +var defineProperty = require('../internals/object-define-property').f; +var create = require('../internals/object-create'); +var redefineAll = require('../internals/redefine-all'); +var bind = require('../internals/bind-context'); +var anInstance = require('../internals/an-instance'); +var iterate = require('../internals/iterate'); +var defineIterator = require('../internals/define-iterator'); +var setSpecies = require('../internals/set-species'); +var DESCRIPTORS = require('../internals/descriptors'); +var fastKey = require('../internals/internal-metadata').fastKey; +var InternalStateModule = require('../internals/internal-state'); + +var setInternalState = InternalStateModule.set; +var internalStateGetterFor = InternalStateModule.getterFor; + +module.exports = { + getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, CONSTRUCTOR_NAME); + setInternalState(that, { + type: CONSTRUCTOR_NAME, + index: create(null), + first: undefined, + last: undefined, + size: 0 + }); + if (!DESCRIPTORS) that.size = 0; + if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP); + }); + + var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); + + var define = function (that, key, value) { + var state = getInternalState(that); + var entry = getEntry(that, key); + var previous, index; + // change existing entry + if (entry) { + entry.value = value; + // create new entry + } else { + state.last = entry = { + index: index = fastKey(key, true), + key: key, + value: value, + previous: previous = state.last, + next: undefined, + removed: false + }; + if (!state.first) state.first = entry; + if (previous) previous.next = entry; + if (DESCRIPTORS) state.size++; + else that.size++; + // add to index + if (index !== 'F') state.index[index] = entry; + } return that; + }; + + var getEntry = function (that, key) { + var state = getInternalState(that); + // fast case + var index = fastKey(key); + var entry; + if (index !== 'F') return state.index[index]; + // frozen object case + for (entry = state.first; entry; entry = entry.next) { + if (entry.key == key) return entry; + } + }; + + redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear() { + var that = this; + var state = getInternalState(that); + var data = state.index; + var entry = state.first; + while (entry) { + entry.removed = true; + if (entry.previous) entry.previous = entry.previous.next = undefined; + delete data[entry.index]; + entry = entry.next; + } + state.first = state.last = undefined; + if (DESCRIPTORS) state.size = 0; + else that.size = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function (key) { + var that = this; + var state = getInternalState(that); + var entry = getEntry(that, key); + if (entry) { + var next = entry.next; + var prev = entry.previous; + delete state.index[entry.index]; + entry.removed = true; + if (prev) prev.next = next; + if (next) next.previous = prev; + if (state.first == entry) state.first = next; + if (state.last == entry) state.last = prev; + if (DESCRIPTORS) state.size--; + else that.size--; + } return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /* , that = undefined */) { + var state = getInternalState(this); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var entry; + while (entry = entry ? entry.next : state.first) { + boundFunction(entry.value, entry.key, this); + // revert to the last existing entry + while (entry && entry.removed) entry = entry.previous; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key) { + return !!getEntry(this, key); + } + }); + + redefineAll(C.prototype, IS_MAP ? { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key) { + var entry = getEntry(this, key); + return entry && entry.value; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value) { + return define(this, key === 0 ? 0 : key, value); + } + } : { + // 23.2.3.1 Set.prototype.add(value) + add: function add(value) { + return define(this, value = value === 0 ? 0 : value, value); + } + }); + if (DESCRIPTORS) defineProperty(C.prototype, 'size', { + get: function () { + return getInternalState(this).size; + } + }); + return C; + }, + setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) { + var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; + var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); + var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) { + setInternalState(this, { + type: ITERATOR_NAME, + target: iterated, + state: getInternalCollectionState(iterated), + kind: kind, + last: undefined + }); + }, function () { + var state = getInternalIteratorState(this); + var kind = state.kind; + var entry = state.last; + // revert to the last existing entry + while (entry && entry.removed) entry = entry.previous; + // get next entry + if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { + // or finish the iteration + state.target = undefined; + return { value: undefined, done: true }; + } + // return step by kind + if (kind == 'keys') return { value: entry.key, done: false }; + if (kind == 'values') return { value: entry.value, done: false }; + return { value: [entry.key, entry.value], done: false }; + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); + + // add [@@species], 23.1.2.2, 23.2.2.2 + setSpecies(CONSTRUCTOR_NAME); + } +}; + +},{"../internals/an-instance":314,"../internals/bind-context":330,"../internals/define-iterator":355,"../internals/descriptors":357,"../internals/internal-metadata":385,"../internals/internal-state":386,"../internals/iterate":395,"../internals/object-create":413,"../internals/object-define-property":415,"../internals/redefine-all":434,"../internals/set-species":444}],340:[function(require,module,exports){ +'use strict'; +var redefineAll = require('../internals/redefine-all'); +var getWeakData = require('../internals/internal-metadata').getWeakData; +var anObject = require('../internals/an-object'); +var isObject = require('../internals/is-object'); +var anInstance = require('../internals/an-instance'); +var iterate = require('../internals/iterate'); +var ArrayIterationModule = require('../internals/array-iteration'); +var $has = require('../internals/has'); +var InternalStateModule = require('../internals/internal-state'); + +var setInternalState = InternalStateModule.set; +var internalStateGetterFor = InternalStateModule.getterFor; +var find = ArrayIterationModule.find; +var findIndex = ArrayIterationModule.findIndex; +var id = 0; + +// fallback for uncaught frozen keys +var uncaughtFrozenStore = function (store) { + return store.frozen || (store.frozen = new UncaughtFrozenStore()); +}; + +var UncaughtFrozenStore = function () { + this.entries = []; +}; + +var findUncaughtFrozen = function (store, key) { + return find(store.entries, function (it) { + return it[0] === key; + }); +}; + +UncaughtFrozenStore.prototype = { + get: function (key) { + var entry = findUncaughtFrozen(this, key); + if (entry) return entry[1]; + }, + has: function (key) { + return !!findUncaughtFrozen(this, key); + }, + set: function (key, value) { + var entry = findUncaughtFrozen(this, key); + if (entry) entry[1] = value; + else this.entries.push([key, value]); + }, + 'delete': function (key) { + var index = findIndex(this.entries, function (it) { + return it[0] === key; + }); + if (~index) this.entries.splice(index, 1); + return !!~index; + } +}; + +module.exports = { + getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, CONSTRUCTOR_NAME); + setInternalState(that, { + type: CONSTRUCTOR_NAME, + id: id++, + frozen: undefined + }); + if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP); + }); + + var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); + + var define = function (that, key, value) { + var state = getInternalState(that); + var data = getWeakData(anObject(key), true); + if (data === true) uncaughtFrozenStore(state).set(key, value); + else data[state.id] = value; + return that; + }; + + redefineAll(C.prototype, { + // 23.3.3.2 WeakMap.prototype.delete(key) + // 23.4.3.3 WeakSet.prototype.delete(value) + 'delete': function (key) { + var state = getInternalState(this); + if (!isObject(key)) return false; + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state)['delete'](key); + return data && $has(data, state.id) && delete data[state.id]; + }, + // 23.3.3.4 WeakMap.prototype.has(key) + // 23.4.3.4 WeakSet.prototype.has(value) + has: function has(key) { + var state = getInternalState(this); + if (!isObject(key)) return false; + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state).has(key); + return data && $has(data, state.id); + } + }); + + redefineAll(C.prototype, IS_MAP ? { + // 23.3.3.3 WeakMap.prototype.get(key) + get: function get(key) { + var state = getInternalState(this); + if (isObject(key)) { + var data = getWeakData(key); + if (data === true) return uncaughtFrozenStore(state).get(key); + return data ? data[state.id] : undefined; + } + }, + // 23.3.3.5 WeakMap.prototype.set(key, value) + set: function set(key, value) { + return define(this, key, value); + } + } : { + // 23.4.3.1 WeakSet.prototype.add(value) + add: function add(value) { + return define(this, value, true); + } + }); + + return C; + } +}; + +},{"../internals/an-instance":314,"../internals/an-object":315,"../internals/array-iteration":323,"../internals/has":378,"../internals/internal-metadata":385,"../internals/internal-state":386,"../internals/is-object":392,"../internals/iterate":395,"../internals/redefine-all":434}],341:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var global = require('../internals/global'); +var isForced = require('../internals/is-forced'); +var redefine = require('../internals/redefine'); +var InternalMetadataModule = require('../internals/internal-metadata'); +var iterate = require('../internals/iterate'); +var anInstance = require('../internals/an-instance'); +var isObject = require('../internals/is-object'); +var fails = require('../internals/fails'); +var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration'); +var setToStringTag = require('../internals/set-to-string-tag'); +var inheritIfRequired = require('../internals/inherit-if-required'); + +module.exports = function (CONSTRUCTOR_NAME, wrapper, common, IS_MAP, IS_WEAK) { + var NativeConstructor = global[CONSTRUCTOR_NAME]; + var NativePrototype = NativeConstructor && NativeConstructor.prototype; + var Constructor = NativeConstructor; + var ADDER = IS_MAP ? 'set' : 'add'; + var exported = {}; + + var fixMethod = function (KEY) { + var nativeMethod = NativePrototype[KEY]; + redefine(NativePrototype, KEY, + KEY == 'add' ? function add(value) { + nativeMethod.call(this, value === 0 ? 0 : value); + return this; + } : KEY == 'delete' ? function (key) { + return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); + } : KEY == 'get' ? function get(key) { + return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key); + } : KEY == 'has' ? function has(key) { + return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); + } : function set(key, value) { + nativeMethod.call(this, key === 0 ? 0 : key, value); + return this; + } + ); + }; + + // eslint-disable-next-line max-len + if (isForced(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () { + new NativeConstructor().entries().next(); + })))) { + // create collection constructor + Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); + InternalMetadataModule.REQUIRED = true; + } else if (isForced(CONSTRUCTOR_NAME, true)) { + var instance = new Constructor(); + // early implementations not supports chaining + var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); + // most early implementations doesn't supports iterables, most modern - not close it correctly + // eslint-disable-next-line no-new + var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); }); + // for early implementations -0 and +0 not the same + var BUGGY_ZERO = !IS_WEAK && fails(function () { + // V8 ~ Chromium 42- fails only with 5+ elements + var $instance = new NativeConstructor(); + var index = 5; + while (index--) $instance[ADDER](index, index); + return !$instance.has(-0); + }); + + if (!ACCEPT_ITERABLES) { + Constructor = wrapper(function (dummy, iterable) { + anInstance(dummy, Constructor, CONSTRUCTOR_NAME); + var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor); + if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP); + return that; + }); + Constructor.prototype = NativePrototype; + NativePrototype.constructor = Constructor; + } + + if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { + fixMethod('delete'); + fixMethod('has'); + IS_MAP && fixMethod('get'); + } + + if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); + + // weak collections should not contains .clear method + if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; + } + + exported[CONSTRUCTOR_NAME] = Constructor; + $({ global: true, forced: Constructor != NativeConstructor }, exported); + + setToStringTag(Constructor, CONSTRUCTOR_NAME); + + if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP); + + return Constructor; +}; + +},{"../internals/an-instance":314,"../internals/check-correctness-of-iteration":332,"../internals/export":361,"../internals/fails":362,"../internals/global":377,"../internals/inherit-if-required":384,"../internals/internal-metadata":385,"../internals/is-forced":389,"../internals/is-object":392,"../internals/iterate":395,"../internals/redefine":435,"../internals/set-to-string-tag":445}],342:[function(require,module,exports){ +// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` +var Map = require('../modules/es.map'); +var WeakMap = require('../modules/es.weak-map'); +var create = require('../internals/object-create'); +var isObject = require('../internals/is-object'); + +var Node = function () { + // keys + this.object = null; + this.symbol = null; + // child nodes + this.primitives = null; + this.objectsByIndex = create(null); +}; + +Node.prototype.get = function (key, initializer) { + return this[key] || (this[key] = initializer()); +}; + +Node.prototype.next = function (i, it, IS_OBJECT) { + var store = IS_OBJECT + ? this.objectsByIndex[i] || (this.objectsByIndex[i] = new WeakMap()) + : this.primitives || (this.primitives = new Map()); + var entry = store.get(it); + if (!entry) store.set(it, entry = new Node()); + return entry; +}; + +var root = new Node(); + +module.exports = function () { + var active = root; + var length = arguments.length; + var i, it; + // for prevent leaking, start from objects + for (i = 0; i < length; i++) { + if (isObject(it = arguments[i])) active = active.next(i, it, true); + } + if (this === Object && active === root) throw TypeError('Composite keys must contain a non-primitive component'); + for (i = 0; i < length; i++) { + if (!isObject(it = arguments[i])) active = active.next(i, it, false); + } return active; +}; + +},{"../internals/is-object":392,"../internals/object-create":413,"../modules/es.map":519,"../modules/es.weak-map":678}],343:[function(require,module,exports){ +var has = require('../internals/has'); +var ownKeys = require('../internals/own-keys'); +var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor'); +var definePropertyModule = require('../internals/object-define-property'); + +module.exports = function (target, source) { + var keys = ownKeys(source); + var defineProperty = definePropertyModule.f; + var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); + } +}; + +},{"../internals/has":378,"../internals/object-define-property":415,"../internals/object-get-own-property-descriptor":416,"../internals/own-keys":427}],344:[function(require,module,exports){ +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var MATCH = wellKnownSymbol('match'); + +module.exports = function (METHOD_NAME) { + var regexp = /./; + try { + '/./'[METHOD_NAME](regexp); + } catch (e) { + try { + regexp[MATCH] = false; + return '/./'[METHOD_NAME](regexp); + } catch (f) { /* empty */ } + } return false; +}; + +},{"../internals/well-known-symbol":473}],345:[function(require,module,exports){ +var fails = require('../internals/fails'); + +module.exports = !fails(function () { + function F() { /* empty */ } + F.prototype.constructor = null; + return Object.getPrototypeOf(new F()) !== F.prototype; +}); + +},{"../internals/fails":362}],346:[function(require,module,exports){ +'use strict'; +var path = require('../internals/path'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var create = require('../internals/object-create'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefineAll = require('../internals/redefine-all'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var InternalStateModule = require('../internals/internal-state'); +var getBuiltIn = require('../internals/get-built-in'); + +var Promise = getBuiltIn('Promise'); + +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.get; + +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + +var $return = function (value) { + var iterator = getInternalState(this).iterator; + var $$return = iterator['return']; + return $$return === undefined + ? Promise.resolve({ done: true, value: value }) + : anObject($$return.call(iterator, value)); +}; + +var $throw = function (value) { + var iterator = getInternalState(this).iterator; + var $$throw = iterator['throw']; + return $$throw === undefined + ? Promise.reject(value) + : $$throw.call(iterator, value); +}; + +module.exports = function (nextHandler, IS_ITERATOR) { + var AsyncIteratorProxy = function AsyncIterator(state) { + state.next = aFunction(state.iterator.next); + state.done = false; + setInternalState(this, state); + }; + + AsyncIteratorProxy.prototype = redefineAll(create(path.AsyncIterator.prototype), { + next: function next(arg) { + var state = getInternalState(this); + if (state.done) return Promise.resolve({ done: true, value: undefined }); + try { + return Promise.resolve(anObject(nextHandler.call(state, arg, Promise))); + } catch (error) { + return Promise.reject(error); + } + }, + 'return': $return, + 'throw': $throw + }); + + if (!IS_ITERATOR) { + createNonEnumerableProperty(AsyncIteratorProxy.prototype, TO_STRING_TAG, 'Generator'); + } + + return AsyncIteratorProxy; +}; + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/create-non-enumerable-property":350,"../internals/get-built-in":372,"../internals/internal-state":386,"../internals/object-create":413,"../internals/path":430,"../internals/redefine-all":434,"../internals/well-known-symbol":473}],347:[function(require,module,exports){ +var requireObjectCoercible = require('../internals/require-object-coercible'); + +var quot = /"/g; + +// B.2.3.2.1 CreateHTML(string, tag, attribute, value) +// https://tc39.github.io/ecma262/#sec-createhtml +module.exports = function (string, tag, attribute, value) { + var S = String(requireObjectCoercible(string)); + var p1 = '<' + tag; + if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; + return p1 + '>' + S + ''; +}; + +},{"../internals/require-object-coercible":440}],348:[function(require,module,exports){ +'use strict'; +var IteratorPrototype = require('../internals/iterators-core').IteratorPrototype; +var create = require('../internals/object-create'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); +var setToStringTag = require('../internals/set-to-string-tag'); +var Iterators = require('../internals/iterators'); + +var returnThis = function () { return this; }; + +module.exports = function (IteratorConstructor, NAME, next) { + var TO_STRING_TAG = NAME + ' Iterator'; + IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) }); + setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true); + Iterators[TO_STRING_TAG] = returnThis; + return IteratorConstructor; +}; + +},{"../internals/create-property-descriptor":351,"../internals/iterators":397,"../internals/iterators-core":396,"../internals/object-create":413,"../internals/set-to-string-tag":445}],349:[function(require,module,exports){ +'use strict'; +var path = require('../internals/path'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var create = require('../internals/object-create'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefineAll = require('../internals/redefine-all'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var InternalStateModule = require('../internals/internal-state'); + +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.get; + +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + +var $return = function (value) { + var iterator = getInternalState(this).iterator; + var $$return = iterator['return']; + return $$return === undefined ? { done: true, value: value } : anObject($$return.call(iterator, value)); +}; + +var $throw = function (value) { + var iterator = getInternalState(this).iterator; + var $$throw = iterator['throw']; + if ($$throw === undefined) throw value; + return $$throw.call(iterator, value); +}; + +module.exports = function (nextHandler, IS_ITERATOR) { + var IteratorProxy = function Iterator(state) { + state.next = aFunction(state.iterator.next); + state.done = false; + setInternalState(this, state); + }; + + IteratorProxy.prototype = redefineAll(create(path.Iterator.prototype), { + next: function next() { + var state = getInternalState(this); + var result = state.done ? undefined : nextHandler.apply(state, arguments); + return { done: state.done, value: result }; + }, + 'return': $return, + 'throw': $throw + }); + + if (!IS_ITERATOR) { + createNonEnumerableProperty(IteratorProxy.prototype, TO_STRING_TAG, 'Generator'); + } + + return IteratorProxy; +}; + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/create-non-enumerable-property":350,"../internals/internal-state":386,"../internals/object-create":413,"../internals/path":430,"../internals/redefine-all":434,"../internals/well-known-symbol":473}],350:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var definePropertyModule = require('../internals/object-define-property'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); + +module.exports = DESCRIPTORS ? function (object, key, value) { + return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; + +},{"../internals/create-property-descriptor":351,"../internals/descriptors":357,"../internals/object-define-property":415}],351:[function(require,module,exports){ +module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; +}; + +},{}],352:[function(require,module,exports){ +'use strict'; +var toPrimitive = require('../internals/to-primitive'); +var definePropertyModule = require('../internals/object-define-property'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); + +module.exports = function (object, key, value) { + var propertyKey = toPrimitive(key); + if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value)); + else object[propertyKey] = value; +}; + +},{"../internals/create-property-descriptor":351,"../internals/object-define-property":415,"../internals/to-primitive":465}],353:[function(require,module,exports){ +'use strict'; +var fails = require('../internals/fails'); +var padStart = require('../internals/string-pad').start; + +var abs = Math.abs; +var DatePrototype = Date.prototype; +var getTime = DatePrototype.getTime; +var nativeDateToISOString = DatePrototype.toISOString; + +// `Date.prototype.toISOString` method implementation +// https://tc39.github.io/ecma262/#sec-date.prototype.toisostring +// PhantomJS / old WebKit fails here: +module.exports = (fails(function () { + return nativeDateToISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; +}) || !fails(function () { + nativeDateToISOString.call(new Date(NaN)); +})) ? function toISOString() { + if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); + var date = this; + var year = date.getUTCFullYear(); + var milliseconds = date.getUTCMilliseconds(); + var sign = year < 0 ? '-' : year > 9999 ? '+' : ''; + return sign + padStart(abs(year), sign ? 6 : 4, 0) + + '-' + padStart(date.getUTCMonth() + 1, 2, 0) + + '-' + padStart(date.getUTCDate(), 2, 0) + + 'T' + padStart(date.getUTCHours(), 2, 0) + + ':' + padStart(date.getUTCMinutes(), 2, 0) + + ':' + padStart(date.getUTCSeconds(), 2, 0) + + '.' + padStart(milliseconds, 3, 0) + + 'Z'; +} : nativeDateToISOString; + +},{"../internals/fails":362,"../internals/string-pad":452}],354:[function(require,module,exports){ +'use strict'; +var anObject = require('../internals/an-object'); +var toPrimitive = require('../internals/to-primitive'); + +module.exports = function (hint) { + if (hint !== 'string' && hint !== 'number' && hint !== 'default') { + throw TypeError('Incorrect hint'); + } return toPrimitive(anObject(this), hint !== 'number'); +}; + +},{"../internals/an-object":315,"../internals/to-primitive":465}],355:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createIteratorConstructor = require('../internals/create-iterator-constructor'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var setPrototypeOf = require('../internals/object-set-prototype-of'); +var setToStringTag = require('../internals/set-to-string-tag'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefine = require('../internals/redefine'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var IS_PURE = require('../internals/is-pure'); +var Iterators = require('../internals/iterators'); +var IteratorsCore = require('../internals/iterators-core'); + +var IteratorPrototype = IteratorsCore.IteratorPrototype; +var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS; +var ITERATOR = wellKnownSymbol('iterator'); +var KEYS = 'keys'; +var VALUES = 'values'; +var ENTRIES = 'entries'; + +var returnThis = function () { return this; }; + +module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { + createIteratorConstructor(IteratorConstructor, NAME, next); + + var getIterationMethod = function (KIND) { + if (KIND === DEFAULT && defaultIterator) return defaultIterator; + if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND]; + switch (KIND) { + case KEYS: return function keys() { return new IteratorConstructor(this, KIND); }; + case VALUES: return function values() { return new IteratorConstructor(this, KIND); }; + case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); }; + } return function () { return new IteratorConstructor(this); }; + }; + + var TO_STRING_TAG = NAME + ' Iterator'; + var INCORRECT_VALUES_NAME = false; + var IterablePrototype = Iterable.prototype; + var nativeIterator = IterablePrototype[ITERATOR] + || IterablePrototype['@@iterator'] + || DEFAULT && IterablePrototype[DEFAULT]; + var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT); + var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; + var CurrentIteratorPrototype, methods, KEY; + + // fix native + if (anyNativeIterator) { + CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable())); + if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { + if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) { + if (setPrototypeOf) { + setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype); + } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') { + createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis); + } + } + // Set @@toStringTag to native iterators + setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true); + if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis; + } + } + + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { + INCORRECT_VALUES_NAME = true; + defaultIterator = function values() { return nativeIterator.call(this); }; + } + + // define iterator + if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) { + createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator); + } + Iterators[NAME] = defaultIterator; + + // export additional methods + if (DEFAULT) { + methods = { + values: getIterationMethod(VALUES), + keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), + entries: getIterationMethod(ENTRIES) + }; + if (FORCED) for (KEY in methods) { + if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { + redefine(IterablePrototype, KEY, methods[KEY]); + } + } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods); + } + + return methods; +}; + +},{"../internals/create-iterator-constructor":348,"../internals/create-non-enumerable-property":350,"../internals/export":361,"../internals/is-pure":393,"../internals/iterators":397,"../internals/iterators-core":396,"../internals/object-get-prototype-of":420,"../internals/object-set-prototype-of":424,"../internals/redefine":435,"../internals/set-to-string-tag":445,"../internals/well-known-symbol":473}],356:[function(require,module,exports){ +var path = require('../internals/path'); +var has = require('../internals/has'); +var wrappedWellKnownSymbolModule = require('../internals/wrapped-well-known-symbol'); +var defineProperty = require('../internals/object-define-property').f; + +module.exports = function (NAME) { + var Symbol = path.Symbol || (path.Symbol = {}); + if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, { + value: wrappedWellKnownSymbolModule.f(NAME) + }); +}; + +},{"../internals/has":378,"../internals/object-define-property":415,"../internals/path":430,"../internals/wrapped-well-known-symbol":475}],357:[function(require,module,exports){ +var fails = require('../internals/fails'); + +// Thank's IE8 for his funny defineProperty +module.exports = !fails(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); + +},{"../internals/fails":362}],358:[function(require,module,exports){ +var global = require('../internals/global'); +var isObject = require('../internals/is-object'); + +var document = global.document; +// typeof document.createElement is 'object' in old IE +var EXISTS = isObject(document) && isObject(document.createElement); + +module.exports = function (it) { + return EXISTS ? document.createElement(it) : {}; +}; + +},{"../internals/global":377,"../internals/is-object":392}],359:[function(require,module,exports){ +// iterable DOM collections +// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods +module.exports = { + CSSRuleList: 0, + CSSStyleDeclaration: 0, + CSSValueList: 0, + ClientRectList: 0, + DOMRectList: 0, + DOMStringList: 0, + DOMTokenList: 1, + DataTransferItemList: 0, + FileList: 0, + HTMLAllCollection: 0, + HTMLCollection: 0, + HTMLFormElement: 0, + HTMLSelectElement: 0, + MediaList: 0, + MimeTypeArray: 0, + NamedNodeMap: 0, + NodeList: 1, + PaintRequestList: 0, + Plugin: 0, + PluginArray: 0, + SVGLengthList: 0, + SVGNumberList: 0, + SVGPathSegList: 0, + SVGPointList: 0, + SVGStringList: 0, + SVGTransformList: 0, + SourceBufferList: 0, + StyleSheetList: 0, + TextTrackCueList: 0, + TextTrackList: 0, + TouchList: 0 +}; + +},{}],360:[function(require,module,exports){ +// IE8- don't enum bug keys +module.exports = [ + 'constructor', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'toLocaleString', + 'toString', + 'valueOf' +]; + +},{}],361:[function(require,module,exports){ +var global = require('../internals/global'); +var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefine = require('../internals/redefine'); +var setGlobal = require('../internals/set-global'); +var copyConstructorProperties = require('../internals/copy-constructor-properties'); +var isForced = require('../internals/is-forced'); + +/* + options.target - name of the target object + options.global - target is the global object + options.stat - export as static methods of target + options.proto - export as prototype methods of target + options.real - real prototype method for the `pure` version + options.forced - export even if the native feature is available + options.bind - bind methods to the target, required for the `pure` version + options.wrap - wrap constructors to preventing global pollution, required for the `pure` version + options.unsafe - use the simple assignment of property instead of delete + defineProperty + options.sham - add a flag to not completely full polyfills + options.enumerable - export as enumerable property + options.noTargetGet - prevent calling a getter on target +*/ +module.exports = function (options, source) { + var TARGET = options.target; + var GLOBAL = options.global; + var STATIC = options.stat; + var FORCED, target, key, targetProperty, sourceProperty, descriptor; + if (GLOBAL) { + target = global; + } else if (STATIC) { + target = global[TARGET] || setGlobal(TARGET, {}); + } else { + target = (global[TARGET] || {}).prototype; + } + if (target) for (key in source) { + sourceProperty = source[key]; + if (options.noTargetGet) { + descriptor = getOwnPropertyDescriptor(target, key); + targetProperty = descriptor && descriptor.value; + } else targetProperty = target[key]; + FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); + // contained in target + if (!FORCED && targetProperty !== undefined) { + if (typeof sourceProperty === typeof targetProperty) continue; + copyConstructorProperties(sourceProperty, targetProperty); + } + // add a flag to not completely full polyfills + if (options.sham || (targetProperty && targetProperty.sham)) { + createNonEnumerableProperty(sourceProperty, 'sham', true); + } + // extend global + redefine(target, key, sourceProperty, options); + } +}; + +},{"../internals/copy-constructor-properties":343,"../internals/create-non-enumerable-property":350,"../internals/global":377,"../internals/is-forced":389,"../internals/object-get-own-property-descriptor":416,"../internals/redefine":435,"../internals/set-global":443}],362:[function(require,module,exports){ +module.exports = function (exec) { + try { + return !!exec(); + } catch (error) { + return true; + } +}; + +},{}],363:[function(require,module,exports){ +'use strict'; +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefine = require('../internals/redefine'); +var fails = require('../internals/fails'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var regexpExec = require('../internals/regexp-exec'); + +var SPECIES = wellKnownSymbol('species'); + +var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () { + // #replace needs built-in support for named groups. + // #match works fine because it just return the exec results, even if it has + // a "grops" property. + var re = /./; + re.exec = function () { + var result = []; + result.groups = { a: '7' }; + return result; + }; + return ''.replace(re, '$') !== '7'; +}); + +// Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec +// Weex JS has frozen built-in prototypes, so use try / catch wrapper +var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () { + var re = /(?:)/; + var originalExec = re.exec; + re.exec = function () { return originalExec.apply(this, arguments); }; + var result = 'ab'.split(re); + return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b'; +}); + +module.exports = function (KEY, length, exec, sham) { + var SYMBOL = wellKnownSymbol(KEY); + + var DELEGATES_TO_SYMBOL = !fails(function () { + // String methods call symbol-named RegEp methods + var O = {}; + O[SYMBOL] = function () { return 7; }; + return ''[KEY](O) != 7; + }); + + var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () { + // Symbol-named RegExp methods call .exec + var execCalled = false; + var re = /a/; + + if (KEY === 'split') { + // We can't use real regex here since it causes deoptimization + // and serious performance degradation in V8 + // https://github.com/zloirock/core-js/issues/306 + re = {}; + // RegExp[@@split] doesn't call the regex's exec method, but first creates + // a new one. We need to return the patched regex when creating the new one. + re.constructor = {}; + re.constructor[SPECIES] = function () { return re; }; + re.flags = ''; + re[SYMBOL] = /./[SYMBOL]; + } + + re.exec = function () { execCalled = true; return null; }; + + re[SYMBOL](''); + return !execCalled; + }); + + if ( + !DELEGATES_TO_SYMBOL || + !DELEGATES_TO_EXEC || + (KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) || + (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC) + ) { + var nativeRegExpMethod = /./[SYMBOL]; + var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) { + if (regexp.exec === regexpExec) { + if (DELEGATES_TO_SYMBOL && !forceStringMethod) { + // The native String method already delegates to @@method (this + // polyfilled function), leasing to infinite recursion. + // We avoid it by directly calling the native @@method method. + return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) }; + } + return { done: true, value: nativeMethod.call(str, regexp, arg2) }; + } + return { done: false }; + }); + var stringMethod = methods[0]; + var regexMethod = methods[1]; + + redefine(String.prototype, KEY, stringMethod); + redefine(RegExp.prototype, SYMBOL, length == 2 + // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) + // 21.2.5.11 RegExp.prototype[@@split](string, limit) + ? function (string, arg) { return regexMethod.call(string, this, arg); } + // 21.2.5.6 RegExp.prototype[@@match](string) + // 21.2.5.9 RegExp.prototype[@@search](string) + : function (string) { return regexMethod.call(string, this); } + ); + if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true); + } +}; + +},{"../internals/create-non-enumerable-property":350,"../internals/fails":362,"../internals/redefine":435,"../internals/regexp-exec":438,"../internals/well-known-symbol":473}],364:[function(require,module,exports){ +'use strict'; +var isArray = require('../internals/is-array'); +var toLength = require('../internals/to-length'); +var bind = require('../internals/bind-context'); + +// `FlattenIntoArray` abstract operation +// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray +var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) { + var targetIndex = start; + var sourceIndex = 0; + var mapFn = mapper ? bind(mapper, thisArg, 3) : false; + var element; + + while (sourceIndex < sourceLen) { + if (sourceIndex in source) { + element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; + + if (depth > 0 && isArray(element)) { + targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; + } else { + if (targetIndex >= 0x1FFFFFFFFFFFFF) throw TypeError('Exceed the acceptable array length'); + target[targetIndex] = element; + } + + targetIndex++; + } + sourceIndex++; + } + return targetIndex; +}; + +module.exports = flattenIntoArray; + +},{"../internals/bind-context":330,"../internals/is-array":388,"../internals/to-length":461}],365:[function(require,module,exports){ +'use strict'; +var IS_PURE = require('../internals/is-pure'); +var global = require('../internals/global'); +var fails = require('../internals/fails'); + +// Forced replacement object prototype accessors methods +module.exports = IS_PURE || !fails(function () { + var key = Math.random(); + // In FF throws only define methods + // eslint-disable-next-line no-undef, no-useless-call + __defineSetter__.call(null, key, function () { /* empty */ }); + delete global[key]; +}); + +},{"../internals/fails":362,"../internals/global":377,"../internals/is-pure":393}],366:[function(require,module,exports){ +var fails = require('../internals/fails'); + +// check the existence of a method, lowercase +// of a tag and escaping quotes in arguments +module.exports = function (METHOD_NAME) { + return fails(function () { + var test = ''[METHOD_NAME]('"'); + return test !== test.toLowerCase() || test.split('"').length > 3; + }); +}; + +},{"../internals/fails":362}],367:[function(require,module,exports){ +var fails = require('../internals/fails'); +var whitespaces = require('../internals/whitespaces'); + +var non = '\u200B\u0085\u180E'; + +// check that a method works with the correct list +// of whitespaces and has a correct name +module.exports = function (METHOD_NAME) { + return fails(function () { + return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME; + }); +}; + +},{"../internals/fails":362,"../internals/whitespaces":474}],368:[function(require,module,exports){ +var fails = require('../internals/fails'); + +module.exports = !fails(function () { + return Object.isExtensible(Object.preventExtensions({})); +}); + +},{"../internals/fails":362}],369:[function(require,module,exports){ +'use strict'; +var aFunction = require('../internals/a-function'); +var isObject = require('../internals/is-object'); + +var slice = [].slice; +var factories = {}; + +var construct = function (C, argsLength, args) { + if (!(argsLength in factories)) { + for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']'; + // eslint-disable-next-line no-new-func + factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')'); + } return factories[argsLength](C, args); +}; + +// `Function.prototype.bind` method implementation +// https://tc39.github.io/ecma262/#sec-function.prototype.bind +module.exports = Function.bind || function bind(that /* , ...args */) { + var fn = aFunction(this); + var partArgs = slice.call(arguments, 1); + var boundFunction = function bound(/* args... */) { + var args = partArgs.concat(slice.call(arguments)); + return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args); + }; + if (isObject(fn.prototype)) boundFunction.prototype = fn.prototype; + return boundFunction; +}; + +},{"../internals/a-function":310,"../internals/is-object":392}],370:[function(require,module,exports){ +var shared = require('../internals/shared'); + +module.exports = shared('native-function-to-string', Function.toString); + +},{"../internals/shared":448}],371:[function(require,module,exports){ +var getIteratorMethod = require('../internals/get-iterator-method'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator'); + +module.exports = function (it) { + var method = it[ASYNC_ITERATOR]; + return method === undefined ? getIteratorMethod(it) : method; +}; + +},{"../internals/get-iterator-method":373,"../internals/well-known-symbol":473}],372:[function(require,module,exports){ +var path = require('../internals/path'); +var global = require('../internals/global'); + +var aFunction = function (variable) { + return typeof variable == 'function' ? variable : undefined; +}; + +module.exports = function (namespace, method) { + return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace]) + : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method]; +}; + +},{"../internals/global":377,"../internals/path":430}],373:[function(require,module,exports){ +var classof = require('../internals/classof'); +var Iterators = require('../internals/iterators'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var ITERATOR = wellKnownSymbol('iterator'); + +module.exports = function (it) { + if (it != undefined) return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; +}; + +},{"../internals/classof":334,"../internals/iterators":397,"../internals/well-known-symbol":473}],374:[function(require,module,exports){ +var anObject = require('../internals/an-object'); +var getIteratorMethod = require('../internals/get-iterator-method'); + +module.exports = function (it) { + var iteratorMethod = getIteratorMethod(it); + if (typeof iteratorMethod != 'function') { + throw TypeError(String(it) + ' is not iterable'); + } return anObject(iteratorMethod.call(it)); +}; + +},{"../internals/an-object":315,"../internals/get-iterator-method":373}],375:[function(require,module,exports){ +var IS_PURE = require('../internals/is-pure'); +var getIterator = require('../internals/get-iterator'); + +module.exports = IS_PURE ? getIterator : function (it) { + // eslint-disable-next-line no-undef + return Map.prototype.entries.call(it); +}; + +},{"../internals/get-iterator":374,"../internals/is-pure":393}],376:[function(require,module,exports){ +var IS_PURE = require('../internals/is-pure'); +var getIterator = require('../internals/get-iterator'); + +module.exports = IS_PURE ? getIterator : function (it) { + // eslint-disable-next-line no-undef + return Set.prototype.values.call(it); +}; + +},{"../internals/get-iterator":374,"../internals/is-pure":393}],377:[function(require,module,exports){ +(function (global){ +var check = function (it) { + return it && it.Math == Math && it; +}; + +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +module.exports = + // eslint-disable-next-line no-undef + check(typeof globalThis == 'object' && globalThis) || + check(typeof window == 'object' && window) || + check(typeof self == 'object' && self) || + check(typeof global == 'object' && global) || + // eslint-disable-next-line no-new-func + Function('return this')(); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],378:[function(require,module,exports){ +var hasOwnProperty = {}.hasOwnProperty; + +module.exports = function (it, key) { + return hasOwnProperty.call(it, key); +}; + +},{}],379:[function(require,module,exports){ +module.exports = {}; + +},{}],380:[function(require,module,exports){ +var global = require('../internals/global'); + +module.exports = function (a, b) { + var console = global.console; + if (console && console.error) { + arguments.length === 1 ? console.error(a) : console.error(a, b); + } +}; + +},{"../internals/global":377}],381:[function(require,module,exports){ +var getBuiltIn = require('../internals/get-built-in'); + +module.exports = getBuiltIn('document', 'documentElement'); + +},{"../internals/get-built-in":372}],382:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var fails = require('../internals/fails'); +var createElement = require('../internals/document-create-element'); + +// Thank's IE8 for his funny defineProperty +module.exports = !DESCRIPTORS && !fails(function () { + return Object.defineProperty(createElement('div'), 'a', { + get: function () { return 7; } + }).a != 7; +}); + +},{"../internals/descriptors":357,"../internals/document-create-element":358,"../internals/fails":362}],383:[function(require,module,exports){ +var fails = require('../internals/fails'); +var classof = require('../internals/classof-raw'); + +var split = ''.split; + +// fallback for non-array-like ES3 and non-enumerable old V8 strings +module.exports = fails(function () { + // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 + // eslint-disable-next-line no-prototype-builtins + return !Object('z').propertyIsEnumerable(0); +}) ? function (it) { + return classof(it) == 'String' ? split.call(it, '') : Object(it); +} : Object; + +},{"../internals/classof-raw":333,"../internals/fails":362}],384:[function(require,module,exports){ +var isObject = require('../internals/is-object'); +var setPrototypeOf = require('../internals/object-set-prototype-of'); + +// makes subclassing work correct for wrapped built-ins +module.exports = function ($this, dummy, Wrapper) { + var NewTarget, NewTargetPrototype; + if ( + // it can work only with native `setPrototypeOf` + setPrototypeOf && + // we haven't completely correct pre-ES6 way for getting `new.target`, so use this + typeof (NewTarget = dummy.constructor) == 'function' && + NewTarget !== Wrapper && + isObject(NewTargetPrototype = NewTarget.prototype) && + NewTargetPrototype !== Wrapper.prototype + ) setPrototypeOf($this, NewTargetPrototype); + return $this; +}; + +},{"../internals/is-object":392,"../internals/object-set-prototype-of":424}],385:[function(require,module,exports){ +var hiddenKeys = require('../internals/hidden-keys'); +var isObject = require('../internals/is-object'); +var has = require('../internals/has'); +var defineProperty = require('../internals/object-define-property').f; +var uid = require('../internals/uid'); +var FREEZING = require('../internals/freezing'); + +var METADATA = uid('meta'); +var id = 0; + +var isExtensible = Object.isExtensible || function () { + return true; +}; + +var setMetadata = function (it) { + defineProperty(it, METADATA, { value: { + objectID: 'O' + ++id, // object ID + weakData: {} // weak collections IDs + } }); +}; + +var fastKey = function (it, create) { + // return a primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!has(it, METADATA)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMetadata(it); + // return object ID + } return it[METADATA].objectID; +}; + +var getWeakData = function (it, create) { + if (!has(it, METADATA)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMetadata(it); + // return the store of weak collections IDs + } return it[METADATA].weakData; +}; + +// add metadata on freeze-family methods calling +var onFreeze = function (it) { + if (FREEZING && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it); + return it; +}; + +var meta = module.exports = { + REQUIRED: false, + fastKey: fastKey, + getWeakData: getWeakData, + onFreeze: onFreeze +}; + +hiddenKeys[METADATA] = true; + +},{"../internals/freezing":368,"../internals/has":378,"../internals/hidden-keys":379,"../internals/is-object":392,"../internals/object-define-property":415,"../internals/uid":469}],386:[function(require,module,exports){ +var NATIVE_WEAK_MAP = require('../internals/native-weak-map'); +var global = require('../internals/global'); +var isObject = require('../internals/is-object'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var objectHas = require('../internals/has'); +var sharedKey = require('../internals/shared-key'); +var hiddenKeys = require('../internals/hidden-keys'); + +var WeakMap = global.WeakMap; +var set, get, has; + +var enforce = function (it) { + return has(it) ? get(it) : set(it, {}); +}; + +var getterFor = function (TYPE) { + return function (it) { + var state; + if (!isObject(it) || (state = get(it)).type !== TYPE) { + throw TypeError('Incompatible receiver, ' + TYPE + ' required'); + } return state; + }; +}; + +if (NATIVE_WEAK_MAP) { + var store = new WeakMap(); + var wmget = store.get; + var wmhas = store.has; + var wmset = store.set; + set = function (it, metadata) { + wmset.call(store, it, metadata); + return metadata; + }; + get = function (it) { + return wmget.call(store, it) || {}; + }; + has = function (it) { + return wmhas.call(store, it); + }; +} else { + var STATE = sharedKey('state'); + hiddenKeys[STATE] = true; + set = function (it, metadata) { + createNonEnumerableProperty(it, STATE, metadata); + return metadata; + }; + get = function (it) { + return objectHas(it, STATE) ? it[STATE] : {}; + }; + has = function (it) { + return objectHas(it, STATE); + }; +} + +module.exports = { + set: set, + get: get, + has: has, + enforce: enforce, + getterFor: getterFor +}; + +},{"../internals/create-non-enumerable-property":350,"../internals/global":377,"../internals/has":378,"../internals/hidden-keys":379,"../internals/is-object":392,"../internals/native-weak-map":408,"../internals/shared-key":446}],387:[function(require,module,exports){ +var wellKnownSymbol = require('../internals/well-known-symbol'); +var Iterators = require('../internals/iterators'); + +var ITERATOR = wellKnownSymbol('iterator'); +var ArrayPrototype = Array.prototype; + +// check on default Array iterator +module.exports = function (it) { + return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); +}; + +},{"../internals/iterators":397,"../internals/well-known-symbol":473}],388:[function(require,module,exports){ +var classof = require('../internals/classof-raw'); + +// `IsArray` abstract operation +// https://tc39.github.io/ecma262/#sec-isarray +module.exports = Array.isArray || function isArray(arg) { + return classof(arg) == 'Array'; +}; + +},{"../internals/classof-raw":333}],389:[function(require,module,exports){ +var fails = require('../internals/fails'); + +var replacement = /#|\.prototype\./; + +var isForced = function (feature, detection) { + var value = data[normalize(feature)]; + return value == POLYFILL ? true + : value == NATIVE ? false + : typeof detection == 'function' ? fails(detection) + : !!detection; +}; + +var normalize = isForced.normalize = function (string) { + return String(string).replace(replacement, '.').toLowerCase(); +}; + +var data = isForced.data = {}; +var NATIVE = isForced.NATIVE = 'N'; +var POLYFILL = isForced.POLYFILL = 'P'; + +module.exports = isForced; + +},{"../internals/fails":362}],390:[function(require,module,exports){ +var isObject = require('../internals/is-object'); + +var floor = Math.floor; + +// `Number.isInteger` method implementation +// https://tc39.github.io/ecma262/#sec-number.isinteger +module.exports = function isInteger(it) { + return !isObject(it) && isFinite(it) && floor(it) === it; +}; + +},{"../internals/is-object":392}],391:[function(require,module,exports){ +var userAgent = require('../internals/user-agent'); + +module.exports = /(iphone|ipod|ipad).*applewebkit/i.test(userAgent); + +},{"../internals/user-agent":470}],392:[function(require,module,exports){ +module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +},{}],393:[function(require,module,exports){ +module.exports = false; + +},{}],394:[function(require,module,exports){ +var isObject = require('../internals/is-object'); +var classof = require('../internals/classof-raw'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var MATCH = wellKnownSymbol('match'); + +// `IsRegExp` abstract operation +// https://tc39.github.io/ecma262/#sec-isregexp +module.exports = function (it) { + var isRegExp; + return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) == 'RegExp'); +}; + +},{"../internals/classof-raw":333,"../internals/is-object":392,"../internals/well-known-symbol":473}],395:[function(require,module,exports){ +var anObject = require('../internals/an-object'); +var isArrayIteratorMethod = require('../internals/is-array-iterator-method'); +var toLength = require('../internals/to-length'); +var bind = require('../internals/bind-context'); +var getIteratorMethod = require('../internals/get-iterator-method'); +var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing'); + +var Result = function (stopped, result) { + this.stopped = stopped; + this.result = result; +}; + +var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) { + var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1); + var iterator, iterFn, index, length, result, next, step; + + if (IS_ITERATOR) { + iterator = iterable; + } else { + iterFn = getIteratorMethod(iterable); + if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); + // optimisation for array iterators + if (isArrayIteratorMethod(iterFn)) { + for (index = 0, length = toLength(iterable.length); length > index; index++) { + result = AS_ENTRIES + ? boundFunction(anObject(step = iterable[index])[0], step[1]) + : boundFunction(iterable[index]); + if (result && result instanceof Result) return result; + } return new Result(false); + } + iterator = iterFn.call(iterable); + } + + next = iterator.next; + while (!(step = next.call(iterator)).done) { + result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES); + if (typeof result == 'object' && result && result instanceof Result) return result; + } return new Result(false); +}; + +iterate.stop = function (result) { + return new Result(true, result); +}; + +},{"../internals/an-object":315,"../internals/bind-context":330,"../internals/call-with-safe-iteration-closing":331,"../internals/get-iterator-method":373,"../internals/is-array-iterator-method":387,"../internals/to-length":461}],396:[function(require,module,exports){ +'use strict'; +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var has = require('../internals/has'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var IS_PURE = require('../internals/is-pure'); + +var ITERATOR = wellKnownSymbol('iterator'); +var BUGGY_SAFARI_ITERATORS = false; + +var returnThis = function () { return this; }; + +// `%IteratorPrototype%` object +// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object +var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; + +if ([].keys) { + arrayIterator = [].keys(); + // Safari 8 has buggy iterators w/o `next` + if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; + else { + PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); + if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; + } +} + +if (IteratorPrototype == undefined) IteratorPrototype = {}; + +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) { + createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis); +} + +module.exports = { + IteratorPrototype: IteratorPrototype, + BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS +}; + +},{"../internals/create-non-enumerable-property":350,"../internals/has":378,"../internals/is-pure":393,"../internals/object-get-prototype-of":420,"../internals/well-known-symbol":473}],397:[function(require,module,exports){ +arguments[4][379][0].apply(exports,arguments) +},{"dup":379}],398:[function(require,module,exports){ +'use strict'; +var anObject = require('../internals/an-object'); + +// `Map.prototype.upsert` method +// https://github.com/thumbsupep/proposal-upsert +module.exports = function upsert(key, updateFn /* , insertFn */) { + var map = anObject(this); + var insertFn = arguments.length > 2 ? arguments[2] : undefined; + var value; + if (typeof updateFn != 'function' && typeof insertFn != 'function') { + throw TypeError('At least one callback required'); + } + if (map.has(key)) { + value = map.get(key); + if (typeof updateFn == 'function') { + value = updateFn(value); + map.set(key, value); + } + } else if (typeof insertFn == 'function') { + value = insertFn(); + map.set(key, value); + } return value; +}; + +},{"../internals/an-object":315}],399:[function(require,module,exports){ +var nativeExpm1 = Math.expm1; +var exp = Math.exp; + +// `Math.expm1` method implementation +// https://tc39.github.io/ecma262/#sec-math.expm1 +module.exports = (!nativeExpm1 + // Old FF bug + || nativeExpm1(10) > 22025.465794806719 || nativeExpm1(10) < 22025.4657948067165168 + // Tor Browser bug + || nativeExpm1(-2e-17) != -2e-17 +) ? function expm1(x) { + return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; +} : nativeExpm1; + +},{}],400:[function(require,module,exports){ +var sign = require('../internals/math-sign'); + +var abs = Math.abs; +var pow = Math.pow; +var EPSILON = pow(2, -52); +var EPSILON32 = pow(2, -23); +var MAX32 = pow(2, 127) * (2 - EPSILON32); +var MIN32 = pow(2, -126); + +var roundTiesToEven = function (n) { + return n + 1 / EPSILON - 1 / EPSILON; +}; + +// `Math.fround` method implementation +// https://tc39.github.io/ecma262/#sec-math.fround +module.exports = Math.fround || function fround(x) { + var $abs = abs(x); + var $sign = sign(x); + var a, result; + if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; + a = (1 + EPSILON32 / EPSILON) * $abs; + result = a - (a - $abs); + // eslint-disable-next-line no-self-compare + if (result > MAX32 || result != result) return $sign * Infinity; + return $sign * result; +}; + +},{"../internals/math-sign":403}],401:[function(require,module,exports){ +var log = Math.log; + +// `Math.log1p` method implementation +// https://tc39.github.io/ecma262/#sec-math.log1p +module.exports = Math.log1p || function log1p(x) { + return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); +}; + +},{}],402:[function(require,module,exports){ +// `Math.scale` method implementation +// https://rwaldron.github.io/proposal-math-extensions/ +module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { + if ( + arguments.length === 0 + /* eslint-disable no-self-compare */ + || x != x + || inLow != inLow + || inHigh != inHigh + || outLow != outLow + || outHigh != outHigh + /* eslint-enable no-self-compare */ + ) return NaN; + if (x === Infinity || x === -Infinity) return x; + return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; +}; + +},{}],403:[function(require,module,exports){ +// `Math.sign` method implementation +// https://tc39.github.io/ecma262/#sec-math.sign +module.exports = Math.sign || function sign(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; +}; + +},{}],404:[function(require,module,exports){ +var global = require('../internals/global'); +var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; +var classof = require('../internals/classof-raw'); +var macrotask = require('../internals/task').set; +var IS_IOS = require('../internals/is-ios'); + +var MutationObserver = global.MutationObserver || global.WebKitMutationObserver; +var process = global.process; +var Promise = global.Promise; +var IS_NODE = classof(process) == 'process'; +// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask` +var queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask'); +var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value; + +var flush, head, last, notify, toggle, node, promise, then; + +// modern engines have queueMicrotask method +if (!queueMicrotask) { + flush = function () { + var parent, fn; + if (IS_NODE && (parent = process.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (error) { + if (head) notify(); + else last = undefined; + throw error; + } + } last = undefined; + if (parent) parent.enter(); + }; + + // Node.js + if (IS_NODE) { + notify = function () { + process.nextTick(flush); + }; + // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 + } else if (MutationObserver && !IS_IOS) { + toggle = true; + node = document.createTextNode(''); + new MutationObserver(flush).observe(node, { characterData: true }); + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + // Promise.resolve without an argument throws an error in LG WebOS 2 + promise = Promise.resolve(undefined); + then = promise.then; + notify = function () { + then.call(promise, flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } +} + +module.exports = queueMicrotask || function (fn) { + var task = { fn: fn, next: undefined }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } last = task; +}; + +},{"../internals/classof-raw":333,"../internals/global":377,"../internals/is-ios":391,"../internals/object-get-own-property-descriptor":416,"../internals/task":455}],405:[function(require,module,exports){ +var global = require('../internals/global'); + +module.exports = global.Promise; + +},{"../internals/global":377}],406:[function(require,module,exports){ +var fails = require('../internals/fails'); + +module.exports = !!Object.getOwnPropertySymbols && !fails(function () { + // Chrome 38 Symbol has incorrect toString conversion + // eslint-disable-next-line no-undef + return !String(Symbol()); +}); + +},{"../internals/fails":362}],407:[function(require,module,exports){ +var fails = require('../internals/fails'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var IS_PURE = require('../internals/is-pure'); + +var ITERATOR = wellKnownSymbol('iterator'); + +module.exports = !fails(function () { + var url = new URL('b?a=1&b=2&c=3', 'http://a'); + var searchParams = url.searchParams; + var result = ''; + url.pathname = 'c%20d'; + searchParams.forEach(function (value, key) { + searchParams['delete']('b'); + result += key + value; + }); + return (IS_PURE && !url.toJSON) + || !searchParams.sort + || url.href !== 'http://a/c%20d?a=1&c=3' + || searchParams.get('c') !== '3' + || String(new URLSearchParams('?a=1')) !== 'a=1' + || !searchParams[ITERATOR] + // throws in Edge + || new URL('https://a@b').username !== 'a' + || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' + // not punycoded in Edge + || new URL('http://тест').host !== 'xn--e1aybc' + // not escaped in Chrome 62- + || new URL('http://a#б').hash !== '#%D0%B1' + // fails in Chrome 66- + || result !== 'a1c3' + // throws in Safari + || new URL('http://x', undefined).host !== 'x'; +}); + +},{"../internals/fails":362,"../internals/is-pure":393,"../internals/well-known-symbol":473}],408:[function(require,module,exports){ +var global = require('../internals/global'); +var nativeFunctionToString = require('../internals/function-to-string'); + +var WeakMap = global.WeakMap; + +module.exports = typeof WeakMap === 'function' && /native code/.test(nativeFunctionToString.call(WeakMap)); + +},{"../internals/function-to-string":370,"../internals/global":377}],409:[function(require,module,exports){ +'use strict'; +var aFunction = require('../internals/a-function'); + +var PromiseCapability = function (C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); +}; + +// 25.4.1.5 NewPromiseCapability(C) +module.exports.f = function (C) { + return new PromiseCapability(C); +}; + +},{"../internals/a-function":310}],410:[function(require,module,exports){ +var isRegExp = require('../internals/is-regexp'); + +module.exports = function (it) { + if (isRegExp(it)) { + throw TypeError("The method doesn't accept regular expressions"); + } return it; +}; + +},{"../internals/is-regexp":394}],411:[function(require,module,exports){ +var global = require('../internals/global'); + +var globalIsFinite = global.isFinite; + +// `Number.isFinite` method +// https://tc39.github.io/ecma262/#sec-number.isfinite +module.exports = Number.isFinite || function isFinite(it) { + return typeof it == 'number' && globalIsFinite(it); +}; + +},{"../internals/global":377}],412:[function(require,module,exports){ +'use strict'; +var DESCRIPTORS = require('../internals/descriptors'); +var fails = require('../internals/fails'); +var objectKeys = require('../internals/object-keys'); +var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols'); +var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable'); +var toObject = require('../internals/to-object'); +var IndexedObject = require('../internals/indexed-object'); + +var nativeAssign = Object.assign; + +// `Object.assign` method +// https://tc39.github.io/ecma262/#sec-object.assign +// should work with symbols and should have deterministic property order (V8 bug) +module.exports = !nativeAssign || fails(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var symbol = Symbol(); + var alphabet = 'abcdefghijklmnopqrst'; + A[symbol] = 7; + alphabet.split('').forEach(function (chr) { B[chr] = chr; }); + return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet; +}) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = toObject(target); + var argumentsLength = arguments.length; + var index = 1; + var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; + var propertyIsEnumerable = propertyIsEnumerableModule.f; + while (argumentsLength > index) { + var S = IndexedObject(arguments[index++]); + var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) { + key = keys[j++]; + if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key]; + } + } return T; +} : nativeAssign; + +},{"../internals/descriptors":357,"../internals/fails":362,"../internals/indexed-object":383,"../internals/object-get-own-property-symbols":419,"../internals/object-keys":422,"../internals/object-property-is-enumerable":423,"../internals/to-object":462}],413:[function(require,module,exports){ +var anObject = require('../internals/an-object'); +var defineProperties = require('../internals/object-define-properties'); +var enumBugKeys = require('../internals/enum-bug-keys'); +var hiddenKeys = require('../internals/hidden-keys'); +var html = require('../internals/html'); +var documentCreateElement = require('../internals/document-create-element'); +var sharedKey = require('../internals/shared-key'); +var IE_PROTO = sharedKey('IE_PROTO'); + +var PROTOTYPE = 'prototype'; +var Empty = function () { /* empty */ }; + +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = documentCreateElement('iframe'); + var length = enumBugKeys.length; + var lt = '<'; + var script = 'script'; + var gt = '>'; + var js = 'java' + script + ':'; + var iframeDocument; + iframe.style.display = 'none'; + html.appendChild(iframe); + iframe.src = String(js); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + script + gt + 'document.F=Object' + lt + '/' + script + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (length--) delete createDict[PROTOTYPE][enumBugKeys[length]]; + return createDict(); +}; + +// `Object.create` method +// https://tc39.github.io/ecma262/#sec-object.create +module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE] = anObject(O); + result = new Empty(); + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : defineProperties(result, Properties); +}; + +hiddenKeys[IE_PROTO] = true; + +},{"../internals/an-object":315,"../internals/document-create-element":358,"../internals/enum-bug-keys":360,"../internals/hidden-keys":379,"../internals/html":381,"../internals/object-define-properties":414,"../internals/shared-key":446}],414:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var definePropertyModule = require('../internals/object-define-property'); +var anObject = require('../internals/an-object'); +var objectKeys = require('../internals/object-keys'); + +// `Object.defineProperties` method +// https://tc39.github.io/ecma262/#sec-object.defineproperties +module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = objectKeys(Properties); + var length = keys.length; + var index = 0; + var key; + while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]); + return O; +}; + +},{"../internals/an-object":315,"../internals/descriptors":357,"../internals/object-define-property":415,"../internals/object-keys":422}],415:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var IE8_DOM_DEFINE = require('../internals/ie8-dom-define'); +var anObject = require('../internals/an-object'); +var toPrimitive = require('../internals/to-primitive'); + +var nativeDefineProperty = Object.defineProperty; + +// `Object.defineProperty` method +// https://tc39.github.io/ecma262/#sec-object.defineproperty +exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return nativeDefineProperty(O, P, Attributes); + } catch (error) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; + +},{"../internals/an-object":315,"../internals/descriptors":357,"../internals/ie8-dom-define":382,"../internals/to-primitive":465}],416:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); +var toIndexedObject = require('../internals/to-indexed-object'); +var toPrimitive = require('../internals/to-primitive'); +var has = require('../internals/has'); +var IE8_DOM_DEFINE = require('../internals/ie8-dom-define'); + +var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +// `Object.getOwnPropertyDescriptor` method +// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor +exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { + O = toIndexedObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) try { + return nativeGetOwnPropertyDescriptor(O, P); + } catch (error) { /* empty */ } + if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]); +}; + +},{"../internals/create-property-descriptor":351,"../internals/descriptors":357,"../internals/has":378,"../internals/ie8-dom-define":382,"../internals/object-property-is-enumerable":423,"../internals/to-indexed-object":459,"../internals/to-primitive":465}],417:[function(require,module,exports){ +var toIndexedObject = require('../internals/to-indexed-object'); +var nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names').f; + +var toString = {}.toString; + +var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + +var getWindowNames = function (it) { + try { + return nativeGetOwnPropertyNames(it); + } catch (error) { + return windowNames.slice(); + } +}; + +// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window +module.exports.f = function getOwnPropertyNames(it) { + return windowNames && toString.call(it) == '[object Window]' + ? getWindowNames(it) + : nativeGetOwnPropertyNames(toIndexedObject(it)); +}; + +},{"../internals/object-get-own-property-names":418,"../internals/to-indexed-object":459}],418:[function(require,module,exports){ +var internalObjectKeys = require('../internals/object-keys-internal'); +var enumBugKeys = require('../internals/enum-bug-keys'); + +var hiddenKeys = enumBugKeys.concat('length', 'prototype'); + +// `Object.getOwnPropertyNames` method +// https://tc39.github.io/ecma262/#sec-object.getownpropertynames +exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return internalObjectKeys(O, hiddenKeys); +}; + +},{"../internals/enum-bug-keys":360,"../internals/object-keys-internal":421}],419:[function(require,module,exports){ +exports.f = Object.getOwnPropertySymbols; + +},{}],420:[function(require,module,exports){ +var has = require('../internals/has'); +var toObject = require('../internals/to-object'); +var sharedKey = require('../internals/shared-key'); +var CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter'); + +var IE_PROTO = sharedKey('IE_PROTO'); +var ObjectPrototype = Object.prototype; + +// `Object.getPrototypeOf` method +// https://tc39.github.io/ecma262/#sec-object.getprototypeof +module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectPrototype : null; +}; + +},{"../internals/correct-prototype-getter":345,"../internals/has":378,"../internals/shared-key":446,"../internals/to-object":462}],421:[function(require,module,exports){ +var has = require('../internals/has'); +var toIndexedObject = require('../internals/to-indexed-object'); +var indexOf = require('../internals/array-includes').indexOf; +var hiddenKeys = require('../internals/hidden-keys'); + +module.exports = function (object, names) { + var O = toIndexedObject(object); + var i = 0; + var result = []; + var key; + for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (has(O, key = names[i++])) { + ~indexOf(result, key) || result.push(key); + } + return result; +}; + +},{"../internals/array-includes":322,"../internals/has":378,"../internals/hidden-keys":379,"../internals/to-indexed-object":459}],422:[function(require,module,exports){ +var internalObjectKeys = require('../internals/object-keys-internal'); +var enumBugKeys = require('../internals/enum-bug-keys'); + +// `Object.keys` method +// https://tc39.github.io/ecma262/#sec-object.keys +module.exports = Object.keys || function keys(O) { + return internalObjectKeys(O, enumBugKeys); +}; + +},{"../internals/enum-bug-keys":360,"../internals/object-keys-internal":421}],423:[function(require,module,exports){ +'use strict'; +var nativePropertyIsEnumerable = {}.propertyIsEnumerable; +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +// Nashorn ~ JDK8 bug +var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); + +// `Object.prototype.propertyIsEnumerable` method implementation +// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable +exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { + var descriptor = getOwnPropertyDescriptor(this, V); + return !!descriptor && descriptor.enumerable; +} : nativePropertyIsEnumerable; + +},{}],424:[function(require,module,exports){ +var anObject = require('../internals/an-object'); +var aPossiblePrototype = require('../internals/a-possible-prototype'); + +// `Object.setPrototypeOf` method +// https://tc39.github.io/ecma262/#sec-object.setprototypeof +// Works with __proto__ only. Old v8 can't work with null proto objects. +/* eslint-disable no-proto */ +module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () { + var CORRECT_SETTER = false; + var test = {}; + var setter; + try { + setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set; + setter.call(test, []); + CORRECT_SETTER = test instanceof Array; + } catch (error) { /* empty */ } + return function setPrototypeOf(O, proto) { + anObject(O); + aPossiblePrototype(proto); + if (CORRECT_SETTER) setter.call(O, proto); + else O.__proto__ = proto; + return O; + }; +}() : undefined); + +},{"../internals/a-possible-prototype":311,"../internals/an-object":315}],425:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var objectKeys = require('../internals/object-keys'); +var toIndexedObject = require('../internals/to-indexed-object'); +var propertyIsEnumerable = require('../internals/object-property-is-enumerable').f; + +// `Object.{ entries, values }` methods implementation +var createMethod = function (TO_ENTRIES) { + return function (it) { + var O = toIndexedObject(it); + var keys = objectKeys(O); + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) { + key = keys[i++]; + if (!DESCRIPTORS || propertyIsEnumerable.call(O, key)) { + result.push(TO_ENTRIES ? [key, O[key]] : O[key]); + } + } + return result; + }; +}; + +module.exports = { + // `Object.entries` method + // https://tc39.github.io/ecma262/#sec-object.entries + entries: createMethod(true), + // `Object.values` method + // https://tc39.github.io/ecma262/#sec-object.values + values: createMethod(false) +}; + +},{"../internals/descriptors":357,"../internals/object-keys":422,"../internals/object-property-is-enumerable":423,"../internals/to-indexed-object":459}],426:[function(require,module,exports){ +'use strict'; +var classof = require('../internals/classof'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +var test = {}; + +test[TO_STRING_TAG] = 'z'; + +// `Object.prototype.toString` method implementation +// https://tc39.github.io/ecma262/#sec-object.prototype.tostring +module.exports = String(test) !== '[object z]' ? function toString() { + return '[object ' + classof(this) + ']'; +} : test.toString; + +},{"../internals/classof":334,"../internals/well-known-symbol":473}],427:[function(require,module,exports){ +var getBuiltIn = require('../internals/get-built-in'); +var getOwnPropertyNamesModule = require('../internals/object-get-own-property-names'); +var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols'); +var anObject = require('../internals/an-object'); + +// all object keys, includes non-enumerable and symbols +module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { + var keys = getOwnPropertyNamesModule.f(anObject(it)); + var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; + return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; +}; + +},{"../internals/an-object":315,"../internals/get-built-in":372,"../internals/object-get-own-property-names":418,"../internals/object-get-own-property-symbols":419}],428:[function(require,module,exports){ +var global = require('../internals/global'); +var trim = require('../internals/string-trim').trim; +var whitespaces = require('../internals/whitespaces'); + +var nativeParseFloat = global.parseFloat; +var FORCED = 1 / nativeParseFloat(whitespaces + '-0') !== -Infinity; + +// `parseFloat` method +// https://tc39.github.io/ecma262/#sec-parsefloat-string +module.exports = FORCED ? function parseFloat(string) { + var trimmedString = trim(String(string)); + var result = nativeParseFloat(trimmedString); + return result === 0 && trimmedString.charAt(0) == '-' ? -0 : result; +} : nativeParseFloat; + +},{"../internals/global":377,"../internals/string-trim":454,"../internals/whitespaces":474}],429:[function(require,module,exports){ +var global = require('../internals/global'); +var trim = require('../internals/string-trim').trim; +var whitespaces = require('../internals/whitespaces'); + +var nativeParseInt = global.parseInt; +var hex = /^[+-]?0[Xx]/; +var FORCED = nativeParseInt(whitespaces + '08') !== 8 || nativeParseInt(whitespaces + '0x16') !== 22; + +// `parseInt` method +// https://tc39.github.io/ecma262/#sec-parseint-string-radix +module.exports = FORCED ? function parseInt(string, radix) { + var S = trim(String(string)); + return nativeParseInt(S, (radix >>> 0) || (hex.test(S) ? 16 : 10)); +} : nativeParseInt; + +},{"../internals/global":377,"../internals/string-trim":454,"../internals/whitespaces":474}],430:[function(require,module,exports){ +module.exports = require('../internals/global'); + +},{"../internals/global":377}],431:[function(require,module,exports){ +module.exports = function (exec) { + try { + return { error: false, value: exec() }; + } catch (error) { + return { error: true, value: error }; + } +}; + +},{}],432:[function(require,module,exports){ +var anObject = require('../internals/an-object'); +var isObject = require('../internals/is-object'); +var newPromiseCapability = require('../internals/new-promise-capability'); + +module.exports = function (C, x) { + anObject(C); + if (isObject(x) && x.constructor === C) return x; + var promiseCapability = newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; +}; + +},{"../internals/an-object":315,"../internals/is-object":392,"../internals/new-promise-capability":409}],433:[function(require,module,exports){ +'use strict'; +// based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' +var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars +var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators +var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process'; +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + */ +var ucs2decode = function (string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +}; + +/** + * Converts a digit/integer into a basic code point. + */ +var digitToBasic = function (digit) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + */ +var adapt = function (delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + */ +// eslint-disable-next-line max-statements +var encode = function (input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + var i, currentValue; + + // Handle the basic code points. + for (i = 0; i < input.length; i++) { + currentValue = input[i]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + var basicLength = output.length; // number of basic code points. + var handledCPCount = basicLength; // number of code points that have been handled; + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + // All non-basic code points < n have been handled already. Find the next larger one: + var m = maxInt; + for (i = 0; i < input.length; i++) { + currentValue = input[i]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , but guard against overflow. + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + throw RangeError(OVERFLOW_ERROR); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (i = 0; i < input.length; i++) { + currentValue = input[i]; + if (currentValue < n && ++delta > maxInt) { + throw RangeError(OVERFLOW_ERROR); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base; /* no condition */; k += base) { + var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) break; + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +module.exports = function (input) { + var encoded = []; + var labels = input.toLowerCase().replace(regexSeparators, '\u002E').split('.'); + var i, label; + for (i = 0; i < labels.length; i++) { + label = labels[i]; + encoded.push(regexNonASCII.test(label) ? 'xn--' + encode(label) : label); + } + return encoded.join('.'); +}; + +},{}],434:[function(require,module,exports){ +var redefine = require('../internals/redefine'); + +module.exports = function (target, src, options) { + for (var key in src) redefine(target, key, src[key], options); + return target; +}; + +},{"../internals/redefine":435}],435:[function(require,module,exports){ +var global = require('../internals/global'); +var shared = require('../internals/shared'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var has = require('../internals/has'); +var setGlobal = require('../internals/set-global'); +var nativeFunctionToString = require('../internals/function-to-string'); +var InternalStateModule = require('../internals/internal-state'); + +var getInternalState = InternalStateModule.get; +var enforceInternalState = InternalStateModule.enforce; +var TEMPLATE = String(nativeFunctionToString).split('toString'); + +shared('inspectSource', function (it) { + return nativeFunctionToString.call(it); +}); + +(module.exports = function (O, key, value, options) { + var unsafe = options ? !!options.unsafe : false; + var simple = options ? !!options.enumerable : false; + var noTargetGet = options ? !!options.noTargetGet : false; + if (typeof value == 'function') { + if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key); + enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); + } + if (O === global) { + if (simple) O[key] = value; + else setGlobal(key, value); + return; + } else if (!unsafe) { + delete O[key]; + } else if (!noTargetGet && O[key]) { + simple = true; + } + if (simple) O[key] = value; + else createNonEnumerableProperty(O, key, value); +// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative +})(Function.prototype, 'toString', function toString() { + return typeof this == 'function' && getInternalState(this).source || nativeFunctionToString.call(this); +}); + +},{"../internals/create-non-enumerable-property":350,"../internals/function-to-string":370,"../internals/global":377,"../internals/has":378,"../internals/internal-state":386,"../internals/set-global":443,"../internals/shared":448}],436:[function(require,module,exports){ +// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` +var Map = require('../modules/es.map'); +var WeakMap = require('../modules/es.weak-map'); +var shared = require('../internals/shared'); + +var metadata = shared('metadata'); +var store = metadata.store || (metadata.store = new WeakMap()); + +var getOrCreateMetadataMap = function (target, targetKey, create) { + var targetMetadata = store.get(target); + if (!targetMetadata) { + if (!create) return; + store.set(target, targetMetadata = new Map()); + } + var keyMetadata = targetMetadata.get(targetKey); + if (!keyMetadata) { + if (!create) return; + targetMetadata.set(targetKey, keyMetadata = new Map()); + } return keyMetadata; +}; + +var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? false : metadataMap.has(MetadataKey); +}; + +var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); +}; + +var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { + getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); +}; + +var ordinaryOwnMetadataKeys = function (target, targetKey) { + var metadataMap = getOrCreateMetadataMap(target, targetKey, false); + var keys = []; + if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); + return keys; +}; + +var toMetadataKey = function (it) { + return it === undefined || typeof it == 'symbol' ? it : String(it); +}; + +module.exports = { + store: store, + getMap: getOrCreateMetadataMap, + has: ordinaryHasOwnMetadata, + get: ordinaryGetOwnMetadata, + set: ordinaryDefineOwnMetadata, + keys: ordinaryOwnMetadataKeys, + toKey: toMetadataKey +}; + +},{"../internals/shared":448,"../modules/es.map":519,"../modules/es.weak-map":678}],437:[function(require,module,exports){ +var classof = require('./classof-raw'); +var regexpExec = require('./regexp-exec'); + +// `RegExpExec` abstract operation +// https://tc39.github.io/ecma262/#sec-regexpexec +module.exports = function (R, S) { + var exec = R.exec; + if (typeof exec === 'function') { + var result = exec.call(R, S); + if (typeof result !== 'object') { + throw TypeError('RegExp exec method returned something other than an Object or null'); + } + return result; + } + + if (classof(R) !== 'RegExp') { + throw TypeError('RegExp#exec called on incompatible receiver'); + } + + return regexpExec.call(R, S); +}; + + +},{"./classof-raw":333,"./regexp-exec":438}],438:[function(require,module,exports){ +'use strict'; +var regexpFlags = require('./regexp-flags'); + +var nativeExec = RegExp.prototype.exec; +// This always refers to the native implementation, because the +// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js, +// which loads this file before patching the method. +var nativeReplace = String.prototype.replace; + +var patchedExec = nativeExec; + +var UPDATES_LAST_INDEX_WRONG = (function () { + var re1 = /a/; + var re2 = /b*/g; + nativeExec.call(re1, 'a'); + nativeExec.call(re2, 'a'); + return re1.lastIndex !== 0 || re2.lastIndex !== 0; +})(); + +// nonparticipating capturing group, copied from es5-shim's String#split patch. +var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; + +var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED; + +if (PATCH) { + patchedExec = function exec(str) { + var re = this; + var lastIndex, reCopy, match, i; + + if (NPCG_INCLUDED) { + reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re)); + } + if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex; + + match = nativeExec.call(re, str); + + if (UPDATES_LAST_INDEX_WRONG && match) { + re.lastIndex = re.global ? match.index + match[0].length : lastIndex; + } + if (NPCG_INCLUDED && match && match.length > 1) { + // Fix browsers whose `exec` methods don't consistently return `undefined` + // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/ + nativeReplace.call(match[0], reCopy, function () { + for (i = 1; i < arguments.length - 2; i++) { + if (arguments[i] === undefined) match[i] = undefined; + } + }); + } + + return match; + }; +} + +module.exports = patchedExec; + +},{"./regexp-flags":439}],439:[function(require,module,exports){ +'use strict'; +var anObject = require('../internals/an-object'); + +// `RegExp.prototype.flags` getter implementation +// https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags +module.exports = function () { + var that = anObject(this); + var result = ''; + if (that.global) result += 'g'; + if (that.ignoreCase) result += 'i'; + if (that.multiline) result += 'm'; + if (that.dotAll) result += 's'; + if (that.unicode) result += 'u'; + if (that.sticky) result += 'y'; + return result; +}; + +},{"../internals/an-object":315}],440:[function(require,module,exports){ +// `RequireObjectCoercible` abstract operation +// https://tc39.github.io/ecma262/#sec-requireobjectcoercible +module.exports = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; +}; + +},{}],441:[function(require,module,exports){ +// `SameValueZero` abstract operation +// https://tc39.github.io/ecma262/#sec-samevaluezero +module.exports = function (x, y) { + // eslint-disable-next-line no-self-compare + return x === y || x != x && y != y; +}; + +},{}],442:[function(require,module,exports){ +// `SameValue` abstract operation +// https://tc39.github.io/ecma262/#sec-samevalue +module.exports = Object.is || function is(x, y) { + // eslint-disable-next-line no-self-compare + return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; +}; + +},{}],443:[function(require,module,exports){ +var global = require('../internals/global'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); + +module.exports = function (key, value) { + try { + createNonEnumerableProperty(global, key, value); + } catch (error) { + global[key] = value; + } return value; +}; + +},{"../internals/create-non-enumerable-property":350,"../internals/global":377}],444:[function(require,module,exports){ +'use strict'; +var getBuiltIn = require('../internals/get-built-in'); +var definePropertyModule = require('../internals/object-define-property'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var DESCRIPTORS = require('../internals/descriptors'); + +var SPECIES = wellKnownSymbol('species'); + +module.exports = function (CONSTRUCTOR_NAME) { + var Constructor = getBuiltIn(CONSTRUCTOR_NAME); + var defineProperty = definePropertyModule.f; + + if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) { + defineProperty(Constructor, SPECIES, { + configurable: true, + get: function () { return this; } + }); + } +}; + +},{"../internals/descriptors":357,"../internals/get-built-in":372,"../internals/object-define-property":415,"../internals/well-known-symbol":473}],445:[function(require,module,exports){ +var defineProperty = require('../internals/object-define-property').f; +var has = require('../internals/has'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + +module.exports = function (it, TAG, STATIC) { + if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) { + defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG }); + } +}; + +},{"../internals/has":378,"../internals/object-define-property":415,"../internals/well-known-symbol":473}],446:[function(require,module,exports){ +var shared = require('../internals/shared'); +var uid = require('../internals/uid'); + +var keys = shared('keys'); + +module.exports = function (key) { + return keys[key] || (keys[key] = uid(key)); +}; + +},{"../internals/shared":448,"../internals/uid":469}],447:[function(require,module,exports){ +var global = require('../internals/global'); +var setGlobal = require('../internals/set-global'); + +var SHARED = '__core-js_shared__'; +var store = global[SHARED] || setGlobal(SHARED, {}); + +module.exports = store; + +},{"../internals/global":377,"../internals/set-global":443}],448:[function(require,module,exports){ +var IS_PURE = require('../internals/is-pure'); +var store = require('../internals/shared-store'); + +(module.exports = function (key, value) { + return store[key] || (store[key] = value !== undefined ? value : {}); +})('versions', []).push({ + version: '3.4.1', + mode: IS_PURE ? 'pure' : 'global', + copyright: '© 2019 Denis Pushkarev (zloirock.ru)' +}); + +},{"../internals/is-pure":393,"../internals/shared-store":447}],449:[function(require,module,exports){ +'use strict'; +var fails = require('../internals/fails'); + +module.exports = function (METHOD_NAME, argument) { + var method = [][METHOD_NAME]; + return !method || !fails(function () { + // eslint-disable-next-line no-useless-call,no-throw-literal + method.call(null, argument || function () { throw 1; }, 1); + }); +}; + +},{"../internals/fails":362}],450:[function(require,module,exports){ +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var SPECIES = wellKnownSymbol('species'); + +// `SpeciesConstructor` abstract operation +// https://tc39.github.io/ecma262/#sec-speciesconstructor +module.exports = function (O, defaultConstructor) { + var C = anObject(O).constructor; + var S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? defaultConstructor : aFunction(S); +}; + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/well-known-symbol":473}],451:[function(require,module,exports){ +var toInteger = require('../internals/to-integer'); +var requireObjectCoercible = require('../internals/require-object-coercible'); + +// `String.prototype.{ codePointAt, at }` methods implementation +var createMethod = function (CONVERT_TO_STRING) { + return function ($this, pos) { + var S = String(requireObjectCoercible($this)); + var position = toInteger(pos); + var size = S.length; + var first, second; + if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; + first = S.charCodeAt(position); + return first < 0xD800 || first > 0xDBFF || position + 1 === size + || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF + ? CONVERT_TO_STRING ? S.charAt(position) : first + : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; + }; +}; + +module.exports = { + // `String.prototype.codePointAt` method + // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat + codeAt: createMethod(false), + // `String.prototype.at` method + // https://github.com/mathiasbynens/String.prototype.at + charAt: createMethod(true) +}; + +},{"../internals/require-object-coercible":440,"../internals/to-integer":460}],452:[function(require,module,exports){ +// https://github.com/tc39/proposal-string-pad-start-end +var toLength = require('../internals/to-length'); +var repeat = require('../internals/string-repeat'); +var requireObjectCoercible = require('../internals/require-object-coercible'); + +var ceil = Math.ceil; + +// `String.prototype.{ padStart, padEnd }` methods implementation +var createMethod = function (IS_END) { + return function ($this, maxLength, fillString) { + var S = String(requireObjectCoercible($this)); + var stringLength = S.length; + var fillStr = fillString === undefined ? ' ' : String(fillString); + var intMaxLength = toLength(maxLength); + var fillLen, stringFiller; + if (intMaxLength <= stringLength || fillStr == '') return S; + fillLen = intMaxLength - stringLength; + stringFiller = repeat.call(fillStr, ceil(fillLen / fillStr.length)); + if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); + return IS_END ? S + stringFiller : stringFiller + S; + }; +}; + +module.exports = { + // `String.prototype.padStart` method + // https://tc39.github.io/ecma262/#sec-string.prototype.padstart + start: createMethod(false), + // `String.prototype.padEnd` method + // https://tc39.github.io/ecma262/#sec-string.prototype.padend + end: createMethod(true) +}; + +},{"../internals/require-object-coercible":440,"../internals/string-repeat":453,"../internals/to-length":461}],453:[function(require,module,exports){ +'use strict'; +var toInteger = require('../internals/to-integer'); +var requireObjectCoercible = require('../internals/require-object-coercible'); + +// `String.prototype.repeat` method implementation +// https://tc39.github.io/ecma262/#sec-string.prototype.repeat +module.exports = ''.repeat || function repeat(count) { + var str = String(requireObjectCoercible(this)); + var result = ''; + var n = toInteger(count); + if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions'); + for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str; + return result; +}; + +},{"../internals/require-object-coercible":440,"../internals/to-integer":460}],454:[function(require,module,exports){ +var requireObjectCoercible = require('../internals/require-object-coercible'); +var whitespaces = require('../internals/whitespaces'); + +var whitespace = '[' + whitespaces + ']'; +var ltrim = RegExp('^' + whitespace + whitespace + '*'); +var rtrim = RegExp(whitespace + whitespace + '*$'); + +// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation +var createMethod = function (TYPE) { + return function ($this) { + var string = String(requireObjectCoercible($this)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; + }; +}; + +module.exports = { + // `String.prototype.{ trimLeft, trimStart }` methods + // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart + start: createMethod(1), + // `String.prototype.{ trimRight, trimEnd }` methods + // https://tc39.github.io/ecma262/#sec-string.prototype.trimend + end: createMethod(2), + // `String.prototype.trim` method + // https://tc39.github.io/ecma262/#sec-string.prototype.trim + trim: createMethod(3) +}; + +},{"../internals/require-object-coercible":440,"../internals/whitespaces":474}],455:[function(require,module,exports){ +var global = require('../internals/global'); +var fails = require('../internals/fails'); +var classof = require('../internals/classof-raw'); +var bind = require('../internals/bind-context'); +var html = require('../internals/html'); +var createElement = require('../internals/document-create-element'); +var IS_IOS = require('../internals/is-ios'); + +var location = global.location; +var set = global.setImmediate; +var clear = global.clearImmediate; +var process = global.process; +var MessageChannel = global.MessageChannel; +var Dispatch = global.Dispatch; +var counter = 0; +var queue = {}; +var ONREADYSTATECHANGE = 'onreadystatechange'; +var defer, channel, port; + +var run = function (id) { + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } +}; + +var runner = function (id) { + return function () { + run(id); + }; +}; + +var listener = function (event) { + run(event.data); +}; + +var post = function (id) { + // old engines have not location.origin + global.postMessage(id + '', location.protocol + '//' + location.host); +}; + +// Node.js 0.9+ & IE10+ has setImmediate, otherwise: +if (!set || !clear) { + set = function setImmediate(fn) { + var args = []; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args); + }; + defer(counter); + return counter; + }; + clear = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (classof(process) == 'process') { + defer = function (id) { + process.nextTick(runner(id)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(runner(id)); + }; + // Browsers with MessageChannel, includes WebWorkers + // except iOS - https://github.com/zloirock/core-js/issues/624 + } else if (MessageChannel && !IS_IOS) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = bind(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts && !fails(post)) { + defer = post; + global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in createElement('script')) { + defer = function (id) { + html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () { + html.removeChild(this); + run(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(runner(id), 0); + }; + } +} + +module.exports = { + set: set, + clear: clear +}; + +},{"../internals/bind-context":330,"../internals/classof-raw":333,"../internals/document-create-element":358,"../internals/fails":362,"../internals/global":377,"../internals/html":381,"../internals/is-ios":391}],456:[function(require,module,exports){ +var classof = require('../internals/classof-raw'); + +// `thisNumberValue` abstract operation +// https://tc39.github.io/ecma262/#sec-thisnumbervalue +module.exports = function (value) { + if (typeof value != 'number' && classof(value) != 'Number') { + throw TypeError('Incorrect invocation'); + } + return +value; +}; + +},{"../internals/classof-raw":333}],457:[function(require,module,exports){ +var toInteger = require('../internals/to-integer'); + +var max = Math.max; +var min = Math.min; + +// Helper for a popular repeating case of the spec: +// Let integer be ? ToInteger(index). +// If integer < 0, let result be max((length + integer), 0); else let result be min(length, length). +module.exports = function (index, length) { + var integer = toInteger(index); + return integer < 0 ? max(integer + length, 0) : min(integer, length); +}; + +},{"../internals/to-integer":460}],458:[function(require,module,exports){ +var toInteger = require('../internals/to-integer'); +var toLength = require('../internals/to-length'); + +// `ToIndex` abstract operation +// https://tc39.github.io/ecma262/#sec-toindex +module.exports = function (it) { + if (it === undefined) return 0; + var number = toInteger(it); + var length = toLength(number); + if (number !== length) throw RangeError('Wrong length or index'); + return length; +}; + +},{"../internals/to-integer":460,"../internals/to-length":461}],459:[function(require,module,exports){ +// toObject with fallback for non-array-like ES3 strings +var IndexedObject = require('../internals/indexed-object'); +var requireObjectCoercible = require('../internals/require-object-coercible'); + +module.exports = function (it) { + return IndexedObject(requireObjectCoercible(it)); +}; + +},{"../internals/indexed-object":383,"../internals/require-object-coercible":440}],460:[function(require,module,exports){ +var ceil = Math.ceil; +var floor = Math.floor; + +// `ToInteger` abstract operation +// https://tc39.github.io/ecma262/#sec-tointeger +module.exports = function (argument) { + return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); +}; + +},{}],461:[function(require,module,exports){ +var toInteger = require('../internals/to-integer'); + +var min = Math.min; + +// `ToLength` abstract operation +// https://tc39.github.io/ecma262/#sec-tolength +module.exports = function (argument) { + return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 +}; + +},{"../internals/to-integer":460}],462:[function(require,module,exports){ +var requireObjectCoercible = require('../internals/require-object-coercible'); + +// `ToObject` abstract operation +// https://tc39.github.io/ecma262/#sec-toobject +module.exports = function (argument) { + return Object(requireObjectCoercible(argument)); +}; + +},{"../internals/require-object-coercible":440}],463:[function(require,module,exports){ +var toPositiveInteger = require('../internals/to-positive-integer'); + +module.exports = function (it, BYTES) { + var offset = toPositiveInteger(it); + if (offset % BYTES) throw RangeError('Wrong offset'); + return offset; +}; + +},{"../internals/to-positive-integer":464}],464:[function(require,module,exports){ +var toInteger = require('../internals/to-integer'); + +module.exports = function (it) { + var result = toInteger(it); + if (result < 0) throw RangeError("The argument can't be less than 0"); + return result; +}; + +},{"../internals/to-integer":460}],465:[function(require,module,exports){ +var isObject = require('../internals/is-object'); + +// `ToPrimitive` abstract operation +// https://tc39.github.io/ecma262/#sec-toprimitive +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +module.exports = function (input, PREFERRED_STRING) { + if (!isObject(input)) return input; + var fn, val; + if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; + if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; + if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; + throw TypeError("Can't convert object to primitive value"); +}; + +},{"../internals/is-object":392}],466:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var global = require('../internals/global'); +var DESCRIPTORS = require('../internals/descriptors'); +var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = require('../internals/typed-arrays-constructors-requires-wrappers'); +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var ArrayBufferModule = require('../internals/array-buffer'); +var anInstance = require('../internals/an-instance'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var toLength = require('../internals/to-length'); +var toIndex = require('../internals/to-index'); +var toOffset = require('../internals/to-offset'); +var toPrimitive = require('../internals/to-primitive'); +var has = require('../internals/has'); +var classof = require('../internals/classof'); +var isObject = require('../internals/is-object'); +var create = require('../internals/object-create'); +var setPrototypeOf = require('../internals/object-set-prototype-of'); +var getOwnPropertyNames = require('../internals/object-get-own-property-names').f; +var typedArrayFrom = require('../internals/typed-array-from'); +var forEach = require('../internals/array-iteration').forEach; +var setSpecies = require('../internals/set-species'); +var definePropertyModule = require('../internals/object-define-property'); +var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor'); +var InternalStateModule = require('../internals/internal-state'); +var inheritIfRequired = require('../internals/inherit-if-required'); + +var getInternalState = InternalStateModule.get; +var setInternalState = InternalStateModule.set; +var nativeDefineProperty = definePropertyModule.f; +var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; +var round = Math.round; +var RangeError = global.RangeError; +var ArrayBuffer = ArrayBufferModule.ArrayBuffer; +var DataView = ArrayBufferModule.DataView; +var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; +var TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG; +var TypedArray = ArrayBufferViewCore.TypedArray; +var TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype; +var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; +var isTypedArray = ArrayBufferViewCore.isTypedArray; +var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; +var WRONG_LENGTH = 'Wrong length'; + +var fromList = function (C, list) { + var index = 0; + var length = list.length; + var result = new (aTypedArrayConstructor(C))(length); + while (length > index) result[index] = list[index++]; + return result; +}; + +var addGetter = function (it, key) { + nativeDefineProperty(it, key, { get: function () { + return getInternalState(this)[key]; + } }); +}; + +var isArrayBuffer = function (it) { + var klass; + return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer'; +}; + +var isTypedArrayIndex = function (target, key) { + return isTypedArray(target) + && typeof key != 'symbol' + && key in target + && String(+key) == String(key); +}; + +var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) { + return isTypedArrayIndex(target, key = toPrimitive(key, true)) + ? createPropertyDescriptor(2, target[key]) + : nativeGetOwnPropertyDescriptor(target, key); +}; + +var wrappedDefineProperty = function defineProperty(target, key, descriptor) { + if (isTypedArrayIndex(target, key = toPrimitive(key, true)) + && isObject(descriptor) + && has(descriptor, 'value') + && !has(descriptor, 'get') + && !has(descriptor, 'set') + // TODO: add validation descriptor w/o calling accessors + && !descriptor.configurable + && (!has(descriptor, 'writable') || descriptor.writable) + && (!has(descriptor, 'enumerable') || descriptor.enumerable) + ) { + target[key] = descriptor.value; + return target; + } return nativeDefineProperty(target, key, descriptor); +}; + +if (DESCRIPTORS) { + if (!NATIVE_ARRAY_BUFFER_VIEWS) { + getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor; + definePropertyModule.f = wrappedDefineProperty; + addGetter(TypedArrayPrototype, 'buffer'); + addGetter(TypedArrayPrototype, 'byteOffset'); + addGetter(TypedArrayPrototype, 'byteLength'); + addGetter(TypedArrayPrototype, 'length'); + } + + $({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, { + getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor, + defineProperty: wrappedDefineProperty + }); + + module.exports = function (TYPE, BYTES, wrapper, CLAMPED) { + var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array'; + var GETTER = 'get' + TYPE; + var SETTER = 'set' + TYPE; + var NativeTypedArrayConstructor = global[CONSTRUCTOR_NAME]; + var TypedArrayConstructor = NativeTypedArrayConstructor; + var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype; + var exported = {}; + + var getter = function (that, index) { + var data = getInternalState(that); + return data.view[GETTER](index * BYTES + data.byteOffset, true); + }; + + var setter = function (that, index, value) { + var data = getInternalState(that); + if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF; + data.view[SETTER](index * BYTES + data.byteOffset, value, true); + }; + + var addElement = function (that, index) { + nativeDefineProperty(that, index, { + get: function () { + return getter(this, index); + }, + set: function (value) { + return setter(this, index, value); + }, + enumerable: true + }); + }; + + if (!NATIVE_ARRAY_BUFFER_VIEWS) { + TypedArrayConstructor = wrapper(function (that, data, offset, $length) { + anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME); + var index = 0; + var byteOffset = 0; + var buffer, byteLength, length; + if (!isObject(data)) { + length = toIndex(data); + byteLength = length * BYTES; + buffer = new ArrayBuffer(byteLength); + } else if (isArrayBuffer(data)) { + buffer = data; + byteOffset = toOffset(offset, BYTES); + var $len = data.byteLength; + if ($length === undefined) { + if ($len % BYTES) throw RangeError(WRONG_LENGTH); + byteLength = $len - byteOffset; + if (byteLength < 0) throw RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if (isTypedArray(data)) { + return fromList(TypedArrayConstructor, data); + } else { + return typedArrayFrom.call(TypedArrayConstructor, data); + } + setInternalState(that, { + buffer: buffer, + byteOffset: byteOffset, + byteLength: byteLength, + length: length, + view: new DataView(buffer) + }); + while (index < length) addElement(that, index++); + }); + + if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); + TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype); + } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) { + TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) { + anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME); + return inheritIfRequired(function () { + if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data)); + if (isArrayBuffer(data)) return $length !== undefined + ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length) + : typedArrayOffset !== undefined + ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES)) + : new NativeTypedArrayConstructor(data); + if (isTypedArray(data)) return fromList(TypedArrayConstructor, data); + return typedArrayFrom.call(TypedArrayConstructor, data); + }(), dummy, TypedArrayConstructor); + }); + + if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray); + forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) { + if (!(key in TypedArrayConstructor)) { + createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]); + } + }); + TypedArrayConstructor.prototype = TypedArrayConstructorPrototype; + } + + if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor); + } + + if (TYPED_ARRAY_TAG) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME); + } + + exported[CONSTRUCTOR_NAME] = TypedArrayConstructor; + + $({ + global: true, forced: TypedArrayConstructor != NativeTypedArrayConstructor, sham: !NATIVE_ARRAY_BUFFER_VIEWS + }, exported); + + if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) { + createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES); + } + + if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) { + createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES); + } + + setSpecies(CONSTRUCTOR_NAME); + }; +} else module.exports = function () { /* empty */ }; + +},{"../internals/an-instance":314,"../internals/array-buffer":317,"../internals/array-buffer-view-core":316,"../internals/array-iteration":323,"../internals/classof":334,"../internals/create-non-enumerable-property":350,"../internals/create-property-descriptor":351,"../internals/descriptors":357,"../internals/export":361,"../internals/global":377,"../internals/has":378,"../internals/inherit-if-required":384,"../internals/internal-state":386,"../internals/is-object":392,"../internals/object-create":413,"../internals/object-define-property":415,"../internals/object-get-own-property-descriptor":416,"../internals/object-get-own-property-names":418,"../internals/object-set-prototype-of":424,"../internals/set-species":444,"../internals/to-index":458,"../internals/to-length":461,"../internals/to-offset":463,"../internals/to-primitive":465,"../internals/typed-array-from":467,"../internals/typed-arrays-constructors-requires-wrappers":468}],467:[function(require,module,exports){ +var toObject = require('../internals/to-object'); +var toLength = require('../internals/to-length'); +var getIteratorMethod = require('../internals/get-iterator-method'); +var isArrayIteratorMethod = require('../internals/is-array-iterator-method'); +var bind = require('../internals/bind-context'); +var aTypedArrayConstructor = require('../internals/array-buffer-view-core').aTypedArrayConstructor; + +module.exports = function from(source /* , mapfn, thisArg */) { + var O = toObject(source); + var argumentsLength = arguments.length; + var mapfn = argumentsLength > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iteratorMethod = getIteratorMethod(O); + var i, length, result, step, iterator, next; + if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) { + iterator = iteratorMethod.call(O); + next = iterator.next; + O = []; + while (!(step = next.call(iterator)).done) { + O.push(step.value); + } + } + if (mapping && argumentsLength > 2) { + mapfn = bind(mapfn, arguments[2], 2); + } + length = toLength(O.length); + result = new (aTypedArrayConstructor(this))(length); + for (i = 0; length > i; i++) { + result[i] = mapping ? mapfn(O[i], i) : O[i]; + } + return result; +}; + +},{"../internals/array-buffer-view-core":316,"../internals/bind-context":330,"../internals/get-iterator-method":373,"../internals/is-array-iterator-method":387,"../internals/to-length":461,"../internals/to-object":462}],468:[function(require,module,exports){ +/* eslint-disable no-new */ +var global = require('../internals/global'); +var fails = require('../internals/fails'); +var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration'); +var NATIVE_ARRAY_BUFFER_VIEWS = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER_VIEWS; + +var ArrayBuffer = global.ArrayBuffer; +var Int8Array = global.Int8Array; + +module.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () { + Int8Array(1); +}) || !fails(function () { + new Int8Array(-1); +}) || !checkCorrectnessOfIteration(function (iterable) { + new Int8Array(); + new Int8Array(null); + new Int8Array(1.5); + new Int8Array(iterable); +}, true) || fails(function () { + // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill + return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1; +}); + +},{"../internals/array-buffer-view-core":316,"../internals/check-correctness-of-iteration":332,"../internals/fails":362,"../internals/global":377}],469:[function(require,module,exports){ +var id = 0; +var postfix = Math.random(); + +module.exports = function (key) { + return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); +}; + +},{}],470:[function(require,module,exports){ +var getBuiltIn = require('../internals/get-built-in'); + +module.exports = getBuiltIn('navigator', 'userAgent') || ''; + +},{"../internals/get-built-in":372}],471:[function(require,module,exports){ +var global = require('../internals/global'); +var userAgent = require('../internals/user-agent'); + +var process = global.process; +var versions = process && process.versions; +var v8 = versions && versions.v8; +var match, version; + +if (v8) { + match = v8.split('.'); + version = match[0] + match[1]; +} else if (userAgent) { + match = userAgent.match(/Edge\/(\d+)/); + if (!match || match[1] >= 74) { + match = userAgent.match(/Chrome\/(\d+)/); + if (match) version = match[1]; + } +} + +module.exports = version && +version; + +},{"../internals/global":377,"../internals/user-agent":470}],472:[function(require,module,exports){ +// https://github.com/zloirock/core-js/issues/280 +var userAgent = require('../internals/user-agent'); + +// eslint-disable-next-line unicorn/no-unsafe-regex +module.exports = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent); + +},{"../internals/user-agent":470}],473:[function(require,module,exports){ +var global = require('../internals/global'); +var shared = require('../internals/shared'); +var uid = require('../internals/uid'); +var NATIVE_SYMBOL = require('../internals/native-symbol'); + +var Symbol = global.Symbol; +var store = shared('wks'); + +module.exports = function (name) { + return store[name] || (store[name] = NATIVE_SYMBOL && Symbol[name] + || (NATIVE_SYMBOL ? Symbol : uid)('Symbol.' + name)); +}; + +},{"../internals/global":377,"../internals/native-symbol":406,"../internals/shared":448,"../internals/uid":469}],474:[function(require,module,exports){ +// a string of all valid unicode whitespaces +// eslint-disable-next-line max-len +module.exports = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + +},{}],475:[function(require,module,exports){ +exports.f = require('../internals/well-known-symbol'); + +},{"../internals/well-known-symbol":473}],476:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var global = require('../internals/global'); +var arrayBufferModule = require('../internals/array-buffer'); +var setSpecies = require('../internals/set-species'); + +var ARRAY_BUFFER = 'ArrayBuffer'; +var ArrayBuffer = arrayBufferModule[ARRAY_BUFFER]; +var NativeArrayBuffer = global[ARRAY_BUFFER]; + +// `ArrayBuffer` constructor +// https://tc39.github.io/ecma262/#sec-arraybuffer-constructor +$({ global: true, forced: NativeArrayBuffer !== ArrayBuffer }, { + ArrayBuffer: ArrayBuffer +}); + +setSpecies(ARRAY_BUFFER); + +},{"../internals/array-buffer":317,"../internals/export":361,"../internals/global":377,"../internals/set-species":444}],477:[function(require,module,exports){ +var $ = require('../internals/export'); +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); + +var NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; + +// `ArrayBuffer.isView` method +// https://tc39.github.io/ecma262/#sec-arraybuffer.isview +$({ target: 'ArrayBuffer', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, { + isView: ArrayBufferViewCore.isView +}); + +},{"../internals/array-buffer-view-core":316,"../internals/export":361}],478:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var ArrayBufferModule = require('../internals/array-buffer'); +var anObject = require('../internals/an-object'); +var toAbsoluteIndex = require('../internals/to-absolute-index'); +var toLength = require('../internals/to-length'); +var speciesConstructor = require('../internals/species-constructor'); + +var ArrayBuffer = ArrayBufferModule.ArrayBuffer; +var DataView = ArrayBufferModule.DataView; +var nativeArrayBufferSlice = ArrayBuffer.prototype.slice; + +var INCORRECT_SLICE = fails(function () { + return !new ArrayBuffer(2).slice(1, undefined).byteLength; +}); + +// `ArrayBuffer.prototype.slice` method +// https://tc39.github.io/ecma262/#sec-arraybuffer.prototype.slice +$({ target: 'ArrayBuffer', proto: true, unsafe: true, forced: INCORRECT_SLICE }, { + slice: function slice(start, end) { + if (nativeArrayBufferSlice !== undefined && end === undefined) { + return nativeArrayBufferSlice.call(anObject(this), start); // FF fix + } + var length = anObject(this).byteLength; + var first = toAbsoluteIndex(start, length); + var fin = toAbsoluteIndex(end === undefined ? length : end, length); + var result = new (speciesConstructor(this, ArrayBuffer))(toLength(fin - first)); + var viewSource = new DataView(this); + var viewTarget = new DataView(result); + var index = 0; + while (first < fin) { + viewTarget.setUint8(index++, viewSource.getUint8(first++)); + } return result; + } +}); + +},{"../internals/an-object":315,"../internals/array-buffer":317,"../internals/export":361,"../internals/fails":362,"../internals/species-constructor":450,"../internals/to-absolute-index":457,"../internals/to-length":461}],479:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var isArray = require('../internals/is-array'); +var isObject = require('../internals/is-object'); +var toObject = require('../internals/to-object'); +var toLength = require('../internals/to-length'); +var createProperty = require('../internals/create-property'); +var arraySpeciesCreate = require('../internals/array-species-create'); +var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var V8_VERSION = require('../internals/v8-version'); + +var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); +var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; +var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; + +// We can't use this feature detection in V8 since it causes +// deoptimization and serious performance degradation +// https://github.com/zloirock/core-js/issues/679 +var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () { + var array = []; + array[IS_CONCAT_SPREADABLE] = false; + return array.concat()[0] !== array; +}); + +var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); + +var isConcatSpreadable = function (O) { + if (!isObject(O)) return false; + var spreadable = O[IS_CONCAT_SPREADABLE]; + return spreadable !== undefined ? !!spreadable : isArray(O); +}; + +var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; + +// `Array.prototype.concat` method +// https://tc39.github.io/ecma262/#sec-array.prototype.concat +// with adding support of @@isConcatSpreadable and @@species +$({ target: 'Array', proto: true, forced: FORCED }, { + concat: function concat(arg) { // eslint-disable-line no-unused-vars + var O = toObject(this); + var A = arraySpeciesCreate(O, 0); + var n = 0; + var i, k, length, len, E; + for (i = -1, length = arguments.length; i < length; i++) { + E = i === -1 ? O : arguments[i]; + if (isConcatSpreadable(E)) { + len = toLength(E.length); + if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); + for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); + } else { + if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); + createProperty(A, n++, E); + } + } + A.length = n; + return A; + } +}); + +},{"../internals/array-method-has-species-support":325,"../internals/array-species-create":327,"../internals/create-property":352,"../internals/export":361,"../internals/fails":362,"../internals/is-array":388,"../internals/is-object":392,"../internals/to-length":461,"../internals/to-object":462,"../internals/v8-version":471,"../internals/well-known-symbol":473}],480:[function(require,module,exports){ +var $ = require('../internals/export'); +var copyWithin = require('../internals/array-copy-within'); +var addToUnscopables = require('../internals/add-to-unscopables'); + +// `Array.prototype.copyWithin` method +// https://tc39.github.io/ecma262/#sec-array.prototype.copywithin +$({ target: 'Array', proto: true }, { + copyWithin: copyWithin +}); + +// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables +addToUnscopables('copyWithin'); + +},{"../internals/add-to-unscopables":312,"../internals/array-copy-within":318,"../internals/export":361}],481:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $every = require('../internals/array-iteration').every; +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +// `Array.prototype.every` method +// https://tc39.github.io/ecma262/#sec-array.prototype.every +$({ target: 'Array', proto: true, forced: sloppyArrayMethod('every') }, { + every: function every(callbackfn /* , thisArg */) { + return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/array-iteration":323,"../internals/export":361,"../internals/sloppy-array-method":449}],482:[function(require,module,exports){ +var $ = require('../internals/export'); +var fill = require('../internals/array-fill'); +var addToUnscopables = require('../internals/add-to-unscopables'); + +// `Array.prototype.fill` method +// https://tc39.github.io/ecma262/#sec-array.prototype.fill +$({ target: 'Array', proto: true }, { + fill: fill +}); + +// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables +addToUnscopables('fill'); + +},{"../internals/add-to-unscopables":312,"../internals/array-fill":319,"../internals/export":361}],483:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $filter = require('../internals/array-iteration').filter; +var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support'); + +// `Array.prototype.filter` method +// https://tc39.github.io/ecma262/#sec-array.prototype.filter +// with adding support of @@species +$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('filter') }, { + filter: function filter(callbackfn /* , thisArg */) { + return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/array-iteration":323,"../internals/array-method-has-species-support":325,"../internals/export":361}],484:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $findIndex = require('../internals/array-iteration').findIndex; +var addToUnscopables = require('../internals/add-to-unscopables'); + +var FIND_INDEX = 'findIndex'; +var SKIPS_HOLES = true; + +// Shouldn't skip holes +if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES = false; }); + +// `Array.prototype.findIndex` method +// https://tc39.github.io/ecma262/#sec-array.prototype.findindex +$({ target: 'Array', proto: true, forced: SKIPS_HOLES }, { + findIndex: function findIndex(callbackfn /* , that = undefined */) { + return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables +addToUnscopables(FIND_INDEX); + +},{"../internals/add-to-unscopables":312,"../internals/array-iteration":323,"../internals/export":361}],485:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $find = require('../internals/array-iteration').find; +var addToUnscopables = require('../internals/add-to-unscopables'); + +var FIND = 'find'; +var SKIPS_HOLES = true; + +// Shouldn't skip holes +if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; }); + +// `Array.prototype.find` method +// https://tc39.github.io/ecma262/#sec-array.prototype.find +$({ target: 'Array', proto: true, forced: SKIPS_HOLES }, { + find: function find(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables +addToUnscopables(FIND); + +},{"../internals/add-to-unscopables":312,"../internals/array-iteration":323,"../internals/export":361}],486:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var flattenIntoArray = require('../internals/flatten-into-array'); +var toObject = require('../internals/to-object'); +var toLength = require('../internals/to-length'); +var aFunction = require('../internals/a-function'); +var arraySpeciesCreate = require('../internals/array-species-create'); + +// `Array.prototype.flatMap` method +// https://github.com/tc39/proposal-flatMap +$({ target: 'Array', proto: true }, { + flatMap: function flatMap(callbackfn /* , thisArg */) { + var O = toObject(this); + var sourceLen = toLength(O.length); + var A; + aFunction(callbackfn); + A = arraySpeciesCreate(O, 0); + A.length = flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + return A; + } +}); + +},{"../internals/a-function":310,"../internals/array-species-create":327,"../internals/export":361,"../internals/flatten-into-array":364,"../internals/to-length":461,"../internals/to-object":462}],487:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var flattenIntoArray = require('../internals/flatten-into-array'); +var toObject = require('../internals/to-object'); +var toLength = require('../internals/to-length'); +var toInteger = require('../internals/to-integer'); +var arraySpeciesCreate = require('../internals/array-species-create'); + +// `Array.prototype.flat` method +// https://github.com/tc39/proposal-flatMap +$({ target: 'Array', proto: true }, { + flat: function flat(/* depthArg = 1 */) { + var depthArg = arguments.length ? arguments[0] : undefined; + var O = toObject(this); + var sourceLen = toLength(O.length); + var A = arraySpeciesCreate(O, 0); + A.length = flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); + return A; + } +}); + +},{"../internals/array-species-create":327,"../internals/export":361,"../internals/flatten-into-array":364,"../internals/to-integer":460,"../internals/to-length":461,"../internals/to-object":462}],488:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var forEach = require('../internals/array-for-each'); + +// `Array.prototype.forEach` method +// https://tc39.github.io/ecma262/#sec-array.prototype.foreach +$({ target: 'Array', proto: true, forced: [].forEach != forEach }, { + forEach: forEach +}); + +},{"../internals/array-for-each":320,"../internals/export":361}],489:[function(require,module,exports){ +var $ = require('../internals/export'); +var from = require('../internals/array-from'); +var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration'); + +var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) { + Array.from(iterable); +}); + +// `Array.from` method +// https://tc39.github.io/ecma262/#sec-array.from +$({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, { + from: from +}); + +},{"../internals/array-from":321,"../internals/check-correctness-of-iteration":332,"../internals/export":361}],490:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $includes = require('../internals/array-includes').includes; +var addToUnscopables = require('../internals/add-to-unscopables'); + +// `Array.prototype.includes` method +// https://tc39.github.io/ecma262/#sec-array.prototype.includes +$({ target: 'Array', proto: true }, { + includes: function includes(el /* , fromIndex = 0 */) { + return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables +addToUnscopables('includes'); + +},{"../internals/add-to-unscopables":312,"../internals/array-includes":322,"../internals/export":361}],491:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $indexOf = require('../internals/array-includes').indexOf; +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +var nativeIndexOf = [].indexOf; + +var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0; +var SLOPPY_METHOD = sloppyArrayMethod('indexOf'); + +// `Array.prototype.indexOf` method +// https://tc39.github.io/ecma262/#sec-array.prototype.indexof +$({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || SLOPPY_METHOD }, { + indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { + return NEGATIVE_ZERO + // convert -0 to +0 + ? nativeIndexOf.apply(this, arguments) || 0 + : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/array-includes":322,"../internals/export":361,"../internals/sloppy-array-method":449}],492:[function(require,module,exports){ +var $ = require('../internals/export'); +var isArray = require('../internals/is-array'); + +// `Array.isArray` method +// https://tc39.github.io/ecma262/#sec-array.isarray +$({ target: 'Array', stat: true }, { + isArray: isArray +}); + +},{"../internals/export":361,"../internals/is-array":388}],493:[function(require,module,exports){ +'use strict'; +var toIndexedObject = require('../internals/to-indexed-object'); +var addToUnscopables = require('../internals/add-to-unscopables'); +var Iterators = require('../internals/iterators'); +var InternalStateModule = require('../internals/internal-state'); +var defineIterator = require('../internals/define-iterator'); + +var ARRAY_ITERATOR = 'Array Iterator'; +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); + +// `Array.prototype.entries` method +// https://tc39.github.io/ecma262/#sec-array.prototype.entries +// `Array.prototype.keys` method +// https://tc39.github.io/ecma262/#sec-array.prototype.keys +// `Array.prototype.values` method +// https://tc39.github.io/ecma262/#sec-array.prototype.values +// `Array.prototype[@@iterator]` method +// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator +// `CreateArrayIterator` internal method +// https://tc39.github.io/ecma262/#sec-createarrayiterator +module.exports = defineIterator(Array, 'Array', function (iterated, kind) { + setInternalState(this, { + type: ARRAY_ITERATOR, + target: toIndexedObject(iterated), // target + index: 0, // next index + kind: kind // kind + }); +// `%ArrayIteratorPrototype%.next` method +// https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next +}, function () { + var state = getInternalState(this); + var target = state.target; + var kind = state.kind; + var index = state.index++; + if (!target || index >= target.length) { + state.target = undefined; + return { value: undefined, done: true }; + } + if (kind == 'keys') return { value: index, done: false }; + if (kind == 'values') return { value: target[index], done: false }; + return { value: [index, target[index]], done: false }; +}, 'values'); + +// argumentsList[@@iterator] is %ArrayProto_values% +// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject +// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject +Iterators.Arguments = Iterators.Array; + +// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables +addToUnscopables('keys'); +addToUnscopables('values'); +addToUnscopables('entries'); + +},{"../internals/add-to-unscopables":312,"../internals/define-iterator":355,"../internals/internal-state":386,"../internals/iterators":397,"../internals/to-indexed-object":459}],494:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IndexedObject = require('../internals/indexed-object'); +var toIndexedObject = require('../internals/to-indexed-object'); +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +var nativeJoin = [].join; + +var ES3_STRINGS = IndexedObject != Object; +var SLOPPY_METHOD = sloppyArrayMethod('join', ','); + +// `Array.prototype.join` method +// https://tc39.github.io/ecma262/#sec-array.prototype.join +$({ target: 'Array', proto: true, forced: ES3_STRINGS || SLOPPY_METHOD }, { + join: function join(separator) { + return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator); + } +}); + +},{"../internals/export":361,"../internals/indexed-object":383,"../internals/sloppy-array-method":449,"../internals/to-indexed-object":459}],495:[function(require,module,exports){ +var $ = require('../internals/export'); +var lastIndexOf = require('../internals/array-last-index-of'); + +// `Array.prototype.lastIndexOf` method +// https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof +$({ target: 'Array', proto: true, forced: lastIndexOf !== [].lastIndexOf }, { + lastIndexOf: lastIndexOf +}); + +},{"../internals/array-last-index-of":324,"../internals/export":361}],496:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $map = require('../internals/array-iteration').map; +var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support'); + +// `Array.prototype.map` method +// https://tc39.github.io/ecma262/#sec-array.prototype.map +// with adding support of @@species +$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('map') }, { + map: function map(callbackfn /* , thisArg */) { + return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/array-iteration":323,"../internals/array-method-has-species-support":325,"../internals/export":361}],497:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var createProperty = require('../internals/create-property'); + +var ISNT_GENERIC = fails(function () { + function F() { /* empty */ } + return !(Array.of.call(F) instanceof F); +}); + +// `Array.of` method +// https://tc39.github.io/ecma262/#sec-array.of +// WebKit Array.of isn't generic +$({ target: 'Array', stat: true, forced: ISNT_GENERIC }, { + of: function of(/* ...args */) { + var index = 0; + var argumentsLength = arguments.length; + var result = new (typeof this == 'function' ? this : Array)(argumentsLength); + while (argumentsLength > index) createProperty(result, index, arguments[index++]); + result.length = argumentsLength; + return result; + } +}); + +},{"../internals/create-property":352,"../internals/export":361,"../internals/fails":362}],498:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $reduceRight = require('../internals/array-reduce').right; +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +// `Array.prototype.reduceRight` method +// https://tc39.github.io/ecma262/#sec-array.prototype.reduceright +$({ target: 'Array', proto: true, forced: sloppyArrayMethod('reduceRight') }, { + reduceRight: function reduceRight(callbackfn /* , initialValue */) { + return $reduceRight(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/array-reduce":326,"../internals/export":361,"../internals/sloppy-array-method":449}],499:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $reduce = require('../internals/array-reduce').left; +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +// `Array.prototype.reduce` method +// https://tc39.github.io/ecma262/#sec-array.prototype.reduce +$({ target: 'Array', proto: true, forced: sloppyArrayMethod('reduce') }, { + reduce: function reduce(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/array-reduce":326,"../internals/export":361,"../internals/sloppy-array-method":449}],500:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var isArray = require('../internals/is-array'); + +var nativeReverse = [].reverse; +var test = [1, 2]; + +// `Array.prototype.reverse` method +// https://tc39.github.io/ecma262/#sec-array.prototype.reverse +// fix for Safari 12.0 bug +// https://bugs.webkit.org/show_bug.cgi?id=188794 +$({ target: 'Array', proto: true, forced: String(test) === String(test.reverse()) }, { + reverse: function reverse() { + // eslint-disable-next-line no-self-assign + if (isArray(this)) this.length = this.length; + return nativeReverse.call(this); + } +}); + +},{"../internals/export":361,"../internals/is-array":388}],501:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var isObject = require('../internals/is-object'); +var isArray = require('../internals/is-array'); +var toAbsoluteIndex = require('../internals/to-absolute-index'); +var toLength = require('../internals/to-length'); +var toIndexedObject = require('../internals/to-indexed-object'); +var createProperty = require('../internals/create-property'); +var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var SPECIES = wellKnownSymbol('species'); +var nativeSlice = [].slice; +var max = Math.max; + +// `Array.prototype.slice` method +// https://tc39.github.io/ecma262/#sec-array.prototype.slice +// fallback for not array-like ES3 strings and DOM objects +$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('slice') }, { + slice: function slice(start, end) { + var O = toIndexedObject(this); + var length = toLength(O.length); + var k = toAbsoluteIndex(start, length); + var fin = toAbsoluteIndex(end === undefined ? length : end, length); + // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible + var Constructor, result, n; + if (isArray(O)) { + Constructor = O.constructor; + // cross-realm fallback + if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) { + Constructor = undefined; + } else if (isObject(Constructor)) { + Constructor = Constructor[SPECIES]; + if (Constructor === null) Constructor = undefined; + } + if (Constructor === Array || Constructor === undefined) { + return nativeSlice.call(O, k, fin); + } + } + result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0)); + for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]); + result.length = n; + return result; + } +}); + +},{"../internals/array-method-has-species-support":325,"../internals/create-property":352,"../internals/export":361,"../internals/is-array":388,"../internals/is-object":392,"../internals/to-absolute-index":457,"../internals/to-indexed-object":459,"../internals/to-length":461,"../internals/well-known-symbol":473}],502:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $some = require('../internals/array-iteration').some; +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +// `Array.prototype.some` method +// https://tc39.github.io/ecma262/#sec-array.prototype.some +$({ target: 'Array', proto: true, forced: sloppyArrayMethod('some') }, { + some: function some(callbackfn /* , thisArg */) { + return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/array-iteration":323,"../internals/export":361,"../internals/sloppy-array-method":449}],503:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var aFunction = require('../internals/a-function'); +var toObject = require('../internals/to-object'); +var fails = require('../internals/fails'); +var sloppyArrayMethod = require('../internals/sloppy-array-method'); + +var test = []; +var nativeSort = test.sort; + +// IE8- +var FAILS_ON_UNDEFINED = fails(function () { + test.sort(undefined); +}); +// V8 bug +var FAILS_ON_NULL = fails(function () { + test.sort(null); +}); +// Old WebKit +var SLOPPY_METHOD = sloppyArrayMethod('sort'); + +var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || SLOPPY_METHOD; + +// `Array.prototype.sort` method +// https://tc39.github.io/ecma262/#sec-array.prototype.sort +$({ target: 'Array', proto: true, forced: FORCED }, { + sort: function sort(comparefn) { + return comparefn === undefined + ? nativeSort.call(toObject(this)) + : nativeSort.call(toObject(this), aFunction(comparefn)); + } +}); + +},{"../internals/a-function":310,"../internals/export":361,"../internals/fails":362,"../internals/sloppy-array-method":449,"../internals/to-object":462}],504:[function(require,module,exports){ +var setSpecies = require('../internals/set-species'); + +// `Array[@@species]` getter +// https://tc39.github.io/ecma262/#sec-get-array-@@species +setSpecies('Array'); + +},{"../internals/set-species":444}],505:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var toAbsoluteIndex = require('../internals/to-absolute-index'); +var toInteger = require('../internals/to-integer'); +var toLength = require('../internals/to-length'); +var toObject = require('../internals/to-object'); +var arraySpeciesCreate = require('../internals/array-species-create'); +var createProperty = require('../internals/create-property'); +var arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support'); + +var max = Math.max; +var min = Math.min; +var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; +var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; + +// `Array.prototype.splice` method +// https://tc39.github.io/ecma262/#sec-array.prototype.splice +// with adding support of @@species +$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('splice') }, { + splice: function splice(start, deleteCount /* , ...items */) { + var O = toObject(this); + var len = toLength(O.length); + var actualStart = toAbsoluteIndex(start, len); + var argumentsLength = arguments.length; + var insertCount, actualDeleteCount, A, k, from, to; + if (argumentsLength === 0) { + insertCount = actualDeleteCount = 0; + } else if (argumentsLength === 1) { + insertCount = 0; + actualDeleteCount = len - actualStart; + } else { + insertCount = argumentsLength - 2; + actualDeleteCount = min(max(toInteger(deleteCount), 0), len - actualStart); + } + if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) { + throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED); + } + A = arraySpeciesCreate(O, actualDeleteCount); + for (k = 0; k < actualDeleteCount; k++) { + from = actualStart + k; + if (from in O) createProperty(A, k, O[from]); + } + A.length = actualDeleteCount; + if (insertCount < actualDeleteCount) { + for (k = actualStart; k < len - actualDeleteCount; k++) { + from = k + actualDeleteCount; + to = k + insertCount; + if (from in O) O[to] = O[from]; + else delete O[to]; + } + for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1]; + } else if (insertCount > actualDeleteCount) { + for (k = len - actualDeleteCount; k > actualStart; k--) { + from = k + actualDeleteCount - 1; + to = k + insertCount - 1; + if (from in O) O[to] = O[from]; + else delete O[to]; + } + } + for (k = 0; k < insertCount; k++) { + O[k + actualStart] = arguments[k + 2]; + } + O.length = len - actualDeleteCount + insertCount; + return A; + } +}); + +},{"../internals/array-method-has-species-support":325,"../internals/array-species-create":327,"../internals/create-property":352,"../internals/export":361,"../internals/to-absolute-index":457,"../internals/to-integer":460,"../internals/to-length":461,"../internals/to-object":462}],506:[function(require,module,exports){ +// this method was added to unscopables after implementation +// in popular engines, so it's moved to a separate module +var addToUnscopables = require('../internals/add-to-unscopables'); + +addToUnscopables('flatMap'); + +},{"../internals/add-to-unscopables":312}],507:[function(require,module,exports){ +// this method was added to unscopables after implementation +// in popular engines, so it's moved to a separate module +var addToUnscopables = require('../internals/add-to-unscopables'); + +addToUnscopables('flat'); + +},{"../internals/add-to-unscopables":312}],508:[function(require,module,exports){ +var $ = require('../internals/export'); +var ArrayBufferModule = require('../internals/array-buffer'); +var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER; + +// `DataView` constructor +// https://tc39.github.io/ecma262/#sec-dataview-constructor +$({ global: true, forced: !NATIVE_ARRAY_BUFFER }, { + DataView: ArrayBufferModule.DataView +}); + +},{"../internals/array-buffer":317,"../internals/array-buffer-view-core":316,"../internals/export":361}],509:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Date.now` method +// https://tc39.github.io/ecma262/#sec-date.now +$({ target: 'Date', stat: true }, { + now: function now() { + return new Date().getTime(); + } +}); + +},{"../internals/export":361}],510:[function(require,module,exports){ +var $ = require('../internals/export'); +var toISOString = require('../internals/date-to-iso-string'); + +// `Date.prototype.toISOString` method +// https://tc39.github.io/ecma262/#sec-date.prototype.toisostring +// PhantomJS / old WebKit has a broken implementations +$({ target: 'Date', proto: true, forced: Date.prototype.toISOString !== toISOString }, { + toISOString: toISOString +}); + +},{"../internals/date-to-iso-string":353,"../internals/export":361}],511:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var toObject = require('../internals/to-object'); +var toPrimitive = require('../internals/to-primitive'); + +var FORCED = fails(function () { + return new Date(NaN).toJSON() !== null + || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; +}); + +// `Date.prototype.toJSON` method +// https://tc39.github.io/ecma262/#sec-date.prototype.tojson +$({ target: 'Date', proto: true, forced: FORCED }, { + // eslint-disable-next-line no-unused-vars + toJSON: function toJSON(key) { + var O = toObject(this); + var pv = toPrimitive(O); + return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/to-object":462,"../internals/to-primitive":465}],512:[function(require,module,exports){ +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var dateToPrimitive = require('../internals/date-to-primitive'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); +var DatePrototype = Date.prototype; + +// `Date.prototype[@@toPrimitive]` method +// https://tc39.github.io/ecma262/#sec-date.prototype-@@toprimitive +if (!(TO_PRIMITIVE in DatePrototype)) { + createNonEnumerableProperty(DatePrototype, TO_PRIMITIVE, dateToPrimitive); +} + +},{"../internals/create-non-enumerable-property":350,"../internals/date-to-primitive":354,"../internals/well-known-symbol":473}],513:[function(require,module,exports){ +var redefine = require('../internals/redefine'); + +var DatePrototype = Date.prototype; +var INVALID_DATE = 'Invalid Date'; +var TO_STRING = 'toString'; +var nativeDateToString = DatePrototype[TO_STRING]; +var getTime = DatePrototype.getTime; + +// `Date.prototype.toString` method +// https://tc39.github.io/ecma262/#sec-date.prototype.tostring +if (new Date(NaN) + '' != INVALID_DATE) { + redefine(DatePrototype, TO_STRING, function toString() { + var value = getTime.call(this); + // eslint-disable-next-line no-self-compare + return value === value ? nativeDateToString.call(this) : INVALID_DATE; + }); +} + +},{"../internals/redefine":435}],514:[function(require,module,exports){ +var $ = require('../internals/export'); +var bind = require('../internals/function-bind'); + +// `Function.prototype.bind` method +// https://tc39.github.io/ecma262/#sec-function.prototype.bind +$({ target: 'Function', proto: true }, { + bind: bind +}); + +},{"../internals/export":361,"../internals/function-bind":369}],515:[function(require,module,exports){ +'use strict'; +var isObject = require('../internals/is-object'); +var definePropertyModule = require('../internals/object-define-property'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var HAS_INSTANCE = wellKnownSymbol('hasInstance'); +var FunctionPrototype = Function.prototype; + +// `Function.prototype[@@hasInstance]` method +// https://tc39.github.io/ecma262/#sec-function.prototype-@@hasinstance +if (!(HAS_INSTANCE in FunctionPrototype)) { + definePropertyModule.f(FunctionPrototype, HAS_INSTANCE, { value: function (O) { + if (typeof this != 'function' || !isObject(O)) return false; + if (!isObject(this.prototype)) return O instanceof this; + // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: + while (O = getPrototypeOf(O)) if (this.prototype === O) return true; + return false; + } }); +} + +},{"../internals/is-object":392,"../internals/object-define-property":415,"../internals/object-get-prototype-of":420,"../internals/well-known-symbol":473}],516:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var defineProperty = require('../internals/object-define-property').f; + +var FunctionPrototype = Function.prototype; +var FunctionPrototypeToString = FunctionPrototype.toString; +var nameRE = /^\s*function ([^ (]*)/; +var NAME = 'name'; + +// Function instances `.name` property +// https://tc39.github.io/ecma262/#sec-function-instances-name +if (DESCRIPTORS && !(NAME in FunctionPrototype)) { + defineProperty(FunctionPrototype, NAME, { + configurable: true, + get: function () { + try { + return FunctionPrototypeToString.call(this).match(nameRE)[1]; + } catch (error) { + return ''; + } + } + }); +} + +},{"../internals/descriptors":357,"../internals/object-define-property":415}],517:[function(require,module,exports){ +var $ = require('../internals/export'); +var global = require('../internals/global'); + +// `globalThis` object +// https://github.com/tc39/proposal-global +$({ global: true }, { + globalThis: global +}); + +},{"../internals/export":361,"../internals/global":377}],518:[function(require,module,exports){ +var global = require('../internals/global'); +var setToStringTag = require('../internals/set-to-string-tag'); + +// JSON[@@toStringTag] property +// https://tc39.github.io/ecma262/#sec-json-@@tostringtag +setToStringTag(global.JSON, 'JSON', true); + +},{"../internals/global":377,"../internals/set-to-string-tag":445}],519:[function(require,module,exports){ +'use strict'; +var collection = require('../internals/collection'); +var collectionStrong = require('../internals/collection-strong'); + +// `Map` constructor +// https://tc39.github.io/ecma262/#sec-map-objects +module.exports = collection('Map', function (get) { + return function Map() { return get(this, arguments.length ? arguments[0] : undefined); }; +}, collectionStrong, true); + +},{"../internals/collection":341,"../internals/collection-strong":339}],520:[function(require,module,exports){ +var $ = require('../internals/export'); +var log1p = require('../internals/math-log1p'); + +var nativeAcosh = Math.acosh; +var log = Math.log; +var sqrt = Math.sqrt; +var LN2 = Math.LN2; + +var FORCED = !nativeAcosh + // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 + || Math.floor(nativeAcosh(Number.MAX_VALUE)) != 710 + // Tor Browser bug: Math.acosh(Infinity) -> NaN + || nativeAcosh(Infinity) != Infinity; + +// `Math.acosh` method +// https://tc39.github.io/ecma262/#sec-math.acosh +$({ target: 'Math', stat: true, forced: FORCED }, { + acosh: function acosh(x) { + return (x = +x) < 1 ? NaN : x > 94906265.62425156 + ? log(x) + LN2 + : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); + } +}); + +},{"../internals/export":361,"../internals/math-log1p":401}],521:[function(require,module,exports){ +var $ = require('../internals/export'); + +var nativeAsinh = Math.asinh; +var log = Math.log; +var sqrt = Math.sqrt; + +function asinh(x) { + return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); +} + +// `Math.asinh` method +// https://tc39.github.io/ecma262/#sec-math.asinh +// Tor Browser bug: Math.asinh(0) -> -0 +$({ target: 'Math', stat: true, forced: !(nativeAsinh && 1 / nativeAsinh(0) > 0) }, { + asinh: asinh +}); + +},{"../internals/export":361}],522:[function(require,module,exports){ +var $ = require('../internals/export'); + +var nativeAtanh = Math.atanh; +var log = Math.log; + +// `Math.atanh` method +// https://tc39.github.io/ecma262/#sec-math.atanh +// Tor Browser bug: Math.atanh(-0) -> 0 +$({ target: 'Math', stat: true, forced: !(nativeAtanh && 1 / nativeAtanh(-0) < 0) }, { + atanh: function atanh(x) { + return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; + } +}); + +},{"../internals/export":361}],523:[function(require,module,exports){ +var $ = require('../internals/export'); +var sign = require('../internals/math-sign'); + +var abs = Math.abs; +var pow = Math.pow; + +// `Math.cbrt` method +// https://tc39.github.io/ecma262/#sec-math.cbrt +$({ target: 'Math', stat: true }, { + cbrt: function cbrt(x) { + return sign(x = +x) * pow(abs(x), 1 / 3); + } +}); + +},{"../internals/export":361,"../internals/math-sign":403}],524:[function(require,module,exports){ +var $ = require('../internals/export'); + +var floor = Math.floor; +var log = Math.log; +var LOG2E = Math.LOG2E; + +// `Math.clz32` method +// https://tc39.github.io/ecma262/#sec-math.clz32 +$({ target: 'Math', stat: true }, { + clz32: function clz32(x) { + return (x >>>= 0) ? 31 - floor(log(x + 0.5) * LOG2E) : 32; + } +}); + +},{"../internals/export":361}],525:[function(require,module,exports){ +var $ = require('../internals/export'); +var expm1 = require('../internals/math-expm1'); + +var nativeCosh = Math.cosh; +var abs = Math.abs; +var E = Math.E; + +// `Math.cosh` method +// https://tc39.github.io/ecma262/#sec-math.cosh +$({ target: 'Math', stat: true, forced: !nativeCosh || nativeCosh(710) === Infinity }, { + cosh: function cosh(x) { + var t = expm1(abs(x) - 1) + 1; + return (t + 1 / (t * E * E)) * (E / 2); + } +}); + +},{"../internals/export":361,"../internals/math-expm1":399}],526:[function(require,module,exports){ +var $ = require('../internals/export'); +var expm1 = require('../internals/math-expm1'); + +// `Math.expm1` method +// https://tc39.github.io/ecma262/#sec-math.expm1 +$({ target: 'Math', stat: true, forced: expm1 != Math.expm1 }, { expm1: expm1 }); + +},{"../internals/export":361,"../internals/math-expm1":399}],527:[function(require,module,exports){ +var $ = require('../internals/export'); +var fround = require('../internals/math-fround'); + +// `Math.fround` method +// https://tc39.github.io/ecma262/#sec-math.fround +$({ target: 'Math', stat: true }, { fround: fround }); + +},{"../internals/export":361,"../internals/math-fround":400}],528:[function(require,module,exports){ +var $ = require('../internals/export'); + +var $hypot = Math.hypot; +var abs = Math.abs; +var sqrt = Math.sqrt; + +// Chrome 77 bug +// https://bugs.chromium.org/p/v8/issues/detail?id=9546 +var BUGGY = !!$hypot && $hypot(Infinity, NaN) !== Infinity; + +// `Math.hypot` method +// https://tc39.github.io/ecma262/#sec-math.hypot +$({ target: 'Math', stat: true, forced: BUGGY }, { + hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars + var sum = 0; + var i = 0; + var aLen = arguments.length; + var larg = 0; + var arg, div; + while (i < aLen) { + arg = abs(arguments[i++]); + if (larg < arg) { + div = larg / arg; + sum = sum * div * div + 1; + larg = arg; + } else if (arg > 0) { + div = arg / larg; + sum += div * div; + } else sum += arg; + } + return larg === Infinity ? Infinity : larg * sqrt(sum); + } +}); + +},{"../internals/export":361}],529:[function(require,module,exports){ +var $ = require('../internals/export'); +var fails = require('../internals/fails'); + +var nativeImul = Math.imul; + +var FORCED = fails(function () { + return nativeImul(0xFFFFFFFF, 5) != -5 || nativeImul.length != 2; +}); + +// `Math.imul` method +// https://tc39.github.io/ecma262/#sec-math.imul +// some WebKit versions fails with big numbers, some has wrong arity +$({ target: 'Math', stat: true, forced: FORCED }, { + imul: function imul(x, y) { + var UINT16 = 0xFFFF; + var xn = +x; + var yn = +y; + var xl = UINT16 & xn; + var yl = UINT16 & yn; + return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); + } +}); + +},{"../internals/export":361,"../internals/fails":362}],530:[function(require,module,exports){ +var $ = require('../internals/export'); + +var log = Math.log; +var LOG10E = Math.LOG10E; + +// `Math.log10` method +// https://tc39.github.io/ecma262/#sec-math.log10 +$({ target: 'Math', stat: true }, { + log10: function log10(x) { + return log(x) * LOG10E; + } +}); + +},{"../internals/export":361}],531:[function(require,module,exports){ +var $ = require('../internals/export'); +var log1p = require('../internals/math-log1p'); + +// `Math.log1p` method +// https://tc39.github.io/ecma262/#sec-math.log1p +$({ target: 'Math', stat: true }, { log1p: log1p }); + +},{"../internals/export":361,"../internals/math-log1p":401}],532:[function(require,module,exports){ +var $ = require('../internals/export'); + +var log = Math.log; +var LN2 = Math.LN2; + +// `Math.log2` method +// https://tc39.github.io/ecma262/#sec-math.log2 +$({ target: 'Math', stat: true }, { + log2: function log2(x) { + return log(x) / LN2; + } +}); + +},{"../internals/export":361}],533:[function(require,module,exports){ +var $ = require('../internals/export'); +var sign = require('../internals/math-sign'); + +// `Math.sign` method +// https://tc39.github.io/ecma262/#sec-math.sign +$({ target: 'Math', stat: true }, { + sign: sign +}); + +},{"../internals/export":361,"../internals/math-sign":403}],534:[function(require,module,exports){ +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var expm1 = require('../internals/math-expm1'); + +var abs = Math.abs; +var exp = Math.exp; +var E = Math.E; + +var FORCED = fails(function () { + return Math.sinh(-2e-17) != -2e-17; +}); + +// `Math.sinh` method +// https://tc39.github.io/ecma262/#sec-math.sinh +// V8 near Chromium 38 has a problem with very small numbers +$({ target: 'Math', stat: true, forced: FORCED }, { + sinh: function sinh(x) { + return abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/math-expm1":399}],535:[function(require,module,exports){ +var $ = require('../internals/export'); +var expm1 = require('../internals/math-expm1'); + +var exp = Math.exp; + +// `Math.tanh` method +// https://tc39.github.io/ecma262/#sec-math.tanh +$({ target: 'Math', stat: true }, { + tanh: function tanh(x) { + var a = expm1(x = +x); + var b = expm1(-x); + return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); + } +}); + +},{"../internals/export":361,"../internals/math-expm1":399}],536:[function(require,module,exports){ +var setToStringTag = require('../internals/set-to-string-tag'); + +// Math[@@toStringTag] property +// https://tc39.github.io/ecma262/#sec-math-@@tostringtag +setToStringTag(Math, 'Math', true); + +},{"../internals/set-to-string-tag":445}],537:[function(require,module,exports){ +var $ = require('../internals/export'); + +var ceil = Math.ceil; +var floor = Math.floor; + +// `Math.trunc` method +// https://tc39.github.io/ecma262/#sec-math.trunc +$({ target: 'Math', stat: true }, { + trunc: function trunc(it) { + return (it > 0 ? floor : ceil)(it); + } +}); + +},{"../internals/export":361}],538:[function(require,module,exports){ +'use strict'; +var DESCRIPTORS = require('../internals/descriptors'); +var global = require('../internals/global'); +var isForced = require('../internals/is-forced'); +var redefine = require('../internals/redefine'); +var has = require('../internals/has'); +var classof = require('../internals/classof-raw'); +var inheritIfRequired = require('../internals/inherit-if-required'); +var toPrimitive = require('../internals/to-primitive'); +var fails = require('../internals/fails'); +var create = require('../internals/object-create'); +var getOwnPropertyNames = require('../internals/object-get-own-property-names').f; +var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; +var defineProperty = require('../internals/object-define-property').f; +var trim = require('../internals/string-trim').trim; + +var NUMBER = 'Number'; +var NativeNumber = global[NUMBER]; +var NumberPrototype = NativeNumber.prototype; + +// Opera ~12 has broken Object#toString +var BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER; + +// `ToNumber` abstract operation +// https://tc39.github.io/ecma262/#sec-tonumber +var toNumber = function (argument) { + var it = toPrimitive(argument, false); + var first, third, radix, maxCode, digits, length, index, code; + if (typeof it == 'string' && it.length > 2) { + it = trim(it); + first = it.charCodeAt(0); + if (first === 43 || first === 45) { + third = it.charCodeAt(2); + if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix + } else if (first === 48) { + switch (it.charCodeAt(1)) { + case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i + case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i + default: return +it; + } + digits = it.slice(2); + length = digits.length; + for (index = 0; index < length; index++) { + code = digits.charCodeAt(index); + // parseInt parses a string to a first unavailable symbol + // but ToNumber should return NaN if a string contains unavailable symbols + if (code < 48 || code > maxCode) return NaN; + } return parseInt(digits, radix); + } + } return +it; +}; + +// `Number` constructor +// https://tc39.github.io/ecma262/#sec-number-constructor +if (isForced(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) { + var NumberWrapper = function Number(value) { + var it = arguments.length < 1 ? 0 : value; + var dummy = this; + return dummy instanceof NumberWrapper + // check on 1..constructor(foo) case + && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classof(dummy) != NUMBER) + ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it); + }; + for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : ( + // ES3: + 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + + // ES2015 (in case, if modules with ES2015 Number statics required before): + 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' + ).split(','), j = 0, key; keys.length > j; j++) { + if (has(NativeNumber, key = keys[j]) && !has(NumberWrapper, key)) { + defineProperty(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key)); + } + } + NumberWrapper.prototype = NumberPrototype; + NumberPrototype.constructor = NumberWrapper; + redefine(global, NUMBER, NumberWrapper); +} + +},{"../internals/classof-raw":333,"../internals/descriptors":357,"../internals/fails":362,"../internals/global":377,"../internals/has":378,"../internals/inherit-if-required":384,"../internals/is-forced":389,"../internals/object-create":413,"../internals/object-define-property":415,"../internals/object-get-own-property-descriptor":416,"../internals/object-get-own-property-names":418,"../internals/redefine":435,"../internals/string-trim":454,"../internals/to-primitive":465}],539:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Number.EPSILON` constant +// https://tc39.github.io/ecma262/#sec-number.epsilon +$({ target: 'Number', stat: true }, { + EPSILON: Math.pow(2, -52) +}); + +},{"../internals/export":361}],540:[function(require,module,exports){ +var $ = require('../internals/export'); +var numberIsFinite = require('../internals/number-is-finite'); + +// `Number.isFinite` method +// https://tc39.github.io/ecma262/#sec-number.isfinite +$({ target: 'Number', stat: true }, { isFinite: numberIsFinite }); + +},{"../internals/export":361,"../internals/number-is-finite":411}],541:[function(require,module,exports){ +var $ = require('../internals/export'); +var isInteger = require('../internals/is-integer'); + +// `Number.isInteger` method +// https://tc39.github.io/ecma262/#sec-number.isinteger +$({ target: 'Number', stat: true }, { + isInteger: isInteger +}); + +},{"../internals/export":361,"../internals/is-integer":390}],542:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Number.isNaN` method +// https://tc39.github.io/ecma262/#sec-number.isnan +$({ target: 'Number', stat: true }, { + isNaN: function isNaN(number) { + // eslint-disable-next-line no-self-compare + return number != number; + } +}); + +},{"../internals/export":361}],543:[function(require,module,exports){ +var $ = require('../internals/export'); +var isInteger = require('../internals/is-integer'); + +var abs = Math.abs; + +// `Number.isSafeInteger` method +// https://tc39.github.io/ecma262/#sec-number.issafeinteger +$({ target: 'Number', stat: true }, { + isSafeInteger: function isSafeInteger(number) { + return isInteger(number) && abs(number) <= 0x1FFFFFFFFFFFFF; + } +}); + +},{"../internals/export":361,"../internals/is-integer":390}],544:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Number.MAX_SAFE_INTEGER` constant +// https://tc39.github.io/ecma262/#sec-number.max_safe_integer +$({ target: 'Number', stat: true }, { + MAX_SAFE_INTEGER: 0x1FFFFFFFFFFFFF +}); + +},{"../internals/export":361}],545:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Number.MIN_SAFE_INTEGER` constant +// https://tc39.github.io/ecma262/#sec-number.min_safe_integer +$({ target: 'Number', stat: true }, { + MIN_SAFE_INTEGER: -0x1FFFFFFFFFFFFF +}); + +},{"../internals/export":361}],546:[function(require,module,exports){ +var $ = require('../internals/export'); +var parseFloat = require('../internals/parse-float'); + +// `Number.parseFloat` method +// https://tc39.github.io/ecma262/#sec-number.parseFloat +$({ target: 'Number', stat: true, forced: Number.parseFloat != parseFloat }, { + parseFloat: parseFloat +}); + +},{"../internals/export":361,"../internals/parse-float":428}],547:[function(require,module,exports){ +var $ = require('../internals/export'); +var parseInt = require('../internals/parse-int'); + +// `Number.parseInt` method +// https://tc39.github.io/ecma262/#sec-number.parseint +$({ target: 'Number', stat: true, forced: Number.parseInt != parseInt }, { + parseInt: parseInt +}); + +},{"../internals/export":361,"../internals/parse-int":429}],548:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var toInteger = require('../internals/to-integer'); +var thisNumberValue = require('../internals/this-number-value'); +var repeat = require('../internals/string-repeat'); +var fails = require('../internals/fails'); + +var nativeToFixed = 1.0.toFixed; +var floor = Math.floor; + +var pow = function (x, n, acc) { + return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); +}; + +var log = function (x) { + var n = 0; + var x2 = x; + while (x2 >= 4096) { + n += 12; + x2 /= 4096; + } + while (x2 >= 2) { + n += 1; + x2 /= 2; + } return n; +}; + +var FORCED = nativeToFixed && ( + 0.00008.toFixed(3) !== '0.000' || + 0.9.toFixed(0) !== '1' || + 1.255.toFixed(2) !== '1.25' || + 1000000000000000128.0.toFixed(0) !== '1000000000000000128' +) || !fails(function () { + // V8 ~ Android 4.3- + nativeToFixed.call({}); +}); + +// `Number.prototype.toFixed` method +// https://tc39.github.io/ecma262/#sec-number.prototype.tofixed +$({ target: 'Number', proto: true, forced: FORCED }, { + // eslint-disable-next-line max-statements + toFixed: function toFixed(fractionDigits) { + var number = thisNumberValue(this); + var fractDigits = toInteger(fractionDigits); + var data = [0, 0, 0, 0, 0, 0]; + var sign = ''; + var result = '0'; + var e, z, j, k; + + var multiply = function (n, c) { + var index = -1; + var c2 = c; + while (++index < 6) { + c2 += n * data[index]; + data[index] = c2 % 1e7; + c2 = floor(c2 / 1e7); + } + }; + + var divide = function (n) { + var index = 6; + var c = 0; + while (--index >= 0) { + c += data[index]; + data[index] = floor(c / n); + c = (c % n) * 1e7; + } + }; + + var dataToString = function () { + var index = 6; + var s = ''; + while (--index >= 0) { + if (s !== '' || index === 0 || data[index] !== 0) { + var t = String(data[index]); + s = s === '' ? t : s + repeat.call('0', 7 - t.length) + t; + } + } return s; + }; + + if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits'); + // eslint-disable-next-line no-self-compare + if (number != number) return 'NaN'; + if (number <= -1e21 || number >= 1e21) return String(number); + if (number < 0) { + sign = '-'; + number = -number; + } + if (number > 1e-21) { + e = log(number * pow(2, 69, 1)) - 69; + z = e < 0 ? number * pow(2, -e, 1) : number / pow(2, e, 1); + z *= 0x10000000000000; + e = 52 - e; + if (e > 0) { + multiply(0, z); + j = fractDigits; + while (j >= 7) { + multiply(1e7, 0); + j -= 7; + } + multiply(pow(10, j, 1), 0); + j = e - 1; + while (j >= 23) { + divide(1 << 23); + j -= 23; + } + divide(1 << j); + multiply(1, 1); + divide(2); + result = dataToString(); + } else { + multiply(0, z); + multiply(1 << -e, 0); + result = dataToString() + repeat.call('0', fractDigits); + } + } + if (fractDigits > 0) { + k = result.length; + result = sign + (k <= fractDigits + ? '0.' + repeat.call('0', fractDigits - k) + result + : result.slice(0, k - fractDigits) + '.' + result.slice(k - fractDigits)); + } else { + result = sign + result; + } return result; + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/string-repeat":453,"../internals/this-number-value":456,"../internals/to-integer":460}],549:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var thisNumberValue = require('../internals/this-number-value'); + +var nativeToPrecision = 1.0.toPrecision; + +var FORCED = fails(function () { + // IE7- + return nativeToPrecision.call(1, undefined) !== '1'; +}) || !fails(function () { + // V8 ~ Android 4.3- + nativeToPrecision.call({}); +}); + +// `Number.prototype.toPrecision` method +// https://tc39.github.io/ecma262/#sec-number.prototype.toprecision +$({ target: 'Number', proto: true, forced: FORCED }, { + toPrecision: function toPrecision(precision) { + return precision === undefined + ? nativeToPrecision.call(thisNumberValue(this)) + : nativeToPrecision.call(thisNumberValue(this), precision); + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/this-number-value":456}],550:[function(require,module,exports){ +var $ = require('../internals/export'); +var assign = require('../internals/object-assign'); + +// `Object.assign` method +// https://tc39.github.io/ecma262/#sec-object.assign +$({ target: 'Object', stat: true, forced: Object.assign !== assign }, { + assign: assign +}); + +},{"../internals/export":361,"../internals/object-assign":412}],551:[function(require,module,exports){ +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var create = require('../internals/object-create'); + +// `Object.create` method +// https://tc39.github.io/ecma262/#sec-object.create +$({ target: 'Object', stat: true, sham: !DESCRIPTORS }, { + create: create +}); + +},{"../internals/descriptors":357,"../internals/export":361,"../internals/object-create":413}],552:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var FORCED = require('../internals/forced-object-prototype-accessors-methods'); +var toObject = require('../internals/to-object'); +var aFunction = require('../internals/a-function'); +var definePropertyModule = require('../internals/object-define-property'); + +// `Object.prototype.__defineGetter__` method +// https://tc39.github.io/ecma262/#sec-object.prototype.__defineGetter__ +if (DESCRIPTORS) { + $({ target: 'Object', proto: true, forced: FORCED }, { + __defineGetter__: function __defineGetter__(P, getter) { + definePropertyModule.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); + } + }); +} + +},{"../internals/a-function":310,"../internals/descriptors":357,"../internals/export":361,"../internals/forced-object-prototype-accessors-methods":365,"../internals/object-define-property":415,"../internals/to-object":462}],553:[function(require,module,exports){ +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var defineProperties = require('../internals/object-define-properties'); + +// `Object.defineProperties` method +// https://tc39.github.io/ecma262/#sec-object.defineproperties +$({ target: 'Object', stat: true, forced: !DESCRIPTORS, sham: !DESCRIPTORS }, { + defineProperties: defineProperties +}); + +},{"../internals/descriptors":357,"../internals/export":361,"../internals/object-define-properties":414}],554:[function(require,module,exports){ +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var objectDefinePropertyModile = require('../internals/object-define-property'); + +// `Object.defineProperty` method +// https://tc39.github.io/ecma262/#sec-object.defineproperty +$({ target: 'Object', stat: true, forced: !DESCRIPTORS, sham: !DESCRIPTORS }, { + defineProperty: objectDefinePropertyModile.f +}); + +},{"../internals/descriptors":357,"../internals/export":361,"../internals/object-define-property":415}],555:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var FORCED = require('../internals/forced-object-prototype-accessors-methods'); +var toObject = require('../internals/to-object'); +var aFunction = require('../internals/a-function'); +var definePropertyModule = require('../internals/object-define-property'); + +// `Object.prototype.__defineSetter__` method +// https://tc39.github.io/ecma262/#sec-object.prototype.__defineSetter__ +if (DESCRIPTORS) { + $({ target: 'Object', proto: true, forced: FORCED }, { + __defineSetter__: function __defineSetter__(P, setter) { + definePropertyModule.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); + } + }); +} + +},{"../internals/a-function":310,"../internals/descriptors":357,"../internals/export":361,"../internals/forced-object-prototype-accessors-methods":365,"../internals/object-define-property":415,"../internals/to-object":462}],556:[function(require,module,exports){ +var $ = require('../internals/export'); +var $entries = require('../internals/object-to-array').entries; + +// `Object.entries` method +// https://tc39.github.io/ecma262/#sec-object.entries +$({ target: 'Object', stat: true }, { + entries: function entries(O) { + return $entries(O); + } +}); + +},{"../internals/export":361,"../internals/object-to-array":425}],557:[function(require,module,exports){ +var $ = require('../internals/export'); +var FREEZING = require('../internals/freezing'); +var fails = require('../internals/fails'); +var isObject = require('../internals/is-object'); +var onFreeze = require('../internals/internal-metadata').onFreeze; + +var nativeFreeze = Object.freeze; +var FAILS_ON_PRIMITIVES = fails(function () { nativeFreeze(1); }); + +// `Object.freeze` method +// https://tc39.github.io/ecma262/#sec-object.freeze +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING }, { + freeze: function freeze(it) { + return nativeFreeze && isObject(it) ? nativeFreeze(onFreeze(it)) : it; + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/freezing":368,"../internals/internal-metadata":385,"../internals/is-object":392}],558:[function(require,module,exports){ +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var createProperty = require('../internals/create-property'); + +// `Object.fromEntries` method +// https://github.com/tc39/proposal-object-from-entries +$({ target: 'Object', stat: true }, { + fromEntries: function fromEntries(iterable) { + var obj = {}; + iterate(iterable, function (k, v) { + createProperty(obj, k, v); + }, undefined, true); + return obj; + } +}); + +},{"../internals/create-property":352,"../internals/export":361,"../internals/iterate":395}],559:[function(require,module,exports){ +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var toIndexedObject = require('../internals/to-indexed-object'); +var nativeGetOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; +var DESCRIPTORS = require('../internals/descriptors'); + +var FAILS_ON_PRIMITIVES = fails(function () { nativeGetOwnPropertyDescriptor(1); }); +var FORCED = !DESCRIPTORS || FAILS_ON_PRIMITIVES; + +// `Object.getOwnPropertyDescriptor` method +// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor +$({ target: 'Object', stat: true, forced: FORCED, sham: !DESCRIPTORS }, { + getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) { + return nativeGetOwnPropertyDescriptor(toIndexedObject(it), key); + } +}); + +},{"../internals/descriptors":357,"../internals/export":361,"../internals/fails":362,"../internals/object-get-own-property-descriptor":416,"../internals/to-indexed-object":459}],560:[function(require,module,exports){ +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var ownKeys = require('../internals/own-keys'); +var toIndexedObject = require('../internals/to-indexed-object'); +var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor'); +var createProperty = require('../internals/create-property'); + +// `Object.getOwnPropertyDescriptors` method +// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors +$({ target: 'Object', stat: true, sham: !DESCRIPTORS }, { + getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { + var O = toIndexedObject(object); + var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; + var keys = ownKeys(O); + var result = {}; + var index = 0; + var key, descriptor; + while (keys.length > index) { + descriptor = getOwnPropertyDescriptor(O, key = keys[index++]); + if (descriptor !== undefined) createProperty(result, key, descriptor); + } + return result; + } +}); + +},{"../internals/create-property":352,"../internals/descriptors":357,"../internals/export":361,"../internals/object-get-own-property-descriptor":416,"../internals/own-keys":427,"../internals/to-indexed-object":459}],561:[function(require,module,exports){ +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names-external').f; + +var FAILS_ON_PRIMITIVES = fails(function () { return !Object.getOwnPropertyNames(1); }); + +// `Object.getOwnPropertyNames` method +// https://tc39.github.io/ecma262/#sec-object.getownpropertynames +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { + getOwnPropertyNames: nativeGetOwnPropertyNames +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/object-get-own-property-names-external":417}],562:[function(require,module,exports){ +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var toObject = require('../internals/to-object'); +var nativeGetPrototypeOf = require('../internals/object-get-prototype-of'); +var CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter'); + +var FAILS_ON_PRIMITIVES = fails(function () { nativeGetPrototypeOf(1); }); + +// `Object.getPrototypeOf` method +// https://tc39.github.io/ecma262/#sec-object.getprototypeof +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !CORRECT_PROTOTYPE_GETTER }, { + getPrototypeOf: function getPrototypeOf(it) { + return nativeGetPrototypeOf(toObject(it)); + } +}); + + +},{"../internals/correct-prototype-getter":345,"../internals/export":361,"../internals/fails":362,"../internals/object-get-prototype-of":420,"../internals/to-object":462}],563:[function(require,module,exports){ +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var isObject = require('../internals/is-object'); + +var nativeIsExtensible = Object.isExtensible; +var FAILS_ON_PRIMITIVES = fails(function () { nativeIsExtensible(1); }); + +// `Object.isExtensible` method +// https://tc39.github.io/ecma262/#sec-object.isextensible +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { + isExtensible: function isExtensible(it) { + return isObject(it) ? nativeIsExtensible ? nativeIsExtensible(it) : true : false; + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/is-object":392}],564:[function(require,module,exports){ +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var isObject = require('../internals/is-object'); + +var nativeIsFrozen = Object.isFrozen; +var FAILS_ON_PRIMITIVES = fails(function () { nativeIsFrozen(1); }); + +// `Object.isFrozen` method +// https://tc39.github.io/ecma262/#sec-object.isfrozen +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { + isFrozen: function isFrozen(it) { + return isObject(it) ? nativeIsFrozen ? nativeIsFrozen(it) : false : true; + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/is-object":392}],565:[function(require,module,exports){ +var $ = require('../internals/export'); +var fails = require('../internals/fails'); +var isObject = require('../internals/is-object'); + +var nativeIsSealed = Object.isSealed; +var FAILS_ON_PRIMITIVES = fails(function () { nativeIsSealed(1); }); + +// `Object.isSealed` method +// https://tc39.github.io/ecma262/#sec-object.issealed +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { + isSealed: function isSealed(it) { + return isObject(it) ? nativeIsSealed ? nativeIsSealed(it) : false : true; + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/is-object":392}],566:[function(require,module,exports){ +var $ = require('../internals/export'); +var is = require('../internals/same-value'); + +// `Object.is` method +// https://tc39.github.io/ecma262/#sec-object.is +$({ target: 'Object', stat: true }, { + is: is +}); + +},{"../internals/export":361,"../internals/same-value":442}],567:[function(require,module,exports){ +var $ = require('../internals/export'); +var toObject = require('../internals/to-object'); +var nativeKeys = require('../internals/object-keys'); +var fails = require('../internals/fails'); + +var FAILS_ON_PRIMITIVES = fails(function () { nativeKeys(1); }); + +// `Object.keys` method +// https://tc39.github.io/ecma262/#sec-object.keys +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { + keys: function keys(it) { + return nativeKeys(toObject(it)); + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/object-keys":422,"../internals/to-object":462}],568:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var FORCED = require('../internals/forced-object-prototype-accessors-methods'); +var toObject = require('../internals/to-object'); +var toPrimitive = require('../internals/to-primitive'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; + +// `Object.prototype.__lookupGetter__` method +// https://tc39.github.io/ecma262/#sec-object.prototype.__lookupGetter__ +if (DESCRIPTORS) { + $({ target: 'Object', proto: true, forced: FORCED }, { + __lookupGetter__: function __lookupGetter__(P) { + var O = toObject(this); + var key = toPrimitive(P, true); + var desc; + do { + if (desc = getOwnPropertyDescriptor(O, key)) return desc.get; + } while (O = getPrototypeOf(O)); + } + }); +} + +},{"../internals/descriptors":357,"../internals/export":361,"../internals/forced-object-prototype-accessors-methods":365,"../internals/object-get-own-property-descriptor":416,"../internals/object-get-prototype-of":420,"../internals/to-object":462,"../internals/to-primitive":465}],569:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var FORCED = require('../internals/forced-object-prototype-accessors-methods'); +var toObject = require('../internals/to-object'); +var toPrimitive = require('../internals/to-primitive'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; + +// `Object.prototype.__lookupSetter__` method +// https://tc39.github.io/ecma262/#sec-object.prototype.__lookupSetter__ +if (DESCRIPTORS) { + $({ target: 'Object', proto: true, forced: FORCED }, { + __lookupSetter__: function __lookupSetter__(P) { + var O = toObject(this); + var key = toPrimitive(P, true); + var desc; + do { + if (desc = getOwnPropertyDescriptor(O, key)) return desc.set; + } while (O = getPrototypeOf(O)); + } + }); +} + +},{"../internals/descriptors":357,"../internals/export":361,"../internals/forced-object-prototype-accessors-methods":365,"../internals/object-get-own-property-descriptor":416,"../internals/object-get-prototype-of":420,"../internals/to-object":462,"../internals/to-primitive":465}],570:[function(require,module,exports){ +var $ = require('../internals/export'); +var isObject = require('../internals/is-object'); +var onFreeze = require('../internals/internal-metadata').onFreeze; +var FREEZING = require('../internals/freezing'); +var fails = require('../internals/fails'); + +var nativePreventExtensions = Object.preventExtensions; +var FAILS_ON_PRIMITIVES = fails(function () { nativePreventExtensions(1); }); + +// `Object.preventExtensions` method +// https://tc39.github.io/ecma262/#sec-object.preventextensions +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING }, { + preventExtensions: function preventExtensions(it) { + return nativePreventExtensions && isObject(it) ? nativePreventExtensions(onFreeze(it)) : it; + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/freezing":368,"../internals/internal-metadata":385,"../internals/is-object":392}],571:[function(require,module,exports){ +var $ = require('../internals/export'); +var isObject = require('../internals/is-object'); +var onFreeze = require('../internals/internal-metadata').onFreeze; +var FREEZING = require('../internals/freezing'); +var fails = require('../internals/fails'); + +var nativeSeal = Object.seal; +var FAILS_ON_PRIMITIVES = fails(function () { nativeSeal(1); }); + +// `Object.seal` method +// https://tc39.github.io/ecma262/#sec-object.seal +$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING }, { + seal: function seal(it) { + return nativeSeal && isObject(it) ? nativeSeal(onFreeze(it)) : it; + } +}); + +},{"../internals/export":361,"../internals/fails":362,"../internals/freezing":368,"../internals/internal-metadata":385,"../internals/is-object":392}],572:[function(require,module,exports){ +var $ = require('../internals/export'); +var setPrototypeOf = require('../internals/object-set-prototype-of'); + +// `Object.setPrototypeOf` method +// https://tc39.github.io/ecma262/#sec-object.setprototypeof +$({ target: 'Object', stat: true }, { + setPrototypeOf: setPrototypeOf +}); + +},{"../internals/export":361,"../internals/object-set-prototype-of":424}],573:[function(require,module,exports){ +var redefine = require('../internals/redefine'); +var toString = require('../internals/object-to-string'); + +var ObjectPrototype = Object.prototype; + +// `Object.prototype.toString` method +// https://tc39.github.io/ecma262/#sec-object.prototype.tostring +if (toString !== ObjectPrototype.toString) { + redefine(ObjectPrototype, 'toString', toString, { unsafe: true }); +} + +},{"../internals/object-to-string":426,"../internals/redefine":435}],574:[function(require,module,exports){ +var $ = require('../internals/export'); +var $values = require('../internals/object-to-array').values; + +// `Object.values` method +// https://tc39.github.io/ecma262/#sec-object.values +$({ target: 'Object', stat: true }, { + values: function values(O) { + return $values(O); + } +}); + +},{"../internals/export":361,"../internals/object-to-array":425}],575:[function(require,module,exports){ +var $ = require('../internals/export'); +var parseFloatImplementation = require('../internals/parse-float'); + +// `parseFloat` method +// https://tc39.github.io/ecma262/#sec-parsefloat-string +$({ global: true, forced: parseFloat != parseFloatImplementation }, { + parseFloat: parseFloatImplementation +}); + +},{"../internals/export":361,"../internals/parse-float":428}],576:[function(require,module,exports){ +var $ = require('../internals/export'); +var parseIntImplementation = require('../internals/parse-int'); + +// `parseInt` method +// https://tc39.github.io/ecma262/#sec-parseint-string-radix +$({ global: true, forced: parseInt != parseIntImplementation }, { + parseInt: parseIntImplementation +}); + +},{"../internals/export":361,"../internals/parse-int":429}],577:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var aFunction = require('../internals/a-function'); +var newPromiseCapabilityModule = require('../internals/new-promise-capability'); +var perform = require('../internals/perform'); +var iterate = require('../internals/iterate'); + +// `Promise.allSettled` method +// https://github.com/tc39/proposal-promise-allSettled +$({ target: 'Promise', stat: true }, { + allSettled: function allSettled(iterable) { + var C = this; + var capability = newPromiseCapabilityModule.f(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var promiseResolve = aFunction(C.resolve); + var values = []; + var counter = 0; + var remaining = 1; + iterate(iterable, function (promise) { + var index = counter++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + promiseResolve.call(C, promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[index] = { status: 'fulfilled', value: value }; + --remaining || resolve(values); + }, function (e) { + if (alreadyCalled) return; + alreadyCalled = true; + values[index] = { status: 'rejected', reason: e }; + --remaining || resolve(values); + }); + }); + --remaining || resolve(values); + }); + if (result.error) reject(result.value); + return capability.promise; + } +}); + +},{"../internals/a-function":310,"../internals/export":361,"../internals/iterate":395,"../internals/new-promise-capability":409,"../internals/perform":431}],578:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var NativePromise = require('../internals/native-promise-constructor'); +var getBuiltIn = require('../internals/get-built-in'); +var speciesConstructor = require('../internals/species-constructor'); +var promiseResolve = require('../internals/promise-resolve'); +var redefine = require('../internals/redefine'); + +// `Promise.prototype.finally` method +// https://tc39.github.io/ecma262/#sec-promise.prototype.finally +$({ target: 'Promise', proto: true, real: true }, { + 'finally': function (onFinally) { + var C = speciesConstructor(this, getBuiltIn('Promise')); + var isFunction = typeof onFinally == 'function'; + return this.then( + isFunction ? function (x) { + return promiseResolve(C, onFinally()).then(function () { return x; }); + } : onFinally, + isFunction ? function (e) { + return promiseResolve(C, onFinally()).then(function () { throw e; }); + } : onFinally + ); + } +}); + +// patch native Promise.prototype for native async functions +if (!IS_PURE && typeof NativePromise == 'function' && !NativePromise.prototype['finally']) { + redefine(NativePromise.prototype, 'finally', getBuiltIn('Promise').prototype['finally']); +} + +},{"../internals/export":361,"../internals/get-built-in":372,"../internals/is-pure":393,"../internals/native-promise-constructor":405,"../internals/promise-resolve":432,"../internals/redefine":435,"../internals/species-constructor":450}],579:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var global = require('../internals/global'); +var getBuiltIn = require('../internals/get-built-in'); +var NativePromise = require('../internals/native-promise-constructor'); +var redefine = require('../internals/redefine'); +var redefineAll = require('../internals/redefine-all'); +var shared = require('../internals/shared'); +var setToStringTag = require('../internals/set-to-string-tag'); +var setSpecies = require('../internals/set-species'); +var isObject = require('../internals/is-object'); +var aFunction = require('../internals/a-function'); +var anInstance = require('../internals/an-instance'); +var classof = require('../internals/classof-raw'); +var iterate = require('../internals/iterate'); +var checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration'); +var speciesConstructor = require('../internals/species-constructor'); +var task = require('../internals/task').set; +var microtask = require('../internals/microtask'); +var promiseResolve = require('../internals/promise-resolve'); +var hostReportErrors = require('../internals/host-report-errors'); +var newPromiseCapabilityModule = require('../internals/new-promise-capability'); +var perform = require('../internals/perform'); +var InternalStateModule = require('../internals/internal-state'); +var isForced = require('../internals/is-forced'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var V8_VERSION = require('../internals/v8-version'); + +var SPECIES = wellKnownSymbol('species'); +var PROMISE = 'Promise'; +var getInternalState = InternalStateModule.get; +var setInternalState = InternalStateModule.set; +var getInternalPromiseState = InternalStateModule.getterFor(PROMISE); +var PromiseConstructor = NativePromise; +var TypeError = global.TypeError; +var document = global.document; +var process = global.process; +var inspectSource = shared('inspectSource'); +var $fetch = getBuiltIn('fetch'); +var newPromiseCapability = newPromiseCapabilityModule.f; +var newGenericPromiseCapability = newPromiseCapability; +var IS_NODE = classof(process) == 'process'; +var DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent); +var UNHANDLED_REJECTION = 'unhandledrejection'; +var REJECTION_HANDLED = 'rejectionhandled'; +var PENDING = 0; +var FULFILLED = 1; +var REJECTED = 2; +var HANDLED = 1; +var UNHANDLED = 2; +var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen; + +var FORCED = isForced(PROMISE, function () { + var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor); + // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables + // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 + // We can't detect it synchronously, so just check versions + if (V8_VERSION === 66) return true; + // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test + if (!GLOBAL_CORE_JS_PROMISE && !IS_NODE && typeof PromiseRejectionEvent != 'function') return true; + // We need Promise#finally in the pure version for preventing prototype pollution + if (IS_PURE && !PromiseConstructor.prototype['finally']) return true; + // We can't use @@species feature detection in V8 since it causes + // deoptimization and performance degradation + // https://github.com/zloirock/core-js/issues/679 + if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false; + // Detect correctness of subclassing with @@species support + var promise = PromiseConstructor.resolve(1); + var FakePromise = function (exec) { + exec(function () { /* empty */ }, function () { /* empty */ }); + }; + var constructor = promise.constructor = {}; + constructor[SPECIES] = FakePromise; + return !(promise.then(function () { /* empty */ }) instanceof FakePromise); +}); + +var INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) { + PromiseConstructor.all(iterable)['catch'](function () { /* empty */ }); +}); + +// helpers +var isThenable = function (it) { + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; +}; + +var notify = function (promise, state, isReject) { + if (state.notified) return; + state.notified = true; + var chain = state.reactions; + microtask(function () { + var value = state.value; + var ok = state.state == FULFILLED; + var index = 0; + // variable length - can't use forEach + while (chain.length > index) { + var reaction = chain[index++]; + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then, exited; + try { + if (handler) { + if (!ok) { + if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state); + state.rejection = HANDLED; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); // can throw + if (domain) { + domain.exit(); + exited = true; + } + } + if (result === reaction.promise) { + reject(TypeError('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (error) { + if (domain && !exited) domain.exit(); + reject(error); + } + } + state.reactions = []; + state.notified = false; + if (isReject && !state.rejection) onUnhandled(promise, state); + }); +}; + +var dispatchEvent = function (name, promise, reason) { + var event, handler; + if (DISPATCH_EVENT) { + event = document.createEvent('Event'); + event.promise = promise; + event.reason = reason; + event.initEvent(name, false, true); + global.dispatchEvent(event); + } else event = { promise: promise, reason: reason }; + if (handler = global['on' + name]) handler(event); + else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason); +}; + +var onUnhandled = function (promise, state) { + task.call(global, function () { + var value = state.value; + var IS_UNHANDLED = isUnhandled(state); + var result; + if (IS_UNHANDLED) { + result = perform(function () { + if (IS_NODE) { + process.emit('unhandledRejection', value, promise); + } else dispatchEvent(UNHANDLED_REJECTION, promise, value); + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED; + if (result.error) throw result.value; + } + }); +}; + +var isUnhandled = function (state) { + return state.rejection !== HANDLED && !state.parent; +}; + +var onHandleUnhandled = function (promise, state) { + task.call(global, function () { + if (IS_NODE) { + process.emit('rejectionHandled', promise); + } else dispatchEvent(REJECTION_HANDLED, promise, state.value); + }); +}; + +var bind = function (fn, promise, state, unwrap) { + return function (value) { + fn(promise, state, value, unwrap); + }; +}; + +var internalReject = function (promise, state, value, unwrap) { + if (state.done) return; + state.done = true; + if (unwrap) state = unwrap; + state.value = value; + state.state = REJECTED; + notify(promise, state, true); +}; + +var internalResolve = function (promise, state, value, unwrap) { + if (state.done) return; + state.done = true; + if (unwrap) state = unwrap; + try { + if (promise === value) throw TypeError("Promise can't be resolved itself"); + var then = isThenable(value); + if (then) { + microtask(function () { + var wrapper = { done: false }; + try { + then.call(value, + bind(internalResolve, promise, wrapper, state), + bind(internalReject, promise, wrapper, state) + ); + } catch (error) { + internalReject(promise, wrapper, error, state); + } + }); + } else { + state.value = value; + state.state = FULFILLED; + notify(promise, state, false); + } + } catch (error) { + internalReject(promise, { done: false }, error, state); + } +}; + +// constructor polyfill +if (FORCED) { + // 25.4.3.1 Promise(executor) + PromiseConstructor = function Promise(executor) { + anInstance(this, PromiseConstructor, PROMISE); + aFunction(executor); + Internal.call(this); + var state = getInternalState(this); + try { + executor(bind(internalResolve, this, state), bind(internalReject, this, state)); + } catch (error) { + internalReject(this, state, error); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + setInternalState(this, { + type: PROMISE, + done: false, + notified: false, + parent: false, + reactions: [], + rejection: false, + state: PENDING, + value: undefined + }); + }; + Internal.prototype = redefineAll(PromiseConstructor.prototype, { + // `Promise.prototype.then` method + // https://tc39.github.io/ecma262/#sec-promise.prototype.then + then: function then(onFulfilled, onRejected) { + var state = getInternalPromiseState(this); + var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = IS_NODE ? process.domain : undefined; + state.parent = true; + state.reactions.push(reaction); + if (state.state != PENDING) notify(this, state, false); + return reaction.promise; + }, + // `Promise.prototype.catch` method + // https://tc39.github.io/ecma262/#sec-promise.prototype.catch + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + var state = getInternalState(promise); + this.promise = promise; + this.resolve = bind(internalResolve, promise, state); + this.reject = bind(internalReject, promise, state); + }; + newPromiseCapabilityModule.f = newPromiseCapability = function (C) { + return C === PromiseConstructor || C === PromiseWrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; + + if (!IS_PURE && typeof NativePromise == 'function') { + nativeThen = NativePromise.prototype.then; + + // wrap native Promise#then for native async functions + redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) { + var that = this; + return new PromiseConstructor(function (resolve, reject) { + nativeThen.call(that, resolve, reject); + }).then(onFulfilled, onRejected); + // https://github.com/zloirock/core-js/issues/640 + }, { unsafe: true }); + + // wrap fetch result + if (typeof $fetch == 'function') $({ global: true, enumerable: true, forced: true }, { + // eslint-disable-next-line no-unused-vars + fetch: function fetch(input /* , init */) { + return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments)); + } + }); + } +} + +$({ global: true, wrap: true, forced: FORCED }, { + Promise: PromiseConstructor +}); + +setToStringTag(PromiseConstructor, PROMISE, false, true); +setSpecies(PROMISE); + +PromiseWrapper = getBuiltIn(PROMISE); + +// statics +$({ target: PROMISE, stat: true, forced: FORCED }, { + // `Promise.reject` method + // https://tc39.github.io/ecma262/#sec-promise.reject + reject: function reject(r) { + var capability = newPromiseCapability(this); + capability.reject.call(undefined, r); + return capability.promise; + } +}); + +$({ target: PROMISE, stat: true, forced: IS_PURE || FORCED }, { + // `Promise.resolve` method + // https://tc39.github.io/ecma262/#sec-promise.resolve + resolve: function resolve(x) { + return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x); + } +}); + +$({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION }, { + // `Promise.all` method + // https://tc39.github.io/ecma262/#sec-promise.all + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var $promiseResolve = aFunction(C.resolve); + var values = []; + var counter = 0; + var remaining = 1; + iterate(iterable, function (promise) { + var index = counter++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + $promiseResolve.call(C, promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.error) reject(result.value); + return capability.promise; + }, + // `Promise.race` method + // https://tc39.github.io/ecma262/#sec-promise.race + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = perform(function () { + var $promiseResolve = aFunction(C.resolve); + iterate(iterable, function (promise) { + $promiseResolve.call(C, promise).then(capability.resolve, reject); + }); + }); + if (result.error) reject(result.value); + return capability.promise; + } +}); + +},{"../internals/a-function":310,"../internals/an-instance":314,"../internals/check-correctness-of-iteration":332,"../internals/classof-raw":333,"../internals/export":361,"../internals/get-built-in":372,"../internals/global":377,"../internals/host-report-errors":380,"../internals/internal-state":386,"../internals/is-forced":389,"../internals/is-object":392,"../internals/is-pure":393,"../internals/iterate":395,"../internals/microtask":404,"../internals/native-promise-constructor":405,"../internals/new-promise-capability":409,"../internals/perform":431,"../internals/promise-resolve":432,"../internals/redefine":435,"../internals/redefine-all":434,"../internals/set-species":444,"../internals/set-to-string-tag":445,"../internals/shared":448,"../internals/species-constructor":450,"../internals/task":455,"../internals/v8-version":471,"../internals/well-known-symbol":473}],580:[function(require,module,exports){ +var $ = require('../internals/export'); +var getBuiltIn = require('../internals/get-built-in'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var fails = require('../internals/fails'); + +var nativeApply = getBuiltIn('Reflect', 'apply'); +var functionApply = Function.apply; + +// MS Edge argumentsList argument is optional +var OPTIONAL_ARGUMENTS_LIST = !fails(function () { + nativeApply(function () { /* empty */ }); +}); + +// `Reflect.apply` method +// https://tc39.github.io/ecma262/#sec-reflect.apply +$({ target: 'Reflect', stat: true, forced: OPTIONAL_ARGUMENTS_LIST }, { + apply: function apply(target, thisArgument, argumentsList) { + aFunction(target); + anObject(argumentsList); + return nativeApply + ? nativeApply(target, thisArgument, argumentsList) + : functionApply.call(target, thisArgument, argumentsList); + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/fails":362,"../internals/get-built-in":372}],581:[function(require,module,exports){ +var $ = require('../internals/export'); +var getBuiltIn = require('../internals/get-built-in'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var isObject = require('../internals/is-object'); +var create = require('../internals/object-create'); +var bind = require('../internals/function-bind'); +var fails = require('../internals/fails'); + +var nativeConstruct = getBuiltIn('Reflect', 'construct'); + +// `Reflect.construct` method +// https://tc39.github.io/ecma262/#sec-reflect.construct +// MS Edge supports only 2 arguments and argumentsList argument is optional +// FF Nightly sets third argument as `new.target`, but does not create `this` from it +var NEW_TARGET_BUG = fails(function () { + function F() { /* empty */ } + return !(nativeConstruct(function () { /* empty */ }, [], F) instanceof F); +}); +var ARGS_BUG = !fails(function () { + nativeConstruct(function () { /* empty */ }); +}); +var FORCED = NEW_TARGET_BUG || ARGS_BUG; + +$({ target: 'Reflect', stat: true, forced: FORCED, sham: FORCED }, { + construct: function construct(Target, args /* , newTarget */) { + aFunction(Target); + anObject(args); + var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); + if (ARGS_BUG && !NEW_TARGET_BUG) return nativeConstruct(Target, args, newTarget); + if (Target == newTarget) { + // w/o altered newTarget, optimization for 0-4 arguments + switch (args.length) { + case 0: return new Target(); + case 1: return new Target(args[0]); + case 2: return new Target(args[0], args[1]); + case 3: return new Target(args[0], args[1], args[2]); + case 4: return new Target(args[0], args[1], args[2], args[3]); + } + // w/o altered newTarget, lot of arguments case + var $args = [null]; + $args.push.apply($args, args); + return new (bind.apply(Target, $args))(); + } + // with altered newTarget, not support built-in constructors + var proto = newTarget.prototype; + var instance = create(isObject(proto) ? proto : Object.prototype); + var result = Function.apply.call(Target, instance, args); + return isObject(result) ? result : instance; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/fails":362,"../internals/function-bind":369,"../internals/get-built-in":372,"../internals/is-object":392,"../internals/object-create":413}],582:[function(require,module,exports){ +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var anObject = require('../internals/an-object'); +var toPrimitive = require('../internals/to-primitive'); +var definePropertyModule = require('../internals/object-define-property'); +var fails = require('../internals/fails'); + +// MS Edge has broken Reflect.defineProperty - throwing instead of returning false +var ERROR_INSTEAD_OF_FALSE = fails(function () { + // eslint-disable-next-line no-undef + Reflect.defineProperty(definePropertyModule.f({}, 1, { value: 1 }), 1, { value: 2 }); +}); + +// `Reflect.defineProperty` method +// https://tc39.github.io/ecma262/#sec-reflect.defineproperty +$({ target: 'Reflect', stat: true, forced: ERROR_INSTEAD_OF_FALSE, sham: !DESCRIPTORS }, { + defineProperty: function defineProperty(target, propertyKey, attributes) { + anObject(target); + var key = toPrimitive(propertyKey, true); + anObject(attributes); + try { + definePropertyModule.f(target, key, attributes); + return true; + } catch (error) { + return false; + } + } +}); + +},{"../internals/an-object":315,"../internals/descriptors":357,"../internals/export":361,"../internals/fails":362,"../internals/object-define-property":415,"../internals/to-primitive":465}],583:[function(require,module,exports){ +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; + +// `Reflect.deleteProperty` method +// https://tc39.github.io/ecma262/#sec-reflect.deleteproperty +$({ target: 'Reflect', stat: true }, { + deleteProperty: function deleteProperty(target, propertyKey) { + var descriptor = getOwnPropertyDescriptor(anObject(target), propertyKey); + return descriptor && !descriptor.configurable ? false : delete target[propertyKey]; + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/object-get-own-property-descriptor":416}],584:[function(require,module,exports){ +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var anObject = require('../internals/an-object'); +var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor'); + +// `Reflect.getOwnPropertyDescriptor` method +// https://tc39.github.io/ecma262/#sec-reflect.getownpropertydescriptor +$({ target: 'Reflect', stat: true, sham: !DESCRIPTORS }, { + getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { + return getOwnPropertyDescriptorModule.f(anObject(target), propertyKey); + } +}); + +},{"../internals/an-object":315,"../internals/descriptors":357,"../internals/export":361,"../internals/object-get-own-property-descriptor":416}],585:[function(require,module,exports){ +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var objectGetPrototypeOf = require('../internals/object-get-prototype-of'); +var CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter'); + +// `Reflect.getPrototypeOf` method +// https://tc39.github.io/ecma262/#sec-reflect.getprototypeof +$({ target: 'Reflect', stat: true, sham: !CORRECT_PROTOTYPE_GETTER }, { + getPrototypeOf: function getPrototypeOf(target) { + return objectGetPrototypeOf(anObject(target)); + } +}); + +},{"../internals/an-object":315,"../internals/correct-prototype-getter":345,"../internals/export":361,"../internals/object-get-prototype-of":420}],586:[function(require,module,exports){ +var $ = require('../internals/export'); +var isObject = require('../internals/is-object'); +var anObject = require('../internals/an-object'); +var has = require('../internals/has'); +var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); + +// `Reflect.get` method +// https://tc39.github.io/ecma262/#sec-reflect.get +function get(target, propertyKey /* , receiver */) { + var receiver = arguments.length < 3 ? target : arguments[2]; + var descriptor, prototype; + if (anObject(target) === receiver) return target[propertyKey]; + if (descriptor = getOwnPropertyDescriptorModule.f(target, propertyKey)) return has(descriptor, 'value') + ? descriptor.value + : descriptor.get === undefined + ? undefined + : descriptor.get.call(receiver); + if (isObject(prototype = getPrototypeOf(target))) return get(prototype, propertyKey, receiver); +} + +$({ target: 'Reflect', stat: true }, { + get: get +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/has":378,"../internals/is-object":392,"../internals/object-get-own-property-descriptor":416,"../internals/object-get-prototype-of":420}],587:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Reflect.has` method +// https://tc39.github.io/ecma262/#sec-reflect.has +$({ target: 'Reflect', stat: true }, { + has: function has(target, propertyKey) { + return propertyKey in target; + } +}); + +},{"../internals/export":361}],588:[function(require,module,exports){ +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); + +var objectIsExtensible = Object.isExtensible; + +// `Reflect.isExtensible` method +// https://tc39.github.io/ecma262/#sec-reflect.isextensible +$({ target: 'Reflect', stat: true }, { + isExtensible: function isExtensible(target) { + anObject(target); + return objectIsExtensible ? objectIsExtensible(target) : true; + } +}); + +},{"../internals/an-object":315,"../internals/export":361}],589:[function(require,module,exports){ +var $ = require('../internals/export'); +var ownKeys = require('../internals/own-keys'); + +// `Reflect.ownKeys` method +// https://tc39.github.io/ecma262/#sec-reflect.ownkeys +$({ target: 'Reflect', stat: true }, { + ownKeys: ownKeys +}); + +},{"../internals/export":361,"../internals/own-keys":427}],590:[function(require,module,exports){ +var $ = require('../internals/export'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var FREEZING = require('../internals/freezing'); + +// `Reflect.preventExtensions` method +// https://tc39.github.io/ecma262/#sec-reflect.preventextensions +$({ target: 'Reflect', stat: true, sham: !FREEZING }, { + preventExtensions: function preventExtensions(target) { + anObject(target); + try { + var objectPreventExtensions = getBuiltIn('Object', 'preventExtensions'); + if (objectPreventExtensions) objectPreventExtensions(target); + return true; + } catch (error) { + return false; + } + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/freezing":368,"../internals/get-built-in":372}],591:[function(require,module,exports){ +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var aPossiblePrototype = require('../internals/a-possible-prototype'); +var objectSetPrototypeOf = require('../internals/object-set-prototype-of'); + +// `Reflect.setPrototypeOf` method +// https://tc39.github.io/ecma262/#sec-reflect.setprototypeof +if (objectSetPrototypeOf) $({ target: 'Reflect', stat: true }, { + setPrototypeOf: function setPrototypeOf(target, proto) { + anObject(target); + aPossiblePrototype(proto); + try { + objectSetPrototypeOf(target, proto); + return true; + } catch (error) { + return false; + } + } +}); + +},{"../internals/a-possible-prototype":311,"../internals/an-object":315,"../internals/export":361,"../internals/object-set-prototype-of":424}],592:[function(require,module,exports){ +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var isObject = require('../internals/is-object'); +var has = require('../internals/has'); +var definePropertyModule = require('../internals/object-define-property'); +var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); + +// `Reflect.set` method +// https://tc39.github.io/ecma262/#sec-reflect.set +function set(target, propertyKey, V /* , receiver */) { + var receiver = arguments.length < 4 ? target : arguments[3]; + var ownDescriptor = getOwnPropertyDescriptorModule.f(anObject(target), propertyKey); + var existingDescriptor, prototype; + if (!ownDescriptor) { + if (isObject(prototype = getPrototypeOf(target))) { + return set(prototype, propertyKey, V, receiver); + } + ownDescriptor = createPropertyDescriptor(0); + } + if (has(ownDescriptor, 'value')) { + if (ownDescriptor.writable === false || !isObject(receiver)) return false; + if (existingDescriptor = getOwnPropertyDescriptorModule.f(receiver, propertyKey)) { + if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; + existingDescriptor.value = V; + definePropertyModule.f(receiver, propertyKey, existingDescriptor); + } else definePropertyModule.f(receiver, propertyKey, createPropertyDescriptor(0, V)); + return true; + } + return ownDescriptor.set === undefined ? false : (ownDescriptor.set.call(receiver, V), true); +} + +$({ target: 'Reflect', stat: true }, { + set: set +}); + +},{"../internals/an-object":315,"../internals/create-property-descriptor":351,"../internals/export":361,"../internals/has":378,"../internals/is-object":392,"../internals/object-define-property":415,"../internals/object-get-own-property-descriptor":416,"../internals/object-get-prototype-of":420}],593:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var global = require('../internals/global'); +var isForced = require('../internals/is-forced'); +var inheritIfRequired = require('../internals/inherit-if-required'); +var defineProperty = require('../internals/object-define-property').f; +var getOwnPropertyNames = require('../internals/object-get-own-property-names').f; +var isRegExp = require('../internals/is-regexp'); +var getFlags = require('../internals/regexp-flags'); +var redefine = require('../internals/redefine'); +var fails = require('../internals/fails'); +var setSpecies = require('../internals/set-species'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var MATCH = wellKnownSymbol('match'); +var NativeRegExp = global.RegExp; +var RegExpPrototype = NativeRegExp.prototype; +var re1 = /a/g; +var re2 = /a/g; + +// "new" should create a new object, old webkit bug +var CORRECT_NEW = new NativeRegExp(re1) !== re1; + +var FORCED = DESCRIPTORS && isForced('RegExp', (!CORRECT_NEW || fails(function () { + re2[MATCH] = false; + // RegExp constructor can alter flags and IsRegExp works correct with @@match + return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i'; +}))); + +// `RegExp` constructor +// https://tc39.github.io/ecma262/#sec-regexp-constructor +if (FORCED) { + var RegExpWrapper = function RegExp(pattern, flags) { + var thisIsRegExp = this instanceof RegExpWrapper; + var patternIsRegExp = isRegExp(pattern); + var flagsAreUndefined = flags === undefined; + return !thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined ? pattern + : inheritIfRequired(CORRECT_NEW + ? new NativeRegExp(patternIsRegExp && !flagsAreUndefined ? pattern.source : pattern, flags) + : NativeRegExp((patternIsRegExp = pattern instanceof RegExpWrapper) + ? pattern.source + : pattern, patternIsRegExp && flagsAreUndefined ? getFlags.call(pattern) : flags) + , thisIsRegExp ? this : RegExpPrototype, RegExpWrapper); + }; + var proxy = function (key) { + key in RegExpWrapper || defineProperty(RegExpWrapper, key, { + configurable: true, + get: function () { return NativeRegExp[key]; }, + set: function (it) { NativeRegExp[key] = it; } + }); + }; + var keys = getOwnPropertyNames(NativeRegExp); + var index = 0; + while (keys.length > index) proxy(keys[index++]); + RegExpPrototype.constructor = RegExpWrapper; + RegExpWrapper.prototype = RegExpPrototype; + redefine(global, 'RegExp', RegExpWrapper); +} + +// https://tc39.github.io/ecma262/#sec-get-regexp-@@species +setSpecies('RegExp'); + +},{"../internals/descriptors":357,"../internals/fails":362,"../internals/global":377,"../internals/inherit-if-required":384,"../internals/is-forced":389,"../internals/is-regexp":394,"../internals/object-define-property":415,"../internals/object-get-own-property-names":418,"../internals/redefine":435,"../internals/regexp-flags":439,"../internals/set-species":444,"../internals/well-known-symbol":473}],594:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var exec = require('../internals/regexp-exec'); + +$({ target: 'RegExp', proto: true, forced: /./.exec !== exec }, { + exec: exec +}); + +},{"../internals/export":361,"../internals/regexp-exec":438}],595:[function(require,module,exports){ +var DESCRIPTORS = require('../internals/descriptors'); +var objectDefinePropertyModule = require('../internals/object-define-property'); +var regExpFlags = require('../internals/regexp-flags'); + +// `RegExp.prototype.flags` getter +// https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags +if (DESCRIPTORS && /./g.flags != 'g') { + objectDefinePropertyModule.f(RegExp.prototype, 'flags', { + configurable: true, + get: regExpFlags + }); +} + +},{"../internals/descriptors":357,"../internals/object-define-property":415,"../internals/regexp-flags":439}],596:[function(require,module,exports){ +'use strict'; +var redefine = require('../internals/redefine'); +var anObject = require('../internals/an-object'); +var fails = require('../internals/fails'); +var flags = require('../internals/regexp-flags'); + +var TO_STRING = 'toString'; +var RegExpPrototype = RegExp.prototype; +var nativeToString = RegExpPrototype[TO_STRING]; + +var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; }); +// FF44- RegExp#toString has a wrong name +var INCORRECT_NAME = nativeToString.name != TO_STRING; + +// `RegExp.prototype.toString` method +// https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring +if (NOT_GENERIC || INCORRECT_NAME) { + redefine(RegExp.prototype, TO_STRING, function toString() { + var R = anObject(this); + var p = String(R.source); + var rf = R.flags; + var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf); + return '/' + p + '/' + f; + }, { unsafe: true }); +} + +},{"../internals/an-object":315,"../internals/fails":362,"../internals/redefine":435,"../internals/regexp-flags":439}],597:[function(require,module,exports){ +'use strict'; +var collection = require('../internals/collection'); +var collectionStrong = require('../internals/collection-strong'); + +// `Set` constructor +// https://tc39.github.io/ecma262/#sec-set-objects +module.exports = collection('Set', function (get) { + return function Set() { return get(this, arguments.length ? arguments[0] : undefined); }; +}, collectionStrong); + +},{"../internals/collection":341,"../internals/collection-strong":339}],598:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.anchor` method +// https://tc39.github.io/ecma262/#sec-string.prototype.anchor +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('anchor') }, { + anchor: function anchor(name) { + return createHTML(this, 'a', 'name', name); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],599:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.big` method +// https://tc39.github.io/ecma262/#sec-string.prototype.big +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('big') }, { + big: function big() { + return createHTML(this, 'big', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],600:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.blink` method +// https://tc39.github.io/ecma262/#sec-string.prototype.blink +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('blink') }, { + blink: function blink() { + return createHTML(this, 'blink', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],601:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.bold` method +// https://tc39.github.io/ecma262/#sec-string.prototype.bold +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('bold') }, { + bold: function bold() { + return createHTML(this, 'b', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],602:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var codeAt = require('../internals/string-multibyte').codeAt; + +// `String.prototype.codePointAt` method +// https://tc39.github.io/ecma262/#sec-string.prototype.codepointat +$({ target: 'String', proto: true }, { + codePointAt: function codePointAt(pos) { + return codeAt(this, pos); + } +}); + +},{"../internals/export":361,"../internals/string-multibyte":451}],603:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var toLength = require('../internals/to-length'); +var notARegExp = require('../internals/not-a-regexp'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var correctIsRegExpLogic = require('../internals/correct-is-regexp-logic'); + +var nativeEndsWith = ''.endsWith; +var min = Math.min; + +// `String.prototype.endsWith` method +// https://tc39.github.io/ecma262/#sec-string.prototype.endswith +$({ target: 'String', proto: true, forced: !correctIsRegExpLogic('endsWith') }, { + endsWith: function endsWith(searchString /* , endPosition = @length */) { + var that = String(requireObjectCoercible(this)); + notARegExp(searchString); + var endPosition = arguments.length > 1 ? arguments[1] : undefined; + var len = toLength(that.length); + var end = endPosition === undefined ? len : min(toLength(endPosition), len); + var search = String(searchString); + return nativeEndsWith + ? nativeEndsWith.call(that, search, end) + : that.slice(end - search.length, end) === search; + } +}); + +},{"../internals/correct-is-regexp-logic":344,"../internals/export":361,"../internals/not-a-regexp":410,"../internals/require-object-coercible":440,"../internals/to-length":461}],604:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.fixed` method +// https://tc39.github.io/ecma262/#sec-string.prototype.fixed +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('fixed') }, { + fixed: function fixed() { + return createHTML(this, 'tt', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],605:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.fontcolor` method +// https://tc39.github.io/ecma262/#sec-string.prototype.fontcolor +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('fontcolor') }, { + fontcolor: function fontcolor(color) { + return createHTML(this, 'font', 'color', color); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],606:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.fontsize` method +// https://tc39.github.io/ecma262/#sec-string.prototype.fontsize +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('fontsize') }, { + fontsize: function fontsize(size) { + return createHTML(this, 'font', 'size', size); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],607:[function(require,module,exports){ +var $ = require('../internals/export'); +var toAbsoluteIndex = require('../internals/to-absolute-index'); + +var fromCharCode = String.fromCharCode; +var nativeFromCodePoint = String.fromCodePoint; + +// length should be 1, old FF problem +var INCORRECT_LENGTH = !!nativeFromCodePoint && nativeFromCodePoint.length != 1; + +// `String.fromCodePoint` method +// https://tc39.github.io/ecma262/#sec-string.fromcodepoint +$({ target: 'String', stat: true, forced: INCORRECT_LENGTH }, { + fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars + var elements = []; + var length = arguments.length; + var i = 0; + var code; + while (length > i) { + code = +arguments[i++]; + if (toAbsoluteIndex(code, 0x10FFFF) !== code) throw RangeError(code + ' is not a valid code point'); + elements.push(code < 0x10000 + ? fromCharCode(code) + : fromCharCode(((code -= 0x10000) >> 10) + 0xD800, code % 0x400 + 0xDC00) + ); + } return elements.join(''); + } +}); + +},{"../internals/export":361,"../internals/to-absolute-index":457}],608:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var notARegExp = require('../internals/not-a-regexp'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var correctIsRegExpLogic = require('../internals/correct-is-regexp-logic'); + +// `String.prototype.includes` method +// https://tc39.github.io/ecma262/#sec-string.prototype.includes +$({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, { + includes: function includes(searchString /* , position = 0 */) { + return !!~String(requireObjectCoercible(this)) + .indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/correct-is-regexp-logic":344,"../internals/export":361,"../internals/not-a-regexp":410,"../internals/require-object-coercible":440}],609:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.italics` method +// https://tc39.github.io/ecma262/#sec-string.prototype.italics +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('italics') }, { + italics: function italics() { + return createHTML(this, 'i', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],610:[function(require,module,exports){ +'use strict'; +var charAt = require('../internals/string-multibyte').charAt; +var InternalStateModule = require('../internals/internal-state'); +var defineIterator = require('../internals/define-iterator'); + +var STRING_ITERATOR = 'String Iterator'; +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); + +// `String.prototype[@@iterator]` method +// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator +defineIterator(String, 'String', function (iterated) { + setInternalState(this, { + type: STRING_ITERATOR, + string: String(iterated), + index: 0 + }); +// `%StringIteratorPrototype%.next` method +// https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next +}, function next() { + var state = getInternalState(this); + var string = state.string; + var index = state.index; + var point; + if (index >= string.length) return { value: undefined, done: true }; + point = charAt(string, index); + state.index += point.length; + return { value: point, done: false }; +}); + +},{"../internals/define-iterator":355,"../internals/internal-state":386,"../internals/string-multibyte":451}],611:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.link` method +// https://tc39.github.io/ecma262/#sec-string.prototype.link +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('link') }, { + link: function link(url) { + return createHTML(this, 'a', 'href', url); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],612:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createIteratorConstructor = require('../internals/create-iterator-constructor'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var toLength = require('../internals/to-length'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var classof = require('../internals/classof'); +var isRegExp = require('../internals/is-regexp'); +var getRegExpFlags = require('../internals/regexp-flags'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var fails = require('../internals/fails'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var speciesConstructor = require('../internals/species-constructor'); +var advanceStringIndex = require('../internals/advance-string-index'); +var InternalStateModule = require('../internals/internal-state'); +var IS_PURE = require('../internals/is-pure'); + +var MATCH_ALL = wellKnownSymbol('matchAll'); +var REGEXP_STRING = 'RegExp String'; +var REGEXP_STRING_ITERATOR = REGEXP_STRING + ' Iterator'; +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(REGEXP_STRING_ITERATOR); +var RegExpPrototype = RegExp.prototype; +var regExpBuiltinExec = RegExpPrototype.exec; +var nativeMatchAll = ''.matchAll; + +var WORKS_WITH_NON_GLOBAL_REGEX = !!nativeMatchAll && !fails(function () { + 'a'.matchAll(/./); +}); + +var regExpExec = function (R, S) { + var exec = R.exec; + var result; + if (typeof exec == 'function') { + result = exec.call(R, S); + if (typeof result != 'object') throw TypeError('Incorrect exec result'); + return result; + } return regExpBuiltinExec.call(R, S); +}; + +// eslint-disable-next-line max-len +var $RegExpStringIterator = createIteratorConstructor(function RegExpStringIterator(regexp, string, global, fullUnicode) { + setInternalState(this, { + type: REGEXP_STRING_ITERATOR, + regexp: regexp, + string: string, + global: global, + unicode: fullUnicode, + done: false + }); +}, REGEXP_STRING, function next() { + var state = getInternalState(this); + if (state.done) return { value: undefined, done: true }; + var R = state.regexp; + var S = state.string; + var match = regExpExec(R, S); + if (match === null) return { value: undefined, done: state.done = true }; + if (state.global) { + if (String(match[0]) == '') R.lastIndex = advanceStringIndex(S, toLength(R.lastIndex), state.unicode); + return { value: match, done: false }; + } + state.done = true; + return { value: match, done: false }; +}); + +var $matchAll = function (string) { + var R = anObject(this); + var S = String(string); + var C, flagsValue, flags, matcher, global, fullUnicode; + C = speciesConstructor(R, RegExp); + flagsValue = R.flags; + if (flagsValue === undefined && R instanceof RegExp && !('flags' in RegExpPrototype)) { + flagsValue = getRegExpFlags.call(R); + } + flags = flagsValue === undefined ? '' : String(flagsValue); + matcher = new C(C === RegExp ? R.source : R, flags); + global = !!~flags.indexOf('g'); + fullUnicode = !!~flags.indexOf('u'); + matcher.lastIndex = toLength(R.lastIndex); + return new $RegExpStringIterator(matcher, S, global, fullUnicode); +}; + +// `String.prototype.matchAll` method +// https://github.com/tc39/proposal-string-matchall +$({ target: 'String', proto: true, forced: WORKS_WITH_NON_GLOBAL_REGEX }, { + matchAll: function matchAll(regexp) { + var O = requireObjectCoercible(this); + var flags, S, matcher, rx; + if (regexp != null) { + if (isRegExp(regexp)) { + flags = String(requireObjectCoercible('flags' in RegExpPrototype + ? regexp.flags + : getRegExpFlags.call(regexp) + )); + if (!~flags.indexOf('g')) throw TypeError('`.matchAll` does not allow non-global regexes'); + } + if (WORKS_WITH_NON_GLOBAL_REGEX) return nativeMatchAll.apply(O, arguments); + matcher = regexp[MATCH_ALL]; + if (matcher === undefined && IS_PURE && classof(regexp) == 'RegExp') matcher = $matchAll; + if (matcher != null) return aFunction(matcher).call(regexp, O); + } else if (WORKS_WITH_NON_GLOBAL_REGEX) return nativeMatchAll.apply(O, arguments); + S = String(O); + rx = new RegExp(regexp, 'g'); + return IS_PURE ? $matchAll.call(rx, S) : rx[MATCH_ALL](S); + } +}); + +IS_PURE || MATCH_ALL in RegExpPrototype || createNonEnumerableProperty(RegExpPrototype, MATCH_ALL, $matchAll); + +},{"../internals/a-function":310,"../internals/advance-string-index":313,"../internals/an-object":315,"../internals/classof":334,"../internals/create-iterator-constructor":348,"../internals/create-non-enumerable-property":350,"../internals/export":361,"../internals/fails":362,"../internals/internal-state":386,"../internals/is-pure":393,"../internals/is-regexp":394,"../internals/regexp-flags":439,"../internals/require-object-coercible":440,"../internals/species-constructor":450,"../internals/to-length":461,"../internals/well-known-symbol":473}],613:[function(require,module,exports){ +'use strict'; +var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic'); +var anObject = require('../internals/an-object'); +var toLength = require('../internals/to-length'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var advanceStringIndex = require('../internals/advance-string-index'); +var regExpExec = require('../internals/regexp-exec-abstract'); + +// @@match logic +fixRegExpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) { + return [ + // `String.prototype.match` method + // https://tc39.github.io/ecma262/#sec-string.prototype.match + function match(regexp) { + var O = requireObjectCoercible(this); + var matcher = regexp == undefined ? undefined : regexp[MATCH]; + return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); + }, + // `RegExp.prototype[@@match]` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match + function (regexp) { + var res = maybeCallNative(nativeMatch, regexp, this); + if (res.done) return res.value; + + var rx = anObject(regexp); + var S = String(this); + + if (!rx.global) return regExpExec(rx, S); + + var fullUnicode = rx.unicode; + rx.lastIndex = 0; + var A = []; + var n = 0; + var result; + while ((result = regExpExec(rx, S)) !== null) { + var matchStr = String(result[0]); + A[n] = matchStr; + if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); + n++; + } + return n === 0 ? null : A; + } + ]; +}); + +},{"../internals/advance-string-index":313,"../internals/an-object":315,"../internals/fix-regexp-well-known-symbol-logic":363,"../internals/regexp-exec-abstract":437,"../internals/require-object-coercible":440,"../internals/to-length":461}],614:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $padEnd = require('../internals/string-pad').end; +var WEBKIT_BUG = require('../internals/webkit-string-pad-bug'); + +// `String.prototype.padEnd` method +// https://tc39.github.io/ecma262/#sec-string.prototype.padend +$({ target: 'String', proto: true, forced: WEBKIT_BUG }, { + padEnd: function padEnd(maxLength /* , fillString = ' ' */) { + return $padEnd(this, maxLength, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/export":361,"../internals/string-pad":452,"../internals/webkit-string-pad-bug":472}],615:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $padStart = require('../internals/string-pad').start; +var WEBKIT_BUG = require('../internals/webkit-string-pad-bug'); + +// `String.prototype.padStart` method +// https://tc39.github.io/ecma262/#sec-string.prototype.padstart +$({ target: 'String', proto: true, forced: WEBKIT_BUG }, { + padStart: function padStart(maxLength /* , fillString = ' ' */) { + return $padStart(this, maxLength, arguments.length > 1 ? arguments[1] : undefined); + } +}); + +},{"../internals/export":361,"../internals/string-pad":452,"../internals/webkit-string-pad-bug":472}],616:[function(require,module,exports){ +var $ = require('../internals/export'); +var toIndexedObject = require('../internals/to-indexed-object'); +var toLength = require('../internals/to-length'); + +// `String.raw` method +// https://tc39.github.io/ecma262/#sec-string.raw +$({ target: 'String', stat: true }, { + raw: function raw(template) { + var rawTemplate = toIndexedObject(template.raw); + var literalSegments = toLength(rawTemplate.length); + var argumentsLength = arguments.length; + var elements = []; + var i = 0; + while (literalSegments > i) { + elements.push(String(rawTemplate[i++])); + if (i < argumentsLength) elements.push(String(arguments[i])); + } return elements.join(''); + } +}); + +},{"../internals/export":361,"../internals/to-indexed-object":459,"../internals/to-length":461}],617:[function(require,module,exports){ +var $ = require('../internals/export'); +var repeat = require('../internals/string-repeat'); + +// `String.prototype.repeat` method +// https://tc39.github.io/ecma262/#sec-string.prototype.repeat +$({ target: 'String', proto: true }, { + repeat: repeat +}); + +},{"../internals/export":361,"../internals/string-repeat":453}],618:[function(require,module,exports){ +'use strict'; +var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic'); +var anObject = require('../internals/an-object'); +var toObject = require('../internals/to-object'); +var toLength = require('../internals/to-length'); +var toInteger = require('../internals/to-integer'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var advanceStringIndex = require('../internals/advance-string-index'); +var regExpExec = require('../internals/regexp-exec-abstract'); + +var max = Math.max; +var min = Math.min; +var floor = Math.floor; +var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g; +var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g; + +var maybeToString = function (it) { + return it === undefined ? it : String(it); +}; + +// @@replace logic +fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative) { + return [ + // `String.prototype.replace` method + // https://tc39.github.io/ecma262/#sec-string.prototype.replace + function replace(searchValue, replaceValue) { + var O = requireObjectCoercible(this); + var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; + return replacer !== undefined + ? replacer.call(searchValue, O, replaceValue) + : nativeReplace.call(String(O), searchValue, replaceValue); + }, + // `RegExp.prototype[@@replace]` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace + function (regexp, replaceValue) { + var res = maybeCallNative(nativeReplace, regexp, this, replaceValue); + if (res.done) return res.value; + + var rx = anObject(regexp); + var S = String(this); + + var functionalReplace = typeof replaceValue === 'function'; + if (!functionalReplace) replaceValue = String(replaceValue); + + var global = rx.global; + if (global) { + var fullUnicode = rx.unicode; + rx.lastIndex = 0; + } + var results = []; + while (true) { + var result = regExpExec(rx, S); + if (result === null) break; + + results.push(result); + if (!global) break; + + var matchStr = String(result[0]); + if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); + } + + var accumulatedResult = ''; + var nextSourcePosition = 0; + for (var i = 0; i < results.length; i++) { + result = results[i]; + + var matched = String(result[0]); + var position = max(min(toInteger(result.index), S.length), 0); + var captures = []; + // NOTE: This is equivalent to + // captures = result.slice(1).map(maybeToString) + // but for some reason `nativeSlice.call(result, 1, result.length)` (called in + // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and + // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. + for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); + var namedCaptures = result.groups; + if (functionalReplace) { + var replacerArgs = [matched].concat(captures, position, S); + if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); + var replacement = String(replaceValue.apply(undefined, replacerArgs)); + } else { + replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); + } + if (position >= nextSourcePosition) { + accumulatedResult += S.slice(nextSourcePosition, position) + replacement; + nextSourcePosition = position + matched.length; + } + } + return accumulatedResult + S.slice(nextSourcePosition); + } + ]; + + // https://tc39.github.io/ecma262/#sec-getsubstitution + function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { + var tailPos = position + matched.length; + var m = captures.length; + var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; + if (namedCaptures !== undefined) { + namedCaptures = toObject(namedCaptures); + symbols = SUBSTITUTION_SYMBOLS; + } + return nativeReplace.call(replacement, symbols, function (match, ch) { + var capture; + switch (ch.charAt(0)) { + case '$': return '$'; + case '&': return matched; + case '`': return str.slice(0, position); + case "'": return str.slice(tailPos); + case '<': + capture = namedCaptures[ch.slice(1, -1)]; + break; + default: // \d\d? + var n = +ch; + if (n === 0) return match; + if (n > m) { + var f = floor(n / 10); + if (f === 0) return match; + if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); + return match; + } + capture = captures[n - 1]; + } + return capture === undefined ? '' : capture; + }); + } +}); + +},{"../internals/advance-string-index":313,"../internals/an-object":315,"../internals/fix-regexp-well-known-symbol-logic":363,"../internals/regexp-exec-abstract":437,"../internals/require-object-coercible":440,"../internals/to-integer":460,"../internals/to-length":461,"../internals/to-object":462}],619:[function(require,module,exports){ +'use strict'; +var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic'); +var anObject = require('../internals/an-object'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var sameValue = require('../internals/same-value'); +var regExpExec = require('../internals/regexp-exec-abstract'); + +// @@search logic +fixRegExpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) { + return [ + // `String.prototype.search` method + // https://tc39.github.io/ecma262/#sec-string.prototype.search + function search(regexp) { + var O = requireObjectCoercible(this); + var searcher = regexp == undefined ? undefined : regexp[SEARCH]; + return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); + }, + // `RegExp.prototype[@@search]` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search + function (regexp) { + var res = maybeCallNative(nativeSearch, regexp, this); + if (res.done) return res.value; + + var rx = anObject(regexp); + var S = String(this); + + var previousLastIndex = rx.lastIndex; + if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0; + var result = regExpExec(rx, S); + if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex; + return result === null ? -1 : result.index; + } + ]; +}); + +},{"../internals/an-object":315,"../internals/fix-regexp-well-known-symbol-logic":363,"../internals/regexp-exec-abstract":437,"../internals/require-object-coercible":440,"../internals/same-value":442}],620:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.small` method +// https://tc39.github.io/ecma262/#sec-string.prototype.small +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('small') }, { + small: function small() { + return createHTML(this, 'small', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],621:[function(require,module,exports){ +'use strict'; +var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic'); +var isRegExp = require('../internals/is-regexp'); +var anObject = require('../internals/an-object'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var speciesConstructor = require('../internals/species-constructor'); +var advanceStringIndex = require('../internals/advance-string-index'); +var toLength = require('../internals/to-length'); +var callRegExpExec = require('../internals/regexp-exec-abstract'); +var regexpExec = require('../internals/regexp-exec'); +var fails = require('../internals/fails'); + +var arrayPush = [].push; +var min = Math.min; +var MAX_UINT32 = 0xFFFFFFFF; + +// babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError +var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); }); + +// @@split logic +fixRegExpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) { + var internalSplit; + if ( + 'abbc'.split(/(b)*/)[1] == 'c' || + 'test'.split(/(?:)/, -1).length != 4 || + 'ab'.split(/(?:ab)*/).length != 2 || + '.'.split(/(.?)(.?)/).length != 4 || + '.'.split(/()()/).length > 1 || + ''.split(/.?/).length + ) { + // based on es5-shim implementation, need to rework it + internalSplit = function (separator, limit) { + var string = String(requireObjectCoercible(this)); + var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; + if (lim === 0) return []; + if (separator === undefined) return [string]; + // If `separator` is not a regex, use native split + if (!isRegExp(separator)) { + return nativeSplit.call(string, separator, lim); + } + var output = []; + var flags = (separator.ignoreCase ? 'i' : '') + + (separator.multiline ? 'm' : '') + + (separator.unicode ? 'u' : '') + + (separator.sticky ? 'y' : ''); + var lastLastIndex = 0; + // Make `global` and avoid `lastIndex` issues by working with a copy + var separatorCopy = new RegExp(separator.source, flags + 'g'); + var match, lastIndex, lastLength; + while (match = regexpExec.call(separatorCopy, string)) { + lastIndex = separatorCopy.lastIndex; + if (lastIndex > lastLastIndex) { + output.push(string.slice(lastLastIndex, match.index)); + if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1)); + lastLength = match[0].length; + lastLastIndex = lastIndex; + if (output.length >= lim) break; + } + if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop + } + if (lastLastIndex === string.length) { + if (lastLength || !separatorCopy.test('')) output.push(''); + } else output.push(string.slice(lastLastIndex)); + return output.length > lim ? output.slice(0, lim) : output; + }; + // Chakra, V8 + } else if ('0'.split(undefined, 0).length) { + internalSplit = function (separator, limit) { + return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit); + }; + } else internalSplit = nativeSplit; + + return [ + // `String.prototype.split` method + // https://tc39.github.io/ecma262/#sec-string.prototype.split + function split(separator, limit) { + var O = requireObjectCoercible(this); + var splitter = separator == undefined ? undefined : separator[SPLIT]; + return splitter !== undefined + ? splitter.call(separator, O, limit) + : internalSplit.call(String(O), separator, limit); + }, + // `RegExp.prototype[@@split]` method + // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split + // + // NOTE: This cannot be properly polyfilled in engines that don't support + // the 'y' flag. + function (regexp, limit) { + var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit); + if (res.done) return res.value; + + var rx = anObject(regexp); + var S = String(this); + var C = speciesConstructor(rx, RegExp); + + var unicodeMatching = rx.unicode; + var flags = (rx.ignoreCase ? 'i' : '') + + (rx.multiline ? 'm' : '') + + (rx.unicode ? 'u' : '') + + (SUPPORTS_Y ? 'y' : 'g'); + + // ^(? + rx + ) is needed, in combination with some S slicing, to + // simulate the 'y' flag. + var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); + var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; + if (lim === 0) return []; + if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : []; + var p = 0; + var q = 0; + var A = []; + while (q < S.length) { + splitter.lastIndex = SUPPORTS_Y ? q : 0; + var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q)); + var e; + if ( + z === null || + (e = min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p + ) { + q = advanceStringIndex(S, q, unicodeMatching); + } else { + A.push(S.slice(p, q)); + if (A.length === lim) return A; + for (var i = 1; i <= z.length - 1; i++) { + A.push(z[i]); + if (A.length === lim) return A; + } + q = p = e; + } + } + A.push(S.slice(p)); + return A; + } + ]; +}, !SUPPORTS_Y); + +},{"../internals/advance-string-index":313,"../internals/an-object":315,"../internals/fails":362,"../internals/fix-regexp-well-known-symbol-logic":363,"../internals/is-regexp":394,"../internals/regexp-exec":438,"../internals/regexp-exec-abstract":437,"../internals/require-object-coercible":440,"../internals/species-constructor":450,"../internals/to-length":461}],622:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var toLength = require('../internals/to-length'); +var notARegExp = require('../internals/not-a-regexp'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var correctIsRegExpLogic = require('../internals/correct-is-regexp-logic'); + +var nativeStartsWith = ''.startsWith; +var min = Math.min; + +// `String.prototype.startsWith` method +// https://tc39.github.io/ecma262/#sec-string.prototype.startswith +$({ target: 'String', proto: true, forced: !correctIsRegExpLogic('startsWith') }, { + startsWith: function startsWith(searchString /* , position = 0 */) { + var that = String(requireObjectCoercible(this)); + notARegExp(searchString); + var index = toLength(min(arguments.length > 1 ? arguments[1] : undefined, that.length)); + var search = String(searchString); + return nativeStartsWith + ? nativeStartsWith.call(that, search, index) + : that.slice(index, index + search.length) === search; + } +}); + +},{"../internals/correct-is-regexp-logic":344,"../internals/export":361,"../internals/not-a-regexp":410,"../internals/require-object-coercible":440,"../internals/to-length":461}],623:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.strike` method +// https://tc39.github.io/ecma262/#sec-string.prototype.strike +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('strike') }, { + strike: function strike() { + return createHTML(this, 'strike', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],624:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.sub` method +// https://tc39.github.io/ecma262/#sec-string.prototype.sub +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('sub') }, { + sub: function sub() { + return createHTML(this, 'sub', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],625:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createHTML = require('../internals/create-html'); +var forcedStringHTMLMethod = require('../internals/forced-string-html-method'); + +// `String.prototype.sup` method +// https://tc39.github.io/ecma262/#sec-string.prototype.sup +$({ target: 'String', proto: true, forced: forcedStringHTMLMethod('sup') }, { + sup: function sup() { + return createHTML(this, 'sup', '', ''); + } +}); + +},{"../internals/create-html":347,"../internals/export":361,"../internals/forced-string-html-method":366}],626:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $trimEnd = require('../internals/string-trim').end; +var forcedStringTrimMethod = require('../internals/forced-string-trim-method'); + +var FORCED = forcedStringTrimMethod('trimEnd'); + +var trimEnd = FORCED ? function trimEnd() { + return $trimEnd(this); +} : ''.trimEnd; + +// `String.prototype.{ trimEnd, trimRight }` methods +// https://github.com/tc39/ecmascript-string-left-right-trim +$({ target: 'String', proto: true, forced: FORCED }, { + trimEnd: trimEnd, + trimRight: trimEnd +}); + +},{"../internals/export":361,"../internals/forced-string-trim-method":367,"../internals/string-trim":454}],627:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $trimStart = require('../internals/string-trim').start; +var forcedStringTrimMethod = require('../internals/forced-string-trim-method'); + +var FORCED = forcedStringTrimMethod('trimStart'); + +var trimStart = FORCED ? function trimStart() { + return $trimStart(this); +} : ''.trimStart; + +// `String.prototype.{ trimStart, trimLeft }` methods +// https://github.com/tc39/ecmascript-string-left-right-trim +$({ target: 'String', proto: true, forced: FORCED }, { + trimStart: trimStart, + trimLeft: trimStart +}); + +},{"../internals/export":361,"../internals/forced-string-trim-method":367,"../internals/string-trim":454}],628:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var $trim = require('../internals/string-trim').trim; +var forcedStringTrimMethod = require('../internals/forced-string-trim-method'); + +// `String.prototype.trim` method +// https://tc39.github.io/ecma262/#sec-string.prototype.trim +$({ target: 'String', proto: true, forced: forcedStringTrimMethod('trim') }, { + trim: function trim() { + return $trim(this); + } +}); + +},{"../internals/export":361,"../internals/forced-string-trim-method":367,"../internals/string-trim":454}],629:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.asyncIterator` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.asynciterator +defineWellKnownSymbol('asyncIterator'); + +},{"../internals/define-well-known-symbol":356}],630:[function(require,module,exports){ +// `Symbol.prototype.description` getter +// https://tc39.github.io/ecma262/#sec-symbol.prototype.description +'use strict'; +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var global = require('../internals/global'); +var has = require('../internals/has'); +var isObject = require('../internals/is-object'); +var defineProperty = require('../internals/object-define-property').f; +var copyConstructorProperties = require('../internals/copy-constructor-properties'); + +var NativeSymbol = global.Symbol; + +if (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) || + // Safari 12 bug + NativeSymbol().description !== undefined +)) { + var EmptyStringDescriptionStore = {}; + // wrap Symbol constructor for correct work with undefined description + var SymbolWrapper = function Symbol() { + var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]); + var result = this instanceof SymbolWrapper + ? new NativeSymbol(description) + // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)' + : description === undefined ? NativeSymbol() : NativeSymbol(description); + if (description === '') EmptyStringDescriptionStore[result] = true; + return result; + }; + copyConstructorProperties(SymbolWrapper, NativeSymbol); + var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype; + symbolPrototype.constructor = SymbolWrapper; + + var symbolToString = symbolPrototype.toString; + var native = String(NativeSymbol('test')) == 'Symbol(test)'; + var regexp = /^Symbol\((.*)\)[^)]+$/; + defineProperty(symbolPrototype, 'description', { + configurable: true, + get: function description() { + var symbol = isObject(this) ? this.valueOf() : this; + var string = symbolToString.call(symbol); + if (has(EmptyStringDescriptionStore, symbol)) return ''; + var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1'); + return desc === '' ? undefined : desc; + } + }); + + $({ global: true, forced: true }, { + Symbol: SymbolWrapper + }); +} + +},{"../internals/copy-constructor-properties":343,"../internals/descriptors":357,"../internals/export":361,"../internals/global":377,"../internals/has":378,"../internals/is-object":392,"../internals/object-define-property":415}],631:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.hasInstance` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.hasinstance +defineWellKnownSymbol('hasInstance'); + +},{"../internals/define-well-known-symbol":356}],632:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.isConcatSpreadable` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.isconcatspreadable +defineWellKnownSymbol('isConcatSpreadable'); + +},{"../internals/define-well-known-symbol":356}],633:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.iterator` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.iterator +defineWellKnownSymbol('iterator'); + +},{"../internals/define-well-known-symbol":356}],634:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var global = require('../internals/global'); +var getBuiltIn = require('../internals/get-built-in'); +var IS_PURE = require('../internals/is-pure'); +var DESCRIPTORS = require('../internals/descriptors'); +var NATIVE_SYMBOL = require('../internals/native-symbol'); +var fails = require('../internals/fails'); +var has = require('../internals/has'); +var isArray = require('../internals/is-array'); +var isObject = require('../internals/is-object'); +var anObject = require('../internals/an-object'); +var toObject = require('../internals/to-object'); +var toIndexedObject = require('../internals/to-indexed-object'); +var toPrimitive = require('../internals/to-primitive'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); +var nativeObjectCreate = require('../internals/object-create'); +var objectKeys = require('../internals/object-keys'); +var getOwnPropertyNamesModule = require('../internals/object-get-own-property-names'); +var getOwnPropertyNamesExternal = require('../internals/object-get-own-property-names-external'); +var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols'); +var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor'); +var definePropertyModule = require('../internals/object-define-property'); +var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefine = require('../internals/redefine'); +var shared = require('../internals/shared'); +var sharedKey = require('../internals/shared-key'); +var hiddenKeys = require('../internals/hidden-keys'); +var uid = require('../internals/uid'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var wrappedWellKnownSymbolModule = require('../internals/wrapped-well-known-symbol'); +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); +var setToStringTag = require('../internals/set-to-string-tag'); +var InternalStateModule = require('../internals/internal-state'); +var $forEach = require('../internals/array-iteration').forEach; + +var HIDDEN = sharedKey('hidden'); +var SYMBOL = 'Symbol'; +var PROTOTYPE = 'prototype'; +var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(SYMBOL); +var ObjectPrototype = Object[PROTOTYPE]; +var $Symbol = global.Symbol; +var $stringify = getBuiltIn('JSON', 'stringify'); +var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; +var nativeDefineProperty = definePropertyModule.f; +var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f; +var nativePropertyIsEnumerable = propertyIsEnumerableModule.f; +var AllSymbols = shared('symbols'); +var ObjectPrototypeSymbols = shared('op-symbols'); +var StringToSymbolRegistry = shared('string-to-symbol-registry'); +var SymbolToStringRegistry = shared('symbol-to-string-registry'); +var WellKnownSymbolsStore = shared('wks'); +var QObject = global.QObject; +// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 +var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + +// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 +var setSymbolDescriptor = DESCRIPTORS && fails(function () { + return nativeObjectCreate(nativeDefineProperty({}, 'a', { + get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; } + })).a != 7; +}) ? function (O, P, Attributes) { + var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P); + if (ObjectPrototypeDescriptor) delete ObjectPrototype[P]; + nativeDefineProperty(O, P, Attributes); + if (ObjectPrototypeDescriptor && O !== ObjectPrototype) { + nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor); + } +} : nativeDefineProperty; + +var wrap = function (tag, description) { + var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]); + setInternalState(symbol, { + type: SYMBOL, + tag: tag, + description: description + }); + if (!DESCRIPTORS) symbol.description = description; + return symbol; +}; + +var isSymbol = NATIVE_SYMBOL && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; +} : function (it) { + return Object(it) instanceof $Symbol; +}; + +var $defineProperty = function defineProperty(O, P, Attributes) { + if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes); + anObject(O); + var key = toPrimitive(P, true); + anObject(Attributes); + if (has(AllSymbols, key)) { + if (!Attributes.enumerable) { + if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {})); + O[HIDDEN][key] = true; + } else { + if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false; + Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) }); + } return setSymbolDescriptor(O, key, Attributes); + } return nativeDefineProperty(O, key, Attributes); +}; + +var $defineProperties = function defineProperties(O, Properties) { + anObject(O); + var properties = toIndexedObject(Properties); + var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties)); + $forEach(keys, function (key) { + if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]); + }); + return O; +}; + +var $create = function create(O, Properties) { + return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties); +}; + +var $propertyIsEnumerable = function propertyIsEnumerable(V) { + var P = toPrimitive(V, true); + var enumerable = nativePropertyIsEnumerable.call(this, P); + if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false; + return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true; +}; + +var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) { + var it = toIndexedObject(O); + var key = toPrimitive(P, true); + if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return; + var descriptor = nativeGetOwnPropertyDescriptor(it, key); + if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) { + descriptor.enumerable = true; + } + return descriptor; +}; + +var $getOwnPropertyNames = function getOwnPropertyNames(O) { + var names = nativeGetOwnPropertyNames(toIndexedObject(O)); + var result = []; + $forEach(names, function (key) { + if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key); + }); + return result; +}; + +var $getOwnPropertySymbols = function getOwnPropertySymbols(O) { + var IS_OBJECT_PROTOTYPE = O === ObjectPrototype; + var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O)); + var result = []; + $forEach(names, function (key) { + if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) { + result.push(AllSymbols[key]); + } + }); + return result; +}; + +// `Symbol` constructor +// https://tc39.github.io/ecma262/#sec-symbol-constructor +if (!NATIVE_SYMBOL) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor'); + var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]); + var tag = uid(description); + var setter = function (value) { + if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value); + if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value)); + }; + if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter }); + return wrap(tag, description); + }; + + redefine($Symbol[PROTOTYPE], 'toString', function toString() { + return getInternalState(this).tag; + }); + + propertyIsEnumerableModule.f = $propertyIsEnumerable; + definePropertyModule.f = $defineProperty; + getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor; + getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames; + getOwnPropertySymbolsModule.f = $getOwnPropertySymbols; + + if (DESCRIPTORS) { + // https://github.com/tc39/proposal-Symbol-description + nativeDefineProperty($Symbol[PROTOTYPE], 'description', { + configurable: true, + get: function description() { + return getInternalState(this).description; + } + }); + if (!IS_PURE) { + redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true }); + } + } + + wrappedWellKnownSymbolModule.f = function (name) { + return wrap(wellKnownSymbol(name), name); + }; +} + +$({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, { + Symbol: $Symbol +}); + +$forEach(objectKeys(WellKnownSymbolsStore), function (name) { + defineWellKnownSymbol(name); +}); + +$({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, { + // `Symbol.for` method + // https://tc39.github.io/ecma262/#sec-symbol.for + 'for': function (key) { + var string = String(key); + if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string]; + var symbol = $Symbol(string); + StringToSymbolRegistry[string] = symbol; + SymbolToStringRegistry[symbol] = string; + return symbol; + }, + // `Symbol.keyFor` method + // https://tc39.github.io/ecma262/#sec-symbol.keyfor + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol'); + if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym]; + }, + useSetter: function () { USE_SETTER = true; }, + useSimple: function () { USE_SETTER = false; } +}); + +$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS }, { + // `Object.create` method + // https://tc39.github.io/ecma262/#sec-object.create + create: $create, + // `Object.defineProperty` method + // https://tc39.github.io/ecma262/#sec-object.defineproperty + defineProperty: $defineProperty, + // `Object.defineProperties` method + // https://tc39.github.io/ecma262/#sec-object.defineproperties + defineProperties: $defineProperties, + // `Object.getOwnPropertyDescriptor` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors + getOwnPropertyDescriptor: $getOwnPropertyDescriptor +}); + +$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, { + // `Object.getOwnPropertyNames` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertynames + getOwnPropertyNames: $getOwnPropertyNames, + // `Object.getOwnPropertySymbols` method + // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols + getOwnPropertySymbols: $getOwnPropertySymbols +}); + +// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives +// https://bugs.chromium.org/p/v8/issues/detail?id=3443 +$({ target: 'Object', stat: true, forced: fails(function () { getOwnPropertySymbolsModule.f(1); }) }, { + getOwnPropertySymbols: function getOwnPropertySymbols(it) { + return getOwnPropertySymbolsModule.f(toObject(it)); + } +}); + +// `JSON.stringify` method behavior with symbols +// https://tc39.github.io/ecma262/#sec-json.stringify +if ($stringify) { + var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () { + var symbol = $Symbol(); + // MS Edge converts symbol values to JSON as {} + return $stringify([symbol]) != '[null]' + // WebKit converts symbol values to JSON as null + || $stringify({ a: symbol }) != '{}' + // V8 throws on boxed symbols + || $stringify(Object(symbol)) != '{}'; + }); + + $({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, { + // eslint-disable-next-line no-unused-vars + stringify: function stringify(it, replacer, space) { + var args = [it]; + var index = 1; + var $replacer; + while (arguments.length > index) args.push(arguments[index++]); + $replacer = replacer; + if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return $stringify.apply(null, args); + } + }); +} + +// `Symbol.prototype[@@toPrimitive]` method +// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive +if (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) { + createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); +} +// `Symbol.prototype[@@toStringTag]` property +// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag +setToStringTag($Symbol, SYMBOL); + +hiddenKeys[HIDDEN] = true; + +},{"../internals/an-object":315,"../internals/array-iteration":323,"../internals/create-non-enumerable-property":350,"../internals/create-property-descriptor":351,"../internals/define-well-known-symbol":356,"../internals/descriptors":357,"../internals/export":361,"../internals/fails":362,"../internals/get-built-in":372,"../internals/global":377,"../internals/has":378,"../internals/hidden-keys":379,"../internals/internal-state":386,"../internals/is-array":388,"../internals/is-object":392,"../internals/is-pure":393,"../internals/native-symbol":406,"../internals/object-create":413,"../internals/object-define-property":415,"../internals/object-get-own-property-descriptor":416,"../internals/object-get-own-property-names":418,"../internals/object-get-own-property-names-external":417,"../internals/object-get-own-property-symbols":419,"../internals/object-keys":422,"../internals/object-property-is-enumerable":423,"../internals/redefine":435,"../internals/set-to-string-tag":445,"../internals/shared":448,"../internals/shared-key":446,"../internals/to-indexed-object":459,"../internals/to-object":462,"../internals/to-primitive":465,"../internals/uid":469,"../internals/well-known-symbol":473,"../internals/wrapped-well-known-symbol":475}],635:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.matchAll` well-known symbol +defineWellKnownSymbol('matchAll'); + +},{"../internals/define-well-known-symbol":356}],636:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.match` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.match +defineWellKnownSymbol('match'); + +},{"../internals/define-well-known-symbol":356}],637:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.replace` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.replace +defineWellKnownSymbol('replace'); + +},{"../internals/define-well-known-symbol":356}],638:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.search` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.search +defineWellKnownSymbol('search'); + +},{"../internals/define-well-known-symbol":356}],639:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.species` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.species +defineWellKnownSymbol('species'); + +},{"../internals/define-well-known-symbol":356}],640:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.split` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.split +defineWellKnownSymbol('split'); + +},{"../internals/define-well-known-symbol":356}],641:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.toPrimitive` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.toprimitive +defineWellKnownSymbol('toPrimitive'); + +},{"../internals/define-well-known-symbol":356}],642:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.toStringTag` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.tostringtag +defineWellKnownSymbol('toStringTag'); + +},{"../internals/define-well-known-symbol":356}],643:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.unscopables` well-known symbol +// https://tc39.github.io/ecma262/#sec-symbol.unscopables +defineWellKnownSymbol('unscopables'); + +},{"../internals/define-well-known-symbol":356}],644:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $copyWithin = require('../internals/array-copy-within'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.copyWithin` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.copywithin +ArrayBufferViewCore.exportProto('copyWithin', function copyWithin(target, start /* , end */) { + return $copyWithin.call(aTypedArray(this), target, start, arguments.length > 2 ? arguments[2] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-copy-within":318}],645:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $every = require('../internals/array-iteration').every; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.every` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.every +ArrayBufferViewCore.exportProto('every', function every(callbackfn /* , thisArg */) { + return $every(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-iteration":323}],646:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $fill = require('../internals/array-fill'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.fill` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill +// eslint-disable-next-line no-unused-vars +ArrayBufferViewCore.exportProto('fill', function fill(value /* , start, end */) { + return $fill.apply(aTypedArray(this), arguments); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-fill":319}],647:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $filter = require('../internals/array-iteration').filter; +var speciesConstructor = require('../internals/species-constructor'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; +var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; + +// `%TypedArray%.prototype.filter` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.filter +ArrayBufferViewCore.exportProto('filter', function filter(callbackfn /* , thisArg */) { + var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + var C = speciesConstructor(this, this.constructor); + var index = 0; + var length = list.length; + var result = new (aTypedArrayConstructor(C))(length); + while (length > index) result[index] = list[index++]; + return result; +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-iteration":323,"../internals/species-constructor":450}],648:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $findIndex = require('../internals/array-iteration').findIndex; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.findIndex` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.findindex +ArrayBufferViewCore.exportProto('findIndex', function findIndex(predicate /* , thisArg */) { + return $findIndex(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-iteration":323}],649:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $find = require('../internals/array-iteration').find; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.find` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.find +ArrayBufferViewCore.exportProto('find', function find(predicate /* , thisArg */) { + return $find(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-iteration":323}],650:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Float32Array` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Float32', 4, function (init) { + return function Float32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"../internals/typed-array-constructor":466}],651:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Float64Array` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Float64', 8, function (init) { + return function Float64Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"../internals/typed-array-constructor":466}],652:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $forEach = require('../internals/array-iteration').forEach; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.forEach` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.foreach +ArrayBufferViewCore.exportProto('forEach', function forEach(callbackfn /* , thisArg */) { + $forEach(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-iteration":323}],653:[function(require,module,exports){ +'use strict'; +var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = require('../internals/typed-arrays-constructors-requires-wrappers'); +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var typedArrayFrom = require('../internals/typed-array-from'); + +// `%TypedArray%.from` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.from +ArrayBufferViewCore.exportStatic('from', typedArrayFrom, TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS); + +},{"../internals/array-buffer-view-core":316,"../internals/typed-array-from":467,"../internals/typed-arrays-constructors-requires-wrappers":468}],654:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $includes = require('../internals/array-includes').includes; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.includes` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.includes +ArrayBufferViewCore.exportProto('includes', function includes(searchElement /* , fromIndex */) { + return $includes(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-includes":322}],655:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $indexOf = require('../internals/array-includes').indexOf; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.indexOf` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.indexof +ArrayBufferViewCore.exportProto('indexOf', function indexOf(searchElement /* , fromIndex */) { + return $indexOf(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-includes":322}],656:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Int16Array` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Int16', 2, function (init) { + return function Int16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"../internals/typed-array-constructor":466}],657:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Int32Array` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Int32', 4, function (init) { + return function Int32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"../internals/typed-array-constructor":466}],658:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Int8Array` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Int8', 1, function (init) { + return function Int8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"../internals/typed-array-constructor":466}],659:[function(require,module,exports){ +'use strict'; +var global = require('../internals/global'); +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var ArrayIterators = require('../modules/es.array.iterator'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var ITERATOR = wellKnownSymbol('iterator'); +var Uint8Array = global.Uint8Array; +var arrayValues = ArrayIterators.values; +var arrayKeys = ArrayIterators.keys; +var arrayEntries = ArrayIterators.entries; +var aTypedArray = ArrayBufferViewCore.aTypedArray; +var exportProto = ArrayBufferViewCore.exportProto; +var nativeTypedArrayIterator = Uint8Array && Uint8Array.prototype[ITERATOR]; + +var CORRECT_ITER_NAME = !!nativeTypedArrayIterator + && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined); + +var typedArrayValues = function values() { + return arrayValues.call(aTypedArray(this)); +}; + +// `%TypedArray%.prototype.entries` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.entries +exportProto('entries', function entries() { + return arrayEntries.call(aTypedArray(this)); +}); +// `%TypedArray%.prototype.keys` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.keys +exportProto('keys', function keys() { + return arrayKeys.call(aTypedArray(this)); +}); +// `%TypedArray%.prototype.values` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.values +exportProto('values', typedArrayValues, !CORRECT_ITER_NAME); +// `%TypedArray%.prototype[@@iterator]` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype-@@iterator +exportProto(ITERATOR, typedArrayValues, !CORRECT_ITER_NAME); + +},{"../internals/array-buffer-view-core":316,"../internals/global":377,"../internals/well-known-symbol":473,"../modules/es.array.iterator":493}],660:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; +var $join = [].join; + +// `%TypedArray%.prototype.join` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join +// eslint-disable-next-line no-unused-vars +ArrayBufferViewCore.exportProto('join', function join(separator) { + return $join.apply(aTypedArray(this), arguments); +}); + +},{"../internals/array-buffer-view-core":316}],661:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $lastIndexOf = require('../internals/array-last-index-of'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.lastIndexOf` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.lastindexof +// eslint-disable-next-line no-unused-vars +ArrayBufferViewCore.exportProto('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */) { + return $lastIndexOf.apply(aTypedArray(this), arguments); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-last-index-of":324}],662:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $map = require('../internals/array-iteration').map; +var speciesConstructor = require('../internals/species-constructor'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; +var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; + +// `%TypedArray%.prototype.map` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.map +ArrayBufferViewCore.exportProto('map', function map(mapfn /* , thisArg */) { + return $map(aTypedArray(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) { + return new (aTypedArrayConstructor(speciesConstructor(O, O.constructor)))(length); + }); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-iteration":323,"../internals/species-constructor":450}],663:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = require('../internals/typed-arrays-constructors-requires-wrappers'); + +var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; + +// `%TypedArray%.of` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.of +ArrayBufferViewCore.exportStatic('of', function of(/* ...items */) { + var index = 0; + var length = arguments.length; + var result = new (aTypedArrayConstructor(this))(length); + while (length > index) result[index] = arguments[index++]; + return result; +}, TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS); + +},{"../internals/array-buffer-view-core":316,"../internals/typed-arrays-constructors-requires-wrappers":468}],664:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $reduceRight = require('../internals/array-reduce').right; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.reduceRicht` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduceright +ArrayBufferViewCore.exportProto('reduceRight', function reduceRight(callbackfn /* , initialValue */) { + return $reduceRight(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-reduce":326}],665:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $reduce = require('../internals/array-reduce').left; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.reduce` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reduce +ArrayBufferViewCore.exportProto('reduce', function reduce(callbackfn /* , initialValue */) { + return $reduce(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-reduce":326}],666:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; +var floor = Math.floor; + +// `%TypedArray%.prototype.reverse` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.reverse +ArrayBufferViewCore.exportProto('reverse', function reverse() { + var that = this; + var length = aTypedArray(that).length; + var middle = floor(length / 2); + var index = 0; + var value; + while (index < middle) { + value = that[index]; + that[index++] = that[--length]; + that[length] = value; + } return that; +}); + +},{"../internals/array-buffer-view-core":316}],667:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var toLength = require('../internals/to-length'); +var toOffset = require('../internals/to-offset'); +var toObject = require('../internals/to-object'); +var fails = require('../internals/fails'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +var FORCED = fails(function () { + // eslint-disable-next-line no-undef + new Int8Array(1).set({}); +}); + +// `%TypedArray%.prototype.set` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.set +ArrayBufferViewCore.exportProto('set', function set(arrayLike /* , offset */) { + aTypedArray(this); + var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1); + var length = this.length; + var src = toObject(arrayLike); + var len = toLength(src.length); + var index = 0; + if (len + offset > length) throw RangeError('Wrong length'); + while (index < len) this[offset + index] = src[index++]; +}, FORCED); + +},{"../internals/array-buffer-view-core":316,"../internals/fails":362,"../internals/to-length":461,"../internals/to-object":462,"../internals/to-offset":463}],668:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var speciesConstructor = require('../internals/species-constructor'); +var fails = require('../internals/fails'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; +var aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor; +var $slice = [].slice; + +var FORCED = fails(function () { + // eslint-disable-next-line no-undef + new Int8Array(1).slice(); +}); + +// `%TypedArray%.prototype.slice` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice +ArrayBufferViewCore.exportProto('slice', function slice(start, end) { + var list = $slice.call(aTypedArray(this), start, end); + var C = speciesConstructor(this, this.constructor); + var index = 0; + var length = list.length; + var result = new (aTypedArrayConstructor(C))(length); + while (length > index) result[index] = list[index++]; + return result; +}, FORCED); + +},{"../internals/array-buffer-view-core":316,"../internals/fails":362,"../internals/species-constructor":450}],669:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var $some = require('../internals/array-iteration').some; + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.some` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some +ArrayBufferViewCore.exportProto('some', function some(callbackfn /* , thisArg */) { + return $some(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/array-iteration":323}],670:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; +var $sort = [].sort; + +// `%TypedArray%.prototype.sort` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.sort +ArrayBufferViewCore.exportProto('sort', function sort(comparefn) { + return $sort.call(aTypedArray(this), comparefn); +}); + +},{"../internals/array-buffer-view-core":316}],671:[function(require,module,exports){ +'use strict'; +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var toLength = require('../internals/to-length'); +var toAbsoluteIndex = require('../internals/to-absolute-index'); +var speciesConstructor = require('../internals/species-constructor'); + +var aTypedArray = ArrayBufferViewCore.aTypedArray; + +// `%TypedArray%.prototype.subarray` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.subarray +ArrayBufferViewCore.exportProto('subarray', function subarray(begin, end) { + var O = aTypedArray(this); + var length = O.length; + var beginIndex = toAbsoluteIndex(begin, length); + return new (speciesConstructor(O, O.constructor))( + O.buffer, + O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT, + toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex) + ); +}); + +},{"../internals/array-buffer-view-core":316,"../internals/species-constructor":450,"../internals/to-absolute-index":457,"../internals/to-length":461}],672:[function(require,module,exports){ +'use strict'; +var global = require('../internals/global'); +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var fails = require('../internals/fails'); + +var Int8Array = global.Int8Array; +var aTypedArray = ArrayBufferViewCore.aTypedArray; +var $toLocaleString = [].toLocaleString; +var $slice = [].slice; + +// iOS Safari 6.x fails here +var TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () { + $toLocaleString.call(new Int8Array(1)); +}); + +var FORCED = fails(function () { + return [1, 2].toLocaleString() != new Int8Array([1, 2]).toLocaleString(); +}) || !fails(function () { + Int8Array.prototype.toLocaleString.call([1, 2]); +}); + +// `%TypedArray%.prototype.toLocaleString` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring +ArrayBufferViewCore.exportProto('toLocaleString', function toLocaleString() { + return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments); +}, FORCED); + +},{"../internals/array-buffer-view-core":316,"../internals/fails":362,"../internals/global":377}],673:[function(require,module,exports){ +'use strict'; +var global = require('../internals/global'); +var ArrayBufferViewCore = require('../internals/array-buffer-view-core'); +var fails = require('../internals/fails'); + +var Uint8Array = global.Uint8Array; +var Uint8ArrayPrototype = Uint8Array && Uint8Array.prototype; +var arrayToString = [].toString; +var arrayJoin = [].join; + +if (fails(function () { arrayToString.call({}); })) { + arrayToString = function toString() { + return arrayJoin.call(this); + }; +} + +// `%TypedArray%.prototype.toString` method +// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tostring +ArrayBufferViewCore.exportProto('toString', arrayToString, (Uint8ArrayPrototype || {}).toString != arrayToString); + +},{"../internals/array-buffer-view-core":316,"../internals/fails":362,"../internals/global":377}],674:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Uint16Array` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Uint16', 2, function (init) { + return function Uint16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"../internals/typed-array-constructor":466}],675:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Uint32Array` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Uint32', 4, function (init) { + return function Uint32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"../internals/typed-array-constructor":466}],676:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Uint8Array` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Uint8', 1, function (init) { + return function Uint8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}); + +},{"../internals/typed-array-constructor":466}],677:[function(require,module,exports){ +var typedArrayConstructor = require('../internals/typed-array-constructor'); + +// `Uint8ClampedArray` constructor +// https://tc39.github.io/ecma262/#sec-typedarray-objects +typedArrayConstructor('Uint8', 1, function (init) { + return function Uint8ClampedArray(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; +}, true); + +},{"../internals/typed-array-constructor":466}],678:[function(require,module,exports){ +'use strict'; +var global = require('../internals/global'); +var redefineAll = require('../internals/redefine-all'); +var InternalMetadataModule = require('../internals/internal-metadata'); +var collection = require('../internals/collection'); +var collectionWeak = require('../internals/collection-weak'); +var isObject = require('../internals/is-object'); +var enforceIternalState = require('../internals/internal-state').enforce; +var NATIVE_WEAK_MAP = require('../internals/native-weak-map'); + +var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global; +var isExtensible = Object.isExtensible; +var InternalWeakMap; + +var wrapper = function (get) { + return function WeakMap() { + return get(this, arguments.length ? arguments[0] : undefined); + }; +}; + +// `WeakMap` constructor +// https://tc39.github.io/ecma262/#sec-weakmap-constructor +var $WeakMap = module.exports = collection('WeakMap', wrapper, collectionWeak, true, true); + +// IE11 WeakMap frozen keys fix +// We can't use feature detection because it crash some old IE builds +// https://github.com/zloirock/core-js/issues/485 +if (NATIVE_WEAK_MAP && IS_IE11) { + InternalWeakMap = collectionWeak.getConstructor(wrapper, 'WeakMap', true); + InternalMetadataModule.REQUIRED = true; + var WeakMapPrototype = $WeakMap.prototype; + var nativeDelete = WeakMapPrototype['delete']; + var nativeHas = WeakMapPrototype.has; + var nativeGet = WeakMapPrototype.get; + var nativeSet = WeakMapPrototype.set; + redefineAll(WeakMapPrototype, { + 'delete': function (key) { + if (isObject(key) && !isExtensible(key)) { + var state = enforceIternalState(this); + if (!state.frozen) state.frozen = new InternalWeakMap(); + return nativeDelete.call(this, key) || state.frozen['delete'](key); + } return nativeDelete.call(this, key); + }, + has: function has(key) { + if (isObject(key) && !isExtensible(key)) { + var state = enforceIternalState(this); + if (!state.frozen) state.frozen = new InternalWeakMap(); + return nativeHas.call(this, key) || state.frozen.has(key); + } return nativeHas.call(this, key); + }, + get: function get(key) { + if (isObject(key) && !isExtensible(key)) { + var state = enforceIternalState(this); + if (!state.frozen) state.frozen = new InternalWeakMap(); + return nativeHas.call(this, key) ? nativeGet.call(this, key) : state.frozen.get(key); + } return nativeGet.call(this, key); + }, + set: function set(key, value) { + if (isObject(key) && !isExtensible(key)) { + var state = enforceIternalState(this); + if (!state.frozen) state.frozen = new InternalWeakMap(); + nativeHas.call(this, key) ? nativeSet.call(this, key, value) : state.frozen.set(key, value); + } else nativeSet.call(this, key, value); + return this; + } + }); +} + +},{"../internals/collection":341,"../internals/collection-weak":340,"../internals/global":377,"../internals/internal-metadata":385,"../internals/internal-state":386,"../internals/is-object":392,"../internals/native-weak-map":408,"../internals/redefine-all":434}],679:[function(require,module,exports){ +'use strict'; +var collection = require('../internals/collection'); +var collectionWeak = require('../internals/collection-weak'); + +// `WeakSet` constructor +// https://tc39.github.io/ecma262/#sec-weakset-constructor +collection('WeakSet', function (get) { + return function WeakSet() { return get(this, arguments.length ? arguments[0] : undefined); }; +}, collectionWeak, false, true); + +},{"../internals/collection":341,"../internals/collection-weak":340}],680:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var setPrototypeOf = require('../internals/object-set-prototype-of'); +var create = require('../internals/object-create'); +var defineProperty = require('../internals/object-define-property'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); +var iterate = require('../internals/iterate'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var InternalStateModule = require('../internals/internal-state'); + +var setInternalState = InternalStateModule.set; +var getInternalAggregateErrorState = InternalStateModule.getterFor('AggregateError'); + +var $AggregateError = function AggregateError(errors, message) { + var that = this; + if (!(that instanceof $AggregateError)) return new $AggregateError(errors, message); + if (setPrototypeOf) { + that = setPrototypeOf(new Error(message), getPrototypeOf(that)); + } + var errorsArray = []; + iterate(errors, errorsArray.push, errorsArray); + if (DESCRIPTORS) setInternalState(that, { errors: errorsArray, type: 'AggregateError' }); + else that.errors = errorsArray; + if (message !== undefined) createNonEnumerableProperty(that, 'message', String(message)); + return that; +}; + +$AggregateError.prototype = create(Error.prototype, { + constructor: createPropertyDescriptor(5, $AggregateError), + message: createPropertyDescriptor(5, ''), + name: createPropertyDescriptor(5, 'AggregateError') +}); + +if (DESCRIPTORS) defineProperty.f($AggregateError.prototype, 'errors', { + get: function () { + return getInternalAggregateErrorState(this).errors; + }, + configurable: true +}); + +$({ global: true }, { + AggregateError: $AggregateError +}); + +},{"../internals/create-non-enumerable-property":350,"../internals/create-property-descriptor":351,"../internals/descriptors":357,"../internals/export":361,"../internals/internal-state":386,"../internals/iterate":395,"../internals/object-create":413,"../internals/object-define-property":415,"../internals/object-get-prototype-of":420,"../internals/object-set-prototype-of":424}],681:[function(require,module,exports){ +var $ = require('../internals/export'); +var isArray = require('../internals/is-array'); + +var isFrozen = Object.isFrozen; + +var isFrozenStringArray = function (array, allowUndefined) { + if (!isFrozen || !isArray(array) || !isFrozen(array)) return false; + var index = 0; + var length = array.length; + var element; + while (index < length) { + element = array[index++]; + if (!(typeof element === 'string' || (allowUndefined && typeof element === 'undefined'))) { + return false; + } + } return length !== 0; +}; + +// `Array.isTemplateObject` method +// https://github.com/tc39/proposal-array-is-template-object +$({ target: 'Array', stat: true }, { + isTemplateObject: function isTemplateObject(value) { + if (!isFrozenStringArray(value, true)) return false; + var raw = value.raw; + if (raw.length !== value.length || !isFrozenStringArray(raw, false)) return false; + return true; + } +}); + +},{"../internals/export":361,"../internals/is-array":388}],682:[function(require,module,exports){ +'use strict'; +var DESCRIPTORS = require('../internals/descriptors'); +var addToUnscopables = require('../internals/add-to-unscopables'); +var toObject = require('../internals/to-object'); +var toLength = require('../internals/to-length'); +var defineProperty = require('../internals/object-define-property').f; + +// `Array.prototype.lastIndex` getter +// https://github.com/keithamus/proposal-array-last +if (DESCRIPTORS && !('lastIndex' in [])) { + defineProperty(Array.prototype, 'lastIndex', { + configurable: true, + get: function lastIndex() { + var O = toObject(this); + var len = toLength(O.length); + return len == 0 ? 0 : len - 1; + } + }); + + addToUnscopables('lastIndex'); +} + +},{"../internals/add-to-unscopables":312,"../internals/descriptors":357,"../internals/object-define-property":415,"../internals/to-length":461,"../internals/to-object":462}],683:[function(require,module,exports){ +'use strict'; +var DESCRIPTORS = require('../internals/descriptors'); +var addToUnscopables = require('../internals/add-to-unscopables'); +var toObject = require('../internals/to-object'); +var toLength = require('../internals/to-length'); +var defineProperty = require('../internals/object-define-property').f; + +// `Array.prototype.lastIndex` accessor +// https://github.com/keithamus/proposal-array-last +if (DESCRIPTORS && !('lastItem' in [])) { + defineProperty(Array.prototype, 'lastItem', { + configurable: true, + get: function lastItem() { + var O = toObject(this); + var len = toLength(O.length); + return len == 0 ? undefined : O[len - 1]; + }, + set: function lastItem(value) { + var O = toObject(this); + var len = toLength(O.length); + return O[len == 0 ? 0 : len - 1] = value; + } + }); + + addToUnscopables('lastItem'); +} + +},{"../internals/add-to-unscopables":312,"../internals/descriptors":357,"../internals/object-define-property":415,"../internals/to-length":461,"../internals/to-object":462}],684:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var anInstance = require('../internals/an-instance'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var has = require('../internals/has'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var AsyncIteratorPrototype = require('../internals/async-iterator-prototype'); +var IS_PURE = require('../internals/is-pure'); + +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + +var AsyncIteratorConstructor = function AsyncIterator() { + anInstance(this, AsyncIteratorConstructor); +}; + +AsyncIteratorConstructor.prototype = AsyncIteratorPrototype; + +if (!has(AsyncIteratorPrototype, TO_STRING_TAG)) { + createNonEnumerableProperty(AsyncIteratorPrototype, TO_STRING_TAG, 'AsyncIterator'); +} + +if (!has(AsyncIteratorPrototype, 'constructor') || AsyncIteratorPrototype.constructor === Object) { + createNonEnumerableProperty(AsyncIteratorPrototype, 'constructor', AsyncIteratorConstructor); +} + +$({ global: true, forced: IS_PURE }, { + AsyncIterator: AsyncIteratorConstructor +}); + +},{"../internals/an-instance":314,"../internals/async-iterator-prototype":329,"../internals/create-non-enumerable-property":350,"../internals/export":361,"../internals/has":378,"../internals/is-pure":393,"../internals/well-known-symbol":473}],685:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var toPositiveInteger = require('../internals/to-positive-integer'); +var createAsyncIteratorProxy = require('../internals/create-async-iterator-proxy'); + +var AsyncIteratorProxy = createAsyncIteratorProxy(function (arg, Promise) { + var state = this; + + return new Promise(function (resolve, reject) { + var loop = function () { + try { + Promise.resolve( + anObject(state.next.call(state.iterator, state.remaining ? undefined : arg)) + ).then(function (step) { + try { + if (anObject(step).done) { + state.done = true; + resolve({ done: true, value: undefined }); + } else if (state.remaining) { + state.remaining--; + loop(); + } else resolve({ done: false, value: step.value }); + } catch (err) { reject(err); } + }, reject); + } catch (error) { reject(error); } + }; + + loop(); + }); +}); + +$({ target: 'AsyncIterator', proto: true, real: true }, { + drop: function drop(limit) { + return new AsyncIteratorProxy({ + iterator: anObject(this), + remaining: toPositiveInteger(limit) + }); + } +}); + +},{"../internals/an-object":315,"../internals/create-async-iterator-proxy":346,"../internals/export":361,"../internals/to-positive-integer":464}],686:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var createAsyncIteratorProxy = require('../internals/create-async-iterator-proxy'); + +var AsyncIteratorProxy = createAsyncIteratorProxy(function (arg, Promise) { + var state = this; + var filterer = state.filterer; + + return new Promise(function (resolve, reject) { + var loop = function () { + try { + Promise.resolve(anObject(state.next.call(state.iterator, arg))).then(function (step) { + try { + if (anObject(step).done) { + state.done = true; + resolve({ done: true, value: undefined }); + } else { + var value = step.value; + Promise.resolve(filterer(value)).then(function (selected) { + selected ? resolve({ done: false, value: value }) : loop(); + }, reject); + } + } catch (err) { reject(err); } + }, reject); + } catch (error) { reject(error); } + }; + + loop(); + }); +}); + +$({ target: 'AsyncIterator', proto: true, real: true }, { + filter: function filter(filterer) { + return new AsyncIteratorProxy({ + iterator: anObject(this), + filterer: aFunction(filterer) + }); + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/create-async-iterator-proxy":346,"../internals/export":361}],687:[function(require,module,exports){ +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var path = require('../internals/path'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var toObject = require('../internals/to-object'); +var createAsyncIteratorProxy = require('../internals/create-async-iterator-proxy'); +var getAsyncIteratorMethod = require('../internals/get-async-iterator-method'); + +var AsyncIterator = path.AsyncIterator; + +var AsyncIteratorProxy = createAsyncIteratorProxy(function (arg) { + return anObject(this.next.call(this.iterator, arg)); +}, true); + +$({ target: 'AsyncIterator', stat: true }, { + from: function from(O) { + var object = toObject(O); + var usingIterator = getAsyncIteratorMethod(object); + var iterator; + if (usingIterator != null) { + iterator = aFunction(usingIterator).call(object); + if (iterator instanceof AsyncIterator) return iterator; + } else { + iterator = object; + } return new AsyncIteratorProxy({ + iterator: iterator + }); + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/create-async-iterator-proxy":346,"../internals/export":361,"../internals/get-async-iterator-method":371,"../internals/path":430,"../internals/to-object":462}],688:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var createAsyncIteratorProxy = require('../internals/create-async-iterator-proxy'); + +var AsyncIteratorProxy = createAsyncIteratorProxy(function (arg, Promise) { + var state = this; + var mapper = state.mapper; + + return Promise.resolve(anObject(state.next.call(state.iterator, arg))).then(function (step) { + if (anObject(step).done) { + state.done = true; + return { done: true, value: undefined }; + } + return Promise.resolve(mapper(step.value)).then(function (value) { + return { done: false, value: value }; + }); + }); +}); + +$({ target: 'AsyncIterator', proto: true, real: true }, { + map: function map(mapper) { + return new AsyncIteratorProxy({ + iterator: anObject(this), + mapper: aFunction(mapper) + }); + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/create-async-iterator-proxy":346,"../internals/export":361}],689:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var toPositiveInteger = require('../internals/to-positive-integer'); +var createAsyncIteratorProxy = require('../internals/create-async-iterator-proxy'); + +var AsyncIteratorProxy = createAsyncIteratorProxy(function (arg) { + if (!this.remaining--) { + this.done = true; + return { done: true, value: undefined }; + } return this.next.call(this.iterator, arg); +}); + +$({ target: 'AsyncIterator', proto: true, real: true }, { + take: function take(limit) { + return new AsyncIteratorProxy({ + iterator: anObject(this), + remaining: toPositiveInteger(limit) + }); + } +}); + +},{"../internals/an-object":315,"../internals/create-async-iterator-proxy":346,"../internals/export":361,"../internals/to-positive-integer":464}],690:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var $toArray = require('../internals/async-iterator-iteration').toArray; + +$({ target: 'AsyncIterator', proto: true, real: true }, { + toArray: function toArray() { + return $toArray(this); + } +}); + +},{"../internals/async-iterator-iteration":328,"../internals/export":361}],691:[function(require,module,exports){ +var $ = require('../internals/export'); +var getCompositeKeyNode = require('../internals/composite-key'); +var getBuiltIn = require('../internals/get-built-in'); +var create = require('../internals/object-create'); + +var initializer = function () { + var freeze = getBuiltIn('Object', 'freeze'); + return freeze ? freeze(create(null)) : create(null); +}; + +// https://github.com/tc39/proposal-richer-keys/tree/master/compositeKey +$({ global: true }, { + compositeKey: function compositeKey() { + return getCompositeKeyNode.apply(Object, arguments).get('object', initializer); + } +}); + +},{"../internals/composite-key":342,"../internals/export":361,"../internals/get-built-in":372,"../internals/object-create":413}],692:[function(require,module,exports){ +var $ = require('../internals/export'); +var getCompositeKeyNode = require('../internals/composite-key'); +var getBuiltIn = require('../internals/get-built-in'); + +// https://github.com/tc39/proposal-richer-keys/tree/master/compositeKey +$({ global: true }, { + compositeSymbol: function compositeSymbol() { + if (arguments.length === 1 && typeof arguments[0] === 'string') return getBuiltIn('Symbol')['for'](arguments[0]); + return getCompositeKeyNode.apply(null, arguments).get('symbol', getBuiltIn('Symbol')); + } +}); + +},{"../internals/composite-key":342,"../internals/export":361,"../internals/get-built-in":372}],693:[function(require,module,exports){ +// TODO: Remove from `core-js@4` +require('./es.global-this'); + +},{"./es.global-this":517}],694:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var createIteratorProxy = require('../internals/create-iterator-proxy'); + +var IteratorProxy = createIteratorProxy(function (arg) { + var result = anObject(this.next.call(this.iterator, arg)); + var done = this.done = !!result.done; + if (!done) return [this.index++, result.value]; +}); + +$({ target: 'Iterator', proto: true, real: true }, { + asIndexedPairs: function asIndexedPairs() { + return new IteratorProxy({ + iterator: anObject(this), + index: 0 + }); + } +}); + +},{"../internals/an-object":315,"../internals/create-iterator-proxy":349,"../internals/export":361}],695:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var global = require('../internals/global'); +var anInstance = require('../internals/an-instance'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var has = require('../internals/has'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var IteratorPrototype = require('../internals/iterators-core').IteratorPrototype; +var IS_PURE = require('../internals/is-pure'); + +var ITERATOR = wellKnownSymbol('iterator'); +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + +var NativeIterator = global.Iterator; + +// FF56- have non-standard global helper `Iterator` +var FORCED = IS_PURE || typeof NativeIterator != 'function' || NativeIterator.prototype !== IteratorPrototype; + +var IteratorConstructor = function Iterator() { + anInstance(this, IteratorConstructor); +}; + +if (IS_PURE) { + IteratorPrototype = {}; + createNonEnumerableProperty(IteratorPrototype, ITERATOR, function () { + return this; + }); +} + +if (!has(IteratorPrototype, TO_STRING_TAG)) { + createNonEnumerableProperty(IteratorPrototype, TO_STRING_TAG, 'Iterator'); +} + +if (!has(IteratorPrototype, 'constructor') || IteratorPrototype.constructor === Object) { + createNonEnumerableProperty(IteratorPrototype, 'constructor', IteratorConstructor); +} + +IteratorConstructor.prototype = IteratorPrototype; + +$({ global: true, forced: FORCED }, { + Iterator: IteratorConstructor +}); + +},{"../internals/an-instance":314,"../internals/create-non-enumerable-property":350,"../internals/export":361,"../internals/global":377,"../internals/has":378,"../internals/is-pure":393,"../internals/iterators-core":396,"../internals/well-known-symbol":473}],696:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var toPositiveInteger = require('../internals/to-positive-integer'); +var createIteratorProxy = require('../internals/create-iterator-proxy'); + +var IteratorProxy = createIteratorProxy(function (arg) { + var iterator = this.iterator; + var next = this.next; + var result, done; + while (this.remaining) { + this.remaining--; + result = anObject(next.call(iterator)); + done = this.done = !!result.done; + if (done) return; + } + result = anObject(next.call(iterator, arg)); + done = this.done = !!result.done; + if (!done) return result.value; +}); + +$({ target: 'Iterator', proto: true, real: true }, { + drop: function drop(limit) { + return new IteratorProxy({ + iterator: anObject(this), + remaining: toPositiveInteger(limit) + }); + } +}); + +},{"../internals/an-object":315,"../internals/create-iterator-proxy":349,"../internals/export":361,"../internals/to-positive-integer":464}],697:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); + +$({ target: 'Iterator', proto: true, real: true }, { + every: function every(fn) { + anObject(this); + aFunction(fn); + return !iterate(this, function (value) { + if (!fn(value)) return iterate.stop(); + }, undefined, false, true).stopped; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/iterate":395}],698:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var createIteratorProxy = require('../internals/create-iterator-proxy'); +var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing'); + +var IteratorProxy = createIteratorProxy(function (arg) { + var iterator = this.iterator; + var filterer = this.filterer; + var next = this.next; + var result, done, value; + while (true) { + result = anObject(next.call(iterator, arg)); + done = this.done = !!result.done; + if (done) return; + value = result.value; + if (callWithSafeIterationClosing(iterator, filterer, value)) return value; + } +}); + +$({ target: 'Iterator', proto: true, real: true }, { + filter: function filter(filterer) { + return new IteratorProxy({ + iterator: anObject(this), + filterer: aFunction(filterer) + }); + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/call-with-safe-iteration-closing":331,"../internals/create-iterator-proxy":349,"../internals/export":361}],699:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); + +$({ target: 'Iterator', proto: true, real: true }, { + find: function find(fn) { + anObject(this); + aFunction(fn); + return iterate(this, function (value) { + if (fn(value)) return iterate.stop(value); + }, undefined, false, true).result; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/iterate":395}],700:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var anObject = require('../internals/an-object'); + +$({ target: 'Iterator', proto: true, real: true }, { + forEach: function forEach(fn) { + iterate(anObject(this), fn, undefined, false, true); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/iterate":395}],701:[function(require,module,exports){ +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var path = require('../internals/path'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var toObject = require('../internals/to-object'); +var createIteratorProxy = require('../internals/create-iterator-proxy'); +var getIteratorMethod = require('../internals/get-iterator-method'); + +var Iterator = path.Iterator; + +var IteratorProxy = createIteratorProxy(function (arg) { + var result = anObject(this.next.call(this.iterator, arg)); + var done = this.done = !!result.done; + if (!done) return result.value; +}, true); + +$({ target: 'Iterator', stat: true }, { + from: function from(O) { + var object = toObject(O); + var usingIterator = getIteratorMethod(object); + var iterator; + if (usingIterator != null) { + iterator = aFunction(usingIterator).call(object); + if (iterator instanceof Iterator) return iterator; + } else { + iterator = object; + } return new IteratorProxy({ + iterator: iterator + }); + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/create-iterator-proxy":349,"../internals/export":361,"../internals/get-iterator-method":373,"../internals/path":430,"../internals/to-object":462}],702:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var createIteratorProxy = require('../internals/create-iterator-proxy'); +var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing'); + +var IteratorProxy = createIteratorProxy(function (arg) { + var iterator = this.iterator; + var result = anObject(this.next.call(iterator, arg)); + var done = this.done = !!result.done; + if (!done) return callWithSafeIterationClosing(iterator, this.mapper, result.value); +}); + +$({ target: 'Iterator', proto: true, real: true }, { + map: function map(mapper) { + return new IteratorProxy({ + iterator: anObject(this), + mapper: aFunction(mapper) + }); + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/call-with-safe-iteration-closing":331,"../internals/create-iterator-proxy":349,"../internals/export":361}],703:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); + +$({ target: 'Iterator', proto: true, real: true }, { + reduce: function reduce(reducer /* , initialValue */) { + anObject(this); + aFunction(reducer); + var noInitial = arguments.length < 2; + var accumulator = noInitial ? undefined : arguments[1]; + iterate(this, function (value) { + if (noInitial) { + noInitial = false; + accumulator = value; + } else { + accumulator = reducer(accumulator, value); + } + }, undefined, false, true); + if (noInitial) throw TypeError('Reduce of empty iterator with no initial value'); + return accumulator; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/iterate":395}],704:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); + +$({ target: 'Iterator', proto: true, real: true }, { + some: function some(fn) { + anObject(this); + aFunction(fn); + return iterate(this, function (value) { + if (fn(value)) return iterate.stop(); + }, undefined, false, true).stopped; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/iterate":395}],705:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var toPositiveInteger = require('../internals/to-positive-integer'); +var createIteratorProxy = require('../internals/create-iterator-proxy'); + +var IteratorProxy = createIteratorProxy(function (arg) { + if (!this.remaining--) { + this.done = true; + return; + } + var result = anObject(this.next.call(this.iterator, arg)); + var done = this.done = !!result.done; + if (!done) return result.value; +}); + +$({ target: 'Iterator', proto: true, real: true }, { + take: function take(limit) { + return new IteratorProxy({ + iterator: anObject(this), + remaining: toPositiveInteger(limit) + }); + } +}); + +},{"../internals/an-object":315,"../internals/create-iterator-proxy":349,"../internals/export":361,"../internals/to-positive-integer":464}],706:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-iterator-helpers +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var anObject = require('../internals/an-object'); + +var push = [].push; + +$({ target: 'Iterator', proto: true, real: true }, { + toArray: function toArray() { + var result = []; + iterate(anObject(this), push, result, false, true); + return result; + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/iterate":395}],707:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var collectionDeleteAll = require('../internals/collection-delete-all'); + +// `Map.prototype.deleteAll` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + deleteAll: function deleteAll(/* ...elements */) { + return collectionDeleteAll.apply(this, arguments); + } +}); + +},{"../internals/collection-delete-all":336,"../internals/export":361,"../internals/is-pure":393}],708:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var bind = require('../internals/bind-context'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.every` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + every: function every(callbackfn /* , thisArg */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + return !iterate(iterator, function (key, value) { + if (!boundFunction(value, key, map)) return iterate.stop(); + }, undefined, true, true).stopped; + } +}); + +},{"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395}],709:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var bind = require('../internals/bind-context'); +var speciesConstructor = require('../internals/species-constructor'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.filter` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + filter: function filter(callbackfn /* , thisArg */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var newMap = new (speciesConstructor(map, getBuiltIn('Map')))(); + var setter = aFunction(newMap.set); + iterate(iterator, function (key, value) { + if (boundFunction(value, key, map)) setter.call(newMap, key, value); + }, undefined, true, true); + return newMap; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-built-in":372,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],710:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var bind = require('../internals/bind-context'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.findKey` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + findKey: function findKey(callbackfn /* , thisArg */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + return iterate(iterator, function (key, value) { + if (boundFunction(value, key, map)) return iterate.stop(key); + }, undefined, true, true).result; + } +}); + +},{"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395}],711:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var bind = require('../internals/bind-context'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.find` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + find: function find(callbackfn /* , thisArg */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + return iterate(iterator, function (key, value) { + if (boundFunction(value, key, map)) return iterate.stop(value); + }, undefined, true, true).result; + } +}); + +},{"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395}],712:[function(require,module,exports){ +var $ = require('../internals/export'); +var from = require('../internals/collection-from'); + +// `Map.from` method +// https://tc39.github.io/proposal-setmap-offrom/#sec-map.from +$({ target: 'Map', stat: true }, { + from: from +}); + +},{"../internals/collection-from":337,"../internals/export":361}],713:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var aFunction = require('../internals/a-function'); + +// `Map.groupBy` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', stat: true }, { + groupBy: function groupBy(iterable, keyDerivative) { + var newMap = new this(); + aFunction(keyDerivative); + var has = aFunction(newMap.has); + var get = aFunction(newMap.get); + var set = aFunction(newMap.set); + iterate(iterable, function (element) { + var derivedKey = keyDerivative(element); + if (!has.call(newMap, derivedKey)) set.call(newMap, derivedKey, [element]); + else get.call(newMap, derivedKey).push(element); + }); + return newMap; + } +}); + +},{"../internals/a-function":310,"../internals/export":361,"../internals/iterate":395}],714:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var getMapIterator = require('../internals/get-map-iterator'); +var sameValueZero = require('../internals/same-value-zero'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.includes` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + includes: function includes(searchElement) { + return iterate(getMapIterator(anObject(this)), function (key, value) { + if (sameValueZero(value, searchElement)) return iterate.stop(); + }, undefined, true, true).stopped; + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395,"../internals/same-value-zero":441}],715:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var iterate = require('../internals/iterate'); +var aFunction = require('../internals/a-function'); + +// `Map.keyBy` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', stat: true }, { + keyBy: function keyBy(iterable, keyDerivative) { + var newMap = new this(); + aFunction(keyDerivative); + var setter = aFunction(newMap.set); + iterate(iterable, function (element) { + setter.call(newMap, keyDerivative(element), element); + }); + return newMap; + } +}); + +},{"../internals/a-function":310,"../internals/export":361,"../internals/iterate":395}],716:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.includes` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + keyOf: function keyOf(searchElement) { + return iterate(getMapIterator(anObject(this)), function (key, value) { + if (value === searchElement) return iterate.stop(key); + }, undefined, true, true).result; + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395}],717:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var bind = require('../internals/bind-context'); +var speciesConstructor = require('../internals/species-constructor'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.mapKeys` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + mapKeys: function mapKeys(callbackfn /* , thisArg */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var newMap = new (speciesConstructor(map, getBuiltIn('Map')))(); + var setter = aFunction(newMap.set); + iterate(iterator, function (key, value) { + setter.call(newMap, boundFunction(value, key, map), value); + }, undefined, true, true); + return newMap; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-built-in":372,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],718:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var bind = require('../internals/bind-context'); +var speciesConstructor = require('../internals/species-constructor'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.mapValues` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + mapValues: function mapValues(callbackfn /* , thisArg */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var newMap = new (speciesConstructor(map, getBuiltIn('Map')))(); + var setter = aFunction(newMap.set); + iterate(iterator, function (key, value) { + setter.call(newMap, key, boundFunction(value, key, map)); + }, undefined, true, true); + return newMap; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-built-in":372,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],719:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.merge` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + // eslint-disable-next-line no-unused-vars + merge: function merge(iterable /* ...iterbles */) { + var map = anObject(this); + var setter = aFunction(map.set); + var i = 0; + while (i < arguments.length) { + iterate(arguments[i++], setter, map, true); + } + return map; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/is-pure":393,"../internals/iterate":395}],720:[function(require,module,exports){ +var $ = require('../internals/export'); +var of = require('../internals/collection-of'); + +// `Map.of` method +// https://tc39.github.io/proposal-setmap-offrom/#sec-map.of +$({ target: 'Map', stat: true }, { + of: of +}); + +},{"../internals/collection-of":338,"../internals/export":361}],721:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Map.prototype.reduce` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + reduce: function reduce(callbackfn /* , initialValue */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var noInitial = arguments.length < 2; + var accumulator = noInitial ? undefined : arguments[1]; + aFunction(callbackfn); + iterate(iterator, function (key, value) { + if (noInitial) { + noInitial = false; + accumulator = value; + } else { + accumulator = callbackfn(accumulator, value, key, map); + } + }, undefined, true, true); + if (noInitial) throw TypeError('Reduce of empty map with no initial value'); + return accumulator; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395}],722:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var bind = require('../internals/bind-context'); +var getMapIterator = require('../internals/get-map-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.some` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + some: function some(callbackfn /* , thisArg */) { + var map = anObject(this); + var iterator = getMapIterator(map); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + return iterate(iterator, function (key, value) { + if (boundFunction(value, key, map)) return iterate.stop(); + }, undefined, true, true).stopped; + } +}); + +},{"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-map-iterator":375,"../internals/is-pure":393,"../internals/iterate":395}],723:[function(require,module,exports){ +'use strict'; +// TODO: remove from `core-js@4` +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var $upsert = require('../internals/map-upsert'); + +// `Map.prototype.updateOrInsert` method (replaced by `Map.prototype.upsert`) +// https://github.com/thumbsupep/proposal-upsert +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + updateOrInsert: $upsert +}); + +},{"../internals/export":361,"../internals/is-pure":393,"../internals/map-upsert":398}],724:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); + +// `Set.prototype.update` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + update: function update(key, callback /* , thunk */) { + var map = anObject(this); + var length = arguments.length; + aFunction(callback); + var isPresentInMap = map.has(key); + if (!isPresentInMap && length < 3) { + throw TypeError('Updating absent value'); + } + var value = isPresentInMap ? map.get(key) : aFunction(length > 2 ? arguments[2] : undefined)(key, map); + map.set(key, callback(value, key, map)); + return map; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/is-pure":393}],725:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var $upsert = require('../internals/map-upsert'); + +// `Map.prototype.upsert` method +// https://github.com/thumbsupep/proposal-upsert +$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { + upsert: $upsert +}); + +},{"../internals/export":361,"../internals/is-pure":393,"../internals/map-upsert":398}],726:[function(require,module,exports){ +var $ = require('../internals/export'); + +var min = Math.min; +var max = Math.max; + +// `Math.clamp` method +// https://rwaldron.github.io/proposal-math-extensions/ +$({ target: 'Math', stat: true }, { + clamp: function clamp(x, lower, upper) { + return min(upper, max(lower, x)); + } +}); + +},{"../internals/export":361}],727:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Math.DEG_PER_RAD` constant +// https://rwaldron.github.io/proposal-math-extensions/ +$({ target: 'Math', stat: true }, { + DEG_PER_RAD: Math.PI / 180 +}); + +},{"../internals/export":361}],728:[function(require,module,exports){ +var $ = require('../internals/export'); + +var RAD_PER_DEG = 180 / Math.PI; + +// `Math.degrees` method +// https://rwaldron.github.io/proposal-math-extensions/ +$({ target: 'Math', stat: true }, { + degrees: function degrees(radians) { + return radians * RAD_PER_DEG; + } +}); + +},{"../internals/export":361}],729:[function(require,module,exports){ +var $ = require('../internals/export'); + +var scale = require('../internals/math-scale'); +var fround = require('../internals/math-fround'); + +// `Math.fscale` method +// https://rwaldron.github.io/proposal-math-extensions/ +$({ target: 'Math', stat: true }, { + fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { + return fround(scale(x, inLow, inHigh, outLow, outHigh)); + } +}); + +},{"../internals/export":361,"../internals/math-fround":400,"../internals/math-scale":402}],730:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Math.iaddh` method +// https://gist.github.com/BrendanEich/4294d5c212a6d2254703 +// TODO: Remove from `core-js@4` +$({ target: 'Math', stat: true }, { + iaddh: function iaddh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; + } +}); + +},{"../internals/export":361}],731:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Math.imulh` method +// https://gist.github.com/BrendanEich/4294d5c212a6d2254703 +// TODO: Remove from `core-js@4` +$({ target: 'Math', stat: true }, { + imulh: function imulh(u, v) { + var UINT16 = 0xFFFF; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >> 16; + var v1 = $v >> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); + } +}); + +},{"../internals/export":361}],732:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Math.isubh` method +// https://gist.github.com/BrendanEich/4294d5c212a6d2254703 +// TODO: Remove from `core-js@4` +$({ target: 'Math', stat: true }, { + isubh: function isubh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; + } +}); + +},{"../internals/export":361}],733:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Math.RAD_PER_DEG` constant +// https://rwaldron.github.io/proposal-math-extensions/ +$({ target: 'Math', stat: true }, { + RAD_PER_DEG: 180 / Math.PI +}); + +},{"../internals/export":361}],734:[function(require,module,exports){ +var $ = require('../internals/export'); + +var DEG_PER_RAD = Math.PI / 180; + +// `Math.radians` method +// https://rwaldron.github.io/proposal-math-extensions/ +$({ target: 'Math', stat: true }, { + radians: function radians(degrees) { + return degrees * DEG_PER_RAD; + } +}); + +},{"../internals/export":361}],735:[function(require,module,exports){ +var $ = require('../internals/export'); +var scale = require('../internals/math-scale'); + +// `Math.scale` method +// https://rwaldron.github.io/proposal-math-extensions/ +$({ target: 'Math', stat: true }, { + scale: scale +}); + +},{"../internals/export":361,"../internals/math-scale":402}],736:[function(require,module,exports){ +var $ = require('../internals/export'); +var anObject = require('../internals/an-object'); +var numberIsFinite = require('../internals/number-is-finite'); +var createIteratorConstructor = require('../internals/create-iterator-constructor'); +var InternalStateModule = require('../internals/internal-state'); + +var SEEDED_RANDOM = 'Seeded Random'; +var SEEDED_RANDOM_GENERATOR = SEEDED_RANDOM + ' Generator'; +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(SEEDED_RANDOM_GENERATOR); +var SEED_TYPE_ERROR = 'Math.seededPRNG() argument should have a "seed" field with a finite value.'; + +var $SeededRandomGenerator = createIteratorConstructor(function SeededRandomGenerator(seed) { + setInternalState(this, { + type: SEEDED_RANDOM_GENERATOR, + seed: seed % 2147483647 + }); +}, SEEDED_RANDOM, function next() { + var state = getInternalState(this); + var seed = state.seed = (state.seed * 1103515245 + 12345) % 2147483647; + return { value: (seed & 1073741823) / 1073741823, done: false }; +}); + +// `Math.seededPRNG` method +// https://github.com/tc39/proposal-seeded-random +// based on https://github.com/tc39/proposal-seeded-random/blob/78b8258835b57fc2100d076151ab506bc3202ae6/demo.html +$({ target: 'Math', stat: true, forced: true }, { + seededPRNG: function seededPRNG(it) { + var seed = anObject(it).seed; + if (!numberIsFinite(seed)) throw TypeError(SEED_TYPE_ERROR); + return new $SeededRandomGenerator(seed); + } +}); + +},{"../internals/an-object":315,"../internals/create-iterator-constructor":348,"../internals/export":361,"../internals/internal-state":386,"../internals/number-is-finite":411}],737:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Math.signbit` method +// https://github.com/tc39/proposal-Math.signbit +$({ target: 'Math', stat: true }, { + signbit: function signbit(x) { + return (x = +x) == x && x == 0 ? 1 / x == -Infinity : x < 0; + } +}); + +},{"../internals/export":361}],738:[function(require,module,exports){ +var $ = require('../internals/export'); + +// `Math.umulh` method +// https://gist.github.com/BrendanEich/4294d5c212a6d2254703 +// TODO: Remove from `core-js@4` +$({ target: 'Math', stat: true }, { + umulh: function umulh(u, v) { + var UINT16 = 0xFFFF; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >>> 16; + var v1 = $v >>> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); + } +}); + +},{"../internals/export":361}],739:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var toInteger = require('../internals/to-integer'); +var parseInt = require('../internals/parse-int'); + +var INVALID_NUMBER_REPRESENTATION = 'Invalid number representation'; +var INVALID_RADIX = 'Invalid radix'; +var valid = /^[\da-z]+$/; + +// `Number.fromString` method +// https://github.com/tc39/proposal-number-fromstring +$({ target: 'Number', stat: true }, { + fromString: function fromString(string, radix) { + var sign = 1; + var R, mathNum; + if (typeof string != 'string') throw TypeError(INVALID_NUMBER_REPRESENTATION); + if (!string.length) throw SyntaxError(INVALID_NUMBER_REPRESENTATION); + if (string.charAt(0) == '-') { + sign = -1; + string = string.slice(1); + if (!string.length) throw SyntaxError(INVALID_NUMBER_REPRESENTATION); + } + R = radix === undefined ? 10 : toInteger(radix); + if (R < 2 || R > 36) throw RangeError(INVALID_RADIX); + if (!valid.test(string) || (mathNum = parseInt(string, R)).toString(R) !== string) { + throw SyntaxError(INVALID_NUMBER_REPRESENTATION); + } + return sign * mathNum; + } +}); + +},{"../internals/export":361,"../internals/parse-int":429,"../internals/to-integer":460}],740:[function(require,module,exports){ +'use strict'; +// https://github.com/tc39/proposal-observable +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var setSpecies = require('../internals/set-species'); +var aFunction = require('../internals/a-function'); +var anObject = require('../internals/an-object'); +var isObject = require('../internals/is-object'); +var anInstance = require('../internals/an-instance'); +var defineProperty = require('../internals/object-define-property').f; +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var redefineAll = require('../internals/redefine-all'); +var getIterator = require('../internals/get-iterator'); +var iterate = require('../internals/iterate'); +var hostReportErrors = require('../internals/host-report-errors'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var InternalStateModule = require('../internals/internal-state'); + +var OBSERVABLE = wellKnownSymbol('observable'); +var getInternalState = InternalStateModule.get; +var setInternalState = InternalStateModule.set; + +var getMethod = function (fn) { + return fn == null ? undefined : aFunction(fn); +}; + +var cleanupSubscription = function (subscriptionState) { + var cleanup = subscriptionState.cleanup; + if (cleanup) { + subscriptionState.cleanup = undefined; + try { + cleanup(); + } catch (error) { + hostReportErrors(error); + } + } +}; + +var subscriptionClosed = function (subscriptionState) { + return subscriptionState.observer === undefined; +}; + +var close = function (subscription, subscriptionState) { + if (!DESCRIPTORS) { + subscription.closed = true; + var subscriptionObserver = subscriptionState.subscriptionObserver; + if (subscriptionObserver) subscriptionObserver.closed = true; + } subscriptionState.observer = undefined; +}; + +var Subscription = function (observer, subscriber) { + var subscriptionState = setInternalState(this, { + cleanup: undefined, + observer: anObject(observer), + subscriptionObserver: undefined + }); + var start; + if (!DESCRIPTORS) this.closed = false; + try { + if (start = getMethod(observer.start)) start.call(observer, this); + } catch (error) { + hostReportErrors(error); + } + if (subscriptionClosed(subscriptionState)) return; + var subscriptionObserver = subscriptionState.subscriptionObserver = new SubscriptionObserver(this); + try { + var cleanup = subscriber(subscriptionObserver); + var subscription = cleanup; + if (cleanup != null) subscriptionState.cleanup = typeof cleanup.unsubscribe === 'function' + ? function () { subscription.unsubscribe(); } + : aFunction(cleanup); + } catch (error) { + subscriptionObserver.error(error); + return; + } if (subscriptionClosed(subscriptionState)) cleanupSubscription(subscriptionState); +}; + +Subscription.prototype = redefineAll({}, { + unsubscribe: function unsubscribe() { + var subscriptionState = getInternalState(this); + if (!subscriptionClosed(subscriptionState)) { + close(this, subscriptionState); + cleanupSubscription(subscriptionState); + } + } +}); + +if (DESCRIPTORS) defineProperty(Subscription.prototype, 'closed', { + configurable: true, + get: function () { + return subscriptionClosed(getInternalState(this)); + } +}); + +var SubscriptionObserver = function (subscription) { + setInternalState(this, { subscription: subscription }); + if (!DESCRIPTORS) this.closed = false; +}; + +SubscriptionObserver.prototype = redefineAll({}, { + next: function next(value) { + var subscriptionState = getInternalState(getInternalState(this).subscription); + if (!subscriptionClosed(subscriptionState)) { + var observer = subscriptionState.observer; + try { + var nextMethod = getMethod(observer.next); + if (nextMethod) nextMethod.call(observer, value); + } catch (error) { + hostReportErrors(error); + } + } + }, + error: function error(value) { + var subscription = getInternalState(this).subscription; + var subscriptionState = getInternalState(subscription); + if (!subscriptionClosed(subscriptionState)) { + var observer = subscriptionState.observer; + close(subscription, subscriptionState); + try { + var errorMethod = getMethod(observer.error); + if (errorMethod) errorMethod.call(observer, value); + else hostReportErrors(value); + } catch (err) { + hostReportErrors(err); + } cleanupSubscription(subscriptionState); + } + }, + complete: function complete() { + var subscription = getInternalState(this).subscription; + var subscriptionState = getInternalState(subscription); + if (!subscriptionClosed(subscriptionState)) { + var observer = subscriptionState.observer; + close(subscription, subscriptionState); + try { + var completeMethod = getMethod(observer.complete); + if (completeMethod) completeMethod.call(observer); + } catch (error) { + hostReportErrors(error); + } cleanupSubscription(subscriptionState); + } + } +}); + +if (DESCRIPTORS) defineProperty(SubscriptionObserver.prototype, 'closed', { + configurable: true, + get: function () { + return subscriptionClosed(getInternalState(getInternalState(this).subscription)); + } +}); + +var $Observable = function Observable(subscriber) { + anInstance(this, $Observable, 'Observable'); + setInternalState(this, { subscriber: aFunction(subscriber) }); +}; + +redefineAll($Observable.prototype, { + subscribe: function subscribe(observer) { + var length = arguments.length; + return new Subscription(typeof observer === 'function' ? { + next: observer, + error: length > 1 ? arguments[1] : undefined, + complete: length > 2 ? arguments[2] : undefined + } : isObject(observer) ? observer : {}, getInternalState(this).subscriber); + } +}); + +redefineAll($Observable, { + from: function from(x) { + var C = typeof this === 'function' ? this : $Observable; + var observableMethod = getMethod(anObject(x)[OBSERVABLE]); + if (observableMethod) { + var observable = anObject(observableMethod.call(x)); + return observable.constructor === C ? observable : new C(function (observer) { + return observable.subscribe(observer); + }); + } + var iterator = getIterator(x); + return new C(function (observer) { + iterate(iterator, function (it) { + observer.next(it); + if (observer.closed) return iterate.stop(); + }, undefined, false, true); + observer.complete(); + }); + }, + of: function of() { + var C = typeof this === 'function' ? this : $Observable; + var length = arguments.length; + var items = new Array(length); + var index = 0; + while (index < length) items[index] = arguments[index++]; + return new C(function (observer) { + for (var i = 0; i < length; i++) { + observer.next(items[i]); + if (observer.closed) return; + } observer.complete(); + }); + } +}); + +createNonEnumerableProperty($Observable.prototype, OBSERVABLE, function () { return this; }); + +$({ global: true }, { + Observable: $Observable +}); + +setSpecies('Observable'); + +},{"../internals/a-function":310,"../internals/an-instance":314,"../internals/an-object":315,"../internals/create-non-enumerable-property":350,"../internals/descriptors":357,"../internals/export":361,"../internals/get-iterator":374,"../internals/host-report-errors":380,"../internals/internal-state":386,"../internals/is-object":392,"../internals/iterate":395,"../internals/object-define-property":415,"../internals/redefine-all":434,"../internals/set-species":444,"../internals/well-known-symbol":473}],741:[function(require,module,exports){ +// TODO: Remove from `core-js@4` +require('./es.promise.all-settled.js'); + +},{"./es.promise.all-settled.js":577}],742:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var aFunction = require('../internals/a-function'); +var getBuiltIn = require('../internals/get-built-in'); +var newPromiseCapabilityModule = require('../internals/new-promise-capability'); +var perform = require('../internals/perform'); +var iterate = require('../internals/iterate'); + +var PROMISE_ANY_ERROR = 'No one promise resolved'; + +// `Promise.any` method +// https://github.com/tc39/proposal-promise-any +$({ target: 'Promise', stat: true }, { + any: function any(iterable) { + var C = this; + var capability = newPromiseCapabilityModule.f(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var promiseResolve = aFunction(C.resolve); + var errors = []; + var counter = 0; + var remaining = 1; + var alreadyResolved = false; + iterate(iterable, function (promise) { + var index = counter++; + var alreadyRejected = false; + errors.push(undefined); + remaining++; + promiseResolve.call(C, promise).then(function (value) { + if (alreadyRejected || alreadyResolved) return; + alreadyResolved = true; + resolve(value); + }, function (e) { + if (alreadyRejected || alreadyResolved) return; + alreadyRejected = true; + errors[index] = e; + --remaining || reject(new (getBuiltIn('AggregateError'))(errors, PROMISE_ANY_ERROR)); + }); + }); + --remaining || reject(new (getBuiltIn('AggregateError'))(errors, PROMISE_ANY_ERROR)); + }); + if (result.error) reject(result.value); + return capability.promise; + } +}); + +},{"../internals/a-function":310,"../internals/export":361,"../internals/get-built-in":372,"../internals/iterate":395,"../internals/new-promise-capability":409,"../internals/perform":431}],743:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var newPromiseCapabilityModule = require('../internals/new-promise-capability'); +var perform = require('../internals/perform'); + +// `Promise.try` method +// https://github.com/tc39/proposal-promise-try +$({ target: 'Promise', stat: true }, { + 'try': function (callbackfn) { + var promiseCapability = newPromiseCapabilityModule.f(this); + var result = perform(callbackfn); + (result.error ? promiseCapability.reject : promiseCapability.resolve)(result.value); + return promiseCapability.promise; + } +}); + +},{"../internals/export":361,"../internals/new-promise-capability":409,"../internals/perform":431}],744:[function(require,module,exports){ +var $ = require('../internals/export'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); + +var toMetadataKey = ReflectMetadataModule.toKey; +var ordinaryDefineOwnMetadata = ReflectMetadataModule.set; + +// `Reflect.defineMetadata` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + defineMetadata: function defineMetadata(metadataKey, metadataValue, target /* , targetKey */) { + var targetKey = arguments.length < 4 ? undefined : toMetadataKey(arguments[3]); + ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), targetKey); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/reflect-metadata":436}],745:[function(require,module,exports){ +var $ = require('../internals/export'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); + +var toMetadataKey = ReflectMetadataModule.toKey; +var getOrCreateMetadataMap = ReflectMetadataModule.getMap; +var store = ReflectMetadataModule.store; + +// `Reflect.deleteMetadata` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetadataKey(arguments[2]); + var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); + if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; + if (metadataMap.size) return true; + var targetMetadata = store.get(target); + targetMetadata['delete'](targetKey); + return !!targetMetadata.size || store['delete'](target); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/reflect-metadata":436}],746:[function(require,module,exports){ +var $ = require('../internals/export'); +// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` +var Set = require('../modules/es.set'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); +var iterate = require('../internals/iterate'); + +var ordinaryOwnMetadataKeys = ReflectMetadataModule.keys; +var toMetadataKey = ReflectMetadataModule.toKey; + +var from = function (iter) { + var result = []; + iterate(iter, result.push, result); + return result; +}; + +var ordinaryMetadataKeys = function (O, P) { + var oKeys = ordinaryOwnMetadataKeys(O, P); + var parent = getPrototypeOf(O); + if (parent === null) return oKeys; + var pKeys = ordinaryMetadataKeys(parent, P); + return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; +}; + +// `Reflect.getMetadataKeys` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { + var targetKey = arguments.length < 2 ? undefined : toMetadataKey(arguments[1]); + return ordinaryMetadataKeys(anObject(target), targetKey); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/iterate":395,"../internals/object-get-prototype-of":420,"../internals/reflect-metadata":436,"../modules/es.set":597}],747:[function(require,module,exports){ +var $ = require('../internals/export'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); + +var ordinaryHasOwnMetadata = ReflectMetadataModule.has; +var ordinaryGetOwnMetadata = ReflectMetadataModule.get; +var toMetadataKey = ReflectMetadataModule.toKey; + +var ordinaryGetMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; +}; + +// `Reflect.getMetadata` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetadataKey(arguments[2]); + return ordinaryGetMetadata(metadataKey, anObject(target), targetKey); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/object-get-prototype-of":420,"../internals/reflect-metadata":436}],748:[function(require,module,exports){ +var $ = require('../internals/export'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); + +var ordinaryOwnMetadataKeys = ReflectMetadataModule.keys; +var toMetadataKey = ReflectMetadataModule.toKey; + +// `Reflect.getOwnMetadataKeys` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { + var targetKey = arguments.length < 2 ? undefined : toMetadataKey(arguments[1]); + return ordinaryOwnMetadataKeys(anObject(target), targetKey); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/reflect-metadata":436}],749:[function(require,module,exports){ +var $ = require('../internals/export'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); + +var ordinaryGetOwnMetadata = ReflectMetadataModule.get; +var toMetadataKey = ReflectMetadataModule.toKey; + +// `Reflect.getOwnMetadata` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetadataKey(arguments[2]); + return ordinaryGetOwnMetadata(metadataKey, anObject(target), targetKey); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/reflect-metadata":436}],750:[function(require,module,exports){ +var $ = require('../internals/export'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); +var getPrototypeOf = require('../internals/object-get-prototype-of'); + +var ordinaryHasOwnMetadata = ReflectMetadataModule.has; +var toMetadataKey = ReflectMetadataModule.toKey; + +var ordinaryHasMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return true; + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; +}; + +// `Reflect.hasMetadata` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetadataKey(arguments[2]); + return ordinaryHasMetadata(metadataKey, anObject(target), targetKey); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/object-get-prototype-of":420,"../internals/reflect-metadata":436}],751:[function(require,module,exports){ +var $ = require('../internals/export'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); + +var ordinaryHasOwnMetadata = ReflectMetadataModule.has; +var toMetadataKey = ReflectMetadataModule.toKey; + +// `Reflect.hasOwnMetadata` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetadataKey(arguments[2]); + return ordinaryHasOwnMetadata(metadataKey, anObject(target), targetKey); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/reflect-metadata":436}],752:[function(require,module,exports){ +var $ = require('../internals/export'); +var ReflectMetadataModule = require('../internals/reflect-metadata'); +var anObject = require('../internals/an-object'); + +var toMetadataKey = ReflectMetadataModule.toKey; +var ordinaryDefineOwnMetadata = ReflectMetadataModule.set; + +// `Reflect.metadata` method +// https://github.com/rbuckton/reflect-metadata +$({ target: 'Reflect', stat: true }, { + metadata: function metadata(metadataKey, metadataValue) { + return function decorator(target, key) { + ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetadataKey(key)); + }; + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/reflect-metadata":436}],753:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var collectionAddAll = require('../internals/collection-add-all'); + +// `Set.prototype.addAll` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + addAll: function addAll(/* ...elements */) { + return collectionAddAll.apply(this, arguments); + } +}); + +},{"../internals/collection-add-all":335,"../internals/export":361,"../internals/is-pure":393}],754:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var collectionDeleteAll = require('../internals/collection-delete-all'); + +// `Set.prototype.deleteAll` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + deleteAll: function deleteAll(/* ...elements */) { + return collectionDeleteAll.apply(this, arguments); + } +}); + +},{"../internals/collection-delete-all":336,"../internals/export":361,"../internals/is-pure":393}],755:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var speciesConstructor = require('../internals/species-constructor'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.difference` method +// https://github.com/tc39/proposal-set-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + difference: function difference(iterable) { + var set = anObject(this); + var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(set); + var remover = aFunction(newSet['delete']); + iterate(iterable, function (value) { + remover.call(newSet, value); + }); + return newSet; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/get-built-in":372,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],756:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var bind = require('../internals/bind-context'); +var getSetIterator = require('../internals/get-set-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.every` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + every: function every(callbackfn /* , thisArg */) { + var set = anObject(this); + var iterator = getSetIterator(set); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + return !iterate(iterator, function (value) { + if (!boundFunction(value, value, set)) return iterate.stop(); + }, undefined, false, true).stopped; + } +}); + +},{"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-set-iterator":376,"../internals/is-pure":393,"../internals/iterate":395}],757:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var bind = require('../internals/bind-context'); +var speciesConstructor = require('../internals/species-constructor'); +var getSetIterator = require('../internals/get-set-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.filter` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + filter: function filter(callbackfn /* , thisArg */) { + var set = anObject(this); + var iterator = getSetIterator(set); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(); + var adder = aFunction(newSet.add); + iterate(iterator, function (value) { + if (boundFunction(value, value, set)) adder.call(newSet, value); + }, undefined, false, true); + return newSet; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-built-in":372,"../internals/get-set-iterator":376,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],758:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var bind = require('../internals/bind-context'); +var getSetIterator = require('../internals/get-set-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.find` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + find: function find(callbackfn /* , thisArg */) { + var set = anObject(this); + var iterator = getSetIterator(set); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + return iterate(iterator, function (value) { + if (boundFunction(value, value, set)) return iterate.stop(value); + }, undefined, false, true).result; + } +}); + +},{"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-set-iterator":376,"../internals/is-pure":393,"../internals/iterate":395}],759:[function(require,module,exports){ +var $ = require('../internals/export'); +var from = require('../internals/collection-from'); + +// `Set.from` method +// https://tc39.github.io/proposal-setmap-offrom/#sec-set.from +$({ target: 'Set', stat: true }, { + from: from +}); + +},{"../internals/collection-from":337,"../internals/export":361}],760:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var speciesConstructor = require('../internals/species-constructor'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.intersection` method +// https://github.com/tc39/proposal-set-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + intersection: function intersection(iterable) { + var set = anObject(this); + var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(); + var hasCheck = aFunction(set.has); + var adder = aFunction(newSet.add); + iterate(iterable, function (value) { + if (hasCheck.call(set, value)) adder.call(newSet, value); + }); + return newSet; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/get-built-in":372,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],761:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.isDisjointFrom` method +// https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + isDisjointFrom: function isDisjointFrom(iterable) { + var set = anObject(this); + var hasCheck = aFunction(set.has); + return !iterate(iterable, function (value) { + if (hasCheck.call(set, value) === true) return iterate.stop(); + }).stopped; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/is-pure":393,"../internals/iterate":395}],762:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var getIterator = require('../internals/get-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.isSubsetOf` method +// https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + isSubsetOf: function isSubsetOf(iterable) { + var iterator = getIterator(this); + var otherSet = anObject(iterable); + var hasCheck = otherSet.has; + if (typeof hasCheck != 'function') { + otherSet = new (getBuiltIn('Set'))(iterable); + hasCheck = aFunction(otherSet.has); + } + return !iterate(iterator, function (value) { + if (hasCheck.call(otherSet, value) === false) return iterate.stop(); + }, undefined, false, true).stopped; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/get-built-in":372,"../internals/get-iterator":374,"../internals/is-pure":393,"../internals/iterate":395}],763:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.isSupersetOf` method +// https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + isSupersetOf: function isSupersetOf(iterable) { + var set = anObject(this); + var hasCheck = aFunction(set.has); + return !iterate(iterable, function (value) { + if (hasCheck.call(set, value) === false) return iterate.stop(); + }).stopped; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/is-pure":393,"../internals/iterate":395}],764:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var getSetIterator = require('../internals/get-set-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.join` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + join: function join(separator) { + var set = anObject(this); + var iterator = getSetIterator(set); + var sep = separator === undefined ? ',' : String(separator); + var result = []; + iterate(iterator, result.push, result, false, true); + return result.join(sep); + } +}); + +},{"../internals/an-object":315,"../internals/export":361,"../internals/get-set-iterator":376,"../internals/is-pure":393,"../internals/iterate":395}],765:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var bind = require('../internals/bind-context'); +var speciesConstructor = require('../internals/species-constructor'); +var getSetIterator = require('../internals/get-set-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.map` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + map: function map(callbackfn /* , thisArg */) { + var set = anObject(this); + var iterator = getSetIterator(set); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(); + var adder = aFunction(newSet.add); + iterate(iterator, function (value) { + adder.call(newSet, boundFunction(value, value, set)); + }, undefined, false, true); + return newSet; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-built-in":372,"../internals/get-set-iterator":376,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],766:[function(require,module,exports){ +var $ = require('../internals/export'); +var of = require('../internals/collection-of'); + +// `Set.of` method +// https://tc39.github.io/proposal-setmap-offrom/#sec-set.of +$({ target: 'Set', stat: true }, { + of: of +}); + +},{"../internals/collection-of":338,"../internals/export":361}],767:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var getSetIterator = require('../internals/get-set-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.reduce` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + reduce: function reduce(callbackfn /* , initialValue */) { + var set = anObject(this); + var iterator = getSetIterator(set); + var noInitial = arguments.length < 2; + var accumulator = noInitial ? undefined : arguments[1]; + aFunction(callbackfn); + iterate(iterator, function (value) { + if (noInitial) { + noInitial = false; + accumulator = value; + } else { + accumulator = callbackfn(accumulator, value, value, set); + } + }, undefined, false, true); + if (noInitial) throw TypeError('Reduce of empty set with no initial value'); + return accumulator; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/get-set-iterator":376,"../internals/is-pure":393,"../internals/iterate":395}],768:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var anObject = require('../internals/an-object'); +var bind = require('../internals/bind-context'); +var getSetIterator = require('../internals/get-set-iterator'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.some` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + some: function some(callbackfn /* , thisArg */) { + var set = anObject(this); + var iterator = getSetIterator(set); + var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + return iterate(iterator, function (value) { + if (boundFunction(value, value, set)) return iterate.stop(); + }, undefined, false, true).stopped; + } +}); + +},{"../internals/an-object":315,"../internals/bind-context":330,"../internals/export":361,"../internals/get-set-iterator":376,"../internals/is-pure":393,"../internals/iterate":395}],769:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var speciesConstructor = require('../internals/species-constructor'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.symmetricDifference` method +// https://github.com/tc39/proposal-set-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + symmetricDifference: function symmetricDifference(iterable) { + var set = anObject(this); + var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(set); + var remover = aFunction(newSet['delete']); + var adder = aFunction(newSet.add); + iterate(iterable, function (value) { + remover.call(newSet, value) || adder.call(newSet, value); + }); + return newSet; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/get-built-in":372,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],770:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var getBuiltIn = require('../internals/get-built-in'); +var anObject = require('../internals/an-object'); +var aFunction = require('../internals/a-function'); +var speciesConstructor = require('../internals/species-constructor'); +var iterate = require('../internals/iterate'); + +// `Set.prototype.union` method +// https://github.com/tc39/proposal-set-methods +$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, { + union: function union(iterable) { + var set = anObject(this); + var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(set); + iterate(iterable, aFunction(newSet.add), newSet); + return newSet; + } +}); + +},{"../internals/a-function":310,"../internals/an-object":315,"../internals/export":361,"../internals/get-built-in":372,"../internals/is-pure":393,"../internals/iterate":395,"../internals/species-constructor":450}],771:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var charAt = require('../internals/string-multibyte').charAt; + +// `String.prototype.at` method +// https://github.com/mathiasbynens/String.prototype.at +$({ target: 'String', proto: true }, { + at: function at(pos) { + return charAt(this, pos); + } +}); + +},{"../internals/export":361,"../internals/string-multibyte":451}],772:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var createIteratorConstructor = require('../internals/create-iterator-constructor'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var InternalStateModule = require('../internals/internal-state'); +var StringMultibyteModule = require('../internals/string-multibyte'); + +var codeAt = StringMultibyteModule.codeAt; +var charAt = StringMultibyteModule.charAt; +var STRING_ITERATOR = 'String Iterator'; +var setInternalState = InternalStateModule.set; +var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); + +// TODO: unify with String#@@iterator +var $StringIterator = createIteratorConstructor(function StringIterator(string) { + setInternalState(this, { + type: STRING_ITERATOR, + string: string, + index: 0 + }); +}, 'String', function next() { + var state = getInternalState(this); + var string = state.string; + var index = state.index; + var point; + if (index >= string.length) return { value: undefined, done: true }; + point = charAt(string, index); + state.index += point.length; + return { value: { codePoint: codeAt(point, 0), position: index }, done: false }; +}); + +// `String.prototype.codePoints` method +// https://github.com/tc39/proposal-string-prototype-codepoints +$({ target: 'String', proto: true }, { + codePoints: function codePoints() { + return new $StringIterator(String(requireObjectCoercible(this))); + } +}); + +},{"../internals/create-iterator-constructor":348,"../internals/export":361,"../internals/internal-state":386,"../internals/require-object-coercible":440,"../internals/string-multibyte":451}],773:[function(require,module,exports){ +// TODO: Remove from `core-js@4` +require('./es.string.match-all'); + +},{"./es.string.match-all":612}],774:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var requireObjectCoercible = require('../internals/require-object-coercible'); +var isRegExp = require('../internals/is-regexp'); +var getRegExpFlags = require('../internals/regexp-flags'); +var wellKnownSymbol = require('../internals/well-known-symbol'); +var IS_PURE = require('../internals/is-pure'); + +var REPLACE = wellKnownSymbol('replace'); +var RegExpPrototype = RegExp.prototype; + +// `String.prototype.replaceAll` method +// https://github.com/tc39/proposal-string-replace-all +$({ target: 'String', proto: true }, { + replaceAll: function replaceAll(searchValue, replaceValue) { + var O = requireObjectCoercible(this); + var IS_REG_EXP, flags, replacer, string, searchString, template, result, position, index; + if (searchValue != null) { + IS_REG_EXP = isRegExp(searchValue); + if (IS_REG_EXP) { + flags = String(requireObjectCoercible('flags' in RegExpPrototype + ? searchValue.flags + : getRegExpFlags.call(searchValue) + )); + if (!~flags.indexOf('g')) throw TypeError('`.replaceAll` does not allow non-global regexes'); + } + replacer = searchValue[REPLACE]; + if (replacer !== undefined) { + return replacer.call(searchValue, O, replaceValue); + } else if (IS_PURE && IS_REG_EXP) { + return String(O).replace(searchValue, replaceValue); + } + } + string = String(O); + searchString = String(searchValue); + if (searchString === '') return replaceAll.call(string, /(?:)/g, replaceValue); + template = string.split(searchString); + if (typeof replaceValue !== 'function') { + return template.join(String(replaceValue)); + } + result = template[0]; + position = result.length; + for (index = 1; index < template.length; index++) { + result += String(replaceValue(searchString, position, string)); + position += searchString.length + template[index].length; + result += template[index]; + } + return result; + } +}); + +},{"../internals/export":361,"../internals/is-pure":393,"../internals/is-regexp":394,"../internals/regexp-flags":439,"../internals/require-object-coercible":440,"../internals/well-known-symbol":473}],775:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.asyncDispose` well-known symbol +// https://github.com/tc39/proposal-using-statement +defineWellKnownSymbol('asyncDispose'); + +},{"../internals/define-well-known-symbol":356}],776:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.dispose` well-known symbol +// https://github.com/tc39/proposal-using-statement +defineWellKnownSymbol('dispose'); + +},{"../internals/define-well-known-symbol":356}],777:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.observable` well-known symbol +// https://github.com/tc39/proposal-observable +defineWellKnownSymbol('observable'); + +},{"../internals/define-well-known-symbol":356}],778:[function(require,module,exports){ +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +// `Symbol.patternMatch` well-known symbol +// https://github.com/tc39/proposal-pattern-matching +defineWellKnownSymbol('patternMatch'); + +},{"../internals/define-well-known-symbol":356}],779:[function(require,module,exports){ +// TODO: remove from `core-js@4` +var defineWellKnownSymbol = require('../internals/define-well-known-symbol'); + +defineWellKnownSymbol('replaceAll'); + +},{"../internals/define-well-known-symbol":356}],780:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var collectionDeleteAll = require('../internals/collection-delete-all'); + +// `WeakMap.prototype.deleteAll` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'WeakMap', proto: true, real: true, forced: IS_PURE }, { + deleteAll: function deleteAll(/* ...elements */) { + return collectionDeleteAll.apply(this, arguments); + } +}); + +},{"../internals/collection-delete-all":336,"../internals/export":361,"../internals/is-pure":393}],781:[function(require,module,exports){ +var $ = require('../internals/export'); +var from = require('../internals/collection-from'); + +// `WeakMap.from` method +// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from +$({ target: 'WeakMap', stat: true }, { + from: from +}); + +},{"../internals/collection-from":337,"../internals/export":361}],782:[function(require,module,exports){ +var $ = require('../internals/export'); +var of = require('../internals/collection-of'); + +// `WeakMap.of` method +// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of +$({ target: 'WeakMap', stat: true }, { + of: of +}); + +},{"../internals/collection-of":338,"../internals/export":361}],783:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var $upsert = require('../internals/map-upsert'); + +// `WeakMap.prototype.upsert` method +// https://github.com/thumbsupep/proposal-upsert +$({ target: 'WeakMap', proto: true, real: true, forced: IS_PURE }, { + upsert: $upsert +}); + +},{"../internals/export":361,"../internals/is-pure":393,"../internals/map-upsert":398}],784:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var collectionAddAll = require('../internals/collection-add-all'); + +// `WeakSet.prototype.addAll` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'WeakSet', proto: true, real: true, forced: IS_PURE }, { + addAll: function addAll(/* ...elements */) { + return collectionAddAll.apply(this, arguments); + } +}); + +},{"../internals/collection-add-all":335,"../internals/export":361,"../internals/is-pure":393}],785:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); +var IS_PURE = require('../internals/is-pure'); +var collectionDeleteAll = require('../internals/collection-delete-all'); + +// `WeakSet.prototype.deleteAll` method +// https://github.com/tc39/proposal-collection-methods +$({ target: 'WeakSet', proto: true, real: true, forced: IS_PURE }, { + deleteAll: function deleteAll(/* ...elements */) { + return collectionDeleteAll.apply(this, arguments); + } +}); + +},{"../internals/collection-delete-all":336,"../internals/export":361,"../internals/is-pure":393}],786:[function(require,module,exports){ +var $ = require('../internals/export'); +var from = require('../internals/collection-from'); + +// `WeakSet.from` method +// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from +$({ target: 'WeakSet', stat: true }, { + from: from +}); + +},{"../internals/collection-from":337,"../internals/export":361}],787:[function(require,module,exports){ +var $ = require('../internals/export'); +var of = require('../internals/collection-of'); + +// `WeakSet.of` method +// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of +$({ target: 'WeakSet', stat: true }, { + of: of +}); + +},{"../internals/collection-of":338,"../internals/export":361}],788:[function(require,module,exports){ +var global = require('../internals/global'); +var DOMIterables = require('../internals/dom-iterables'); +var forEach = require('../internals/array-for-each'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); + +for (var COLLECTION_NAME in DOMIterables) { + var Collection = global[COLLECTION_NAME]; + var CollectionPrototype = Collection && Collection.prototype; + // some Chrome versions have non-configurable methods on DOMTokenList + if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try { + createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach); + } catch (error) { + CollectionPrototype.forEach = forEach; + } +} + +},{"../internals/array-for-each":320,"../internals/create-non-enumerable-property":350,"../internals/dom-iterables":359,"../internals/global":377}],789:[function(require,module,exports){ +var global = require('../internals/global'); +var DOMIterables = require('../internals/dom-iterables'); +var ArrayIteratorMethods = require('../modules/es.array.iterator'); +var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var ITERATOR = wellKnownSymbol('iterator'); +var TO_STRING_TAG = wellKnownSymbol('toStringTag'); +var ArrayValues = ArrayIteratorMethods.values; + +for (var COLLECTION_NAME in DOMIterables) { + var Collection = global[COLLECTION_NAME]; + var CollectionPrototype = Collection && Collection.prototype; + if (CollectionPrototype) { + // some Chrome versions have non-configurable methods on DOMTokenList + if (CollectionPrototype[ITERATOR] !== ArrayValues) try { + createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues); + } catch (error) { + CollectionPrototype[ITERATOR] = ArrayValues; + } + if (!CollectionPrototype[TO_STRING_TAG]) { + createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME); + } + if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) { + // some Chrome versions have non-configurable methods on DOMTokenList + if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try { + createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]); + } catch (error) { + CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME]; + } + } + } +} + +},{"../internals/create-non-enumerable-property":350,"../internals/dom-iterables":359,"../internals/global":377,"../internals/well-known-symbol":473,"../modules/es.array.iterator":493}],790:[function(require,module,exports){ +var global = require('../internals/global'); +var task = require('../internals/task'); + +var FORCED = !global.setImmediate || !global.clearImmediate; + +// http://w3c.github.io/setImmediate/ +require('../internals/export')({ global: true, bind: true, enumerable: true, forced: FORCED }, { + // `setImmediate` method + // http://w3c.github.io/setImmediate/#si-setImmediate + setImmediate: task.set, + // `clearImmediate` method + // http://w3c.github.io/setImmediate/#si-clearImmediate + clearImmediate: task.clear +}); + +},{"../internals/export":361,"../internals/global":377,"../internals/task":455}],791:[function(require,module,exports){ +var $ = require('../internals/export'); +var global = require('../internals/global'); +var microtask = require('../internals/microtask'); +var classof = require('../internals/classof-raw'); + +var process = global.process; +var isNode = classof(process) == 'process'; + +// `queueMicrotask` method +// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask +$({ global: true, enumerable: true, noTargetGet: true }, { + queueMicrotask: function queueMicrotask(fn) { + var domain = isNode && process.domain; + microtask(domain ? domain.bind(fn) : fn); + } +}); + +},{"../internals/classof-raw":333,"../internals/export":361,"../internals/global":377,"../internals/microtask":404}],792:[function(require,module,exports){ +var $ = require('../internals/export'); +var global = require('../internals/global'); +var userAgent = require('../internals/user-agent'); + +var slice = [].slice; +var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check + +var wrap = function (scheduler) { + return function (handler, timeout /* , ...arguments */) { + var boundArgs = arguments.length > 2; + var args = boundArgs ? slice.call(arguments, 2) : undefined; + return scheduler(boundArgs ? function () { + // eslint-disable-next-line no-new-func + (typeof handler == 'function' ? handler : Function(handler)).apply(this, args); + } : handler, timeout); + }; +}; + +// ie9- setTimeout & setInterval additional parameters fix +// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers +$({ global: true, bind: true, forced: MSIE }, { + // `setTimeout` method + // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout + setTimeout: wrap(global.setTimeout), + // `setInterval` method + // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval + setInterval: wrap(global.setInterval) +}); + +},{"../internals/export":361,"../internals/global":377,"../internals/user-agent":470}],793:[function(require,module,exports){ +'use strict'; +// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` +require('../modules/es.array.iterator'); +var $ = require('../internals/export'); +var getBuiltIn = require('../internals/get-built-in'); +var USE_NATIVE_URL = require('../internals/native-url'); +var redefine = require('../internals/redefine'); +var redefineAll = require('../internals/redefine-all'); +var setToStringTag = require('../internals/set-to-string-tag'); +var createIteratorConstructor = require('../internals/create-iterator-constructor'); +var InternalStateModule = require('../internals/internal-state'); +var anInstance = require('../internals/an-instance'); +var hasOwn = require('../internals/has'); +var bind = require('../internals/bind-context'); +var classof = require('../internals/classof'); +var anObject = require('../internals/an-object'); +var isObject = require('../internals/is-object'); +var create = require('../internals/object-create'); +var createPropertyDescriptor = require('../internals/create-property-descriptor'); +var getIterator = require('../internals/get-iterator'); +var getIteratorMethod = require('../internals/get-iterator-method'); +var wellKnownSymbol = require('../internals/well-known-symbol'); + +var $fetch = getBuiltIn('fetch'); +var Headers = getBuiltIn('Headers'); +var ITERATOR = wellKnownSymbol('iterator'); +var URL_SEARCH_PARAMS = 'URLSearchParams'; +var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator'; +var setInternalState = InternalStateModule.set; +var getInternalParamsState = InternalStateModule.getterFor(URL_SEARCH_PARAMS); +var getInternalIteratorState = InternalStateModule.getterFor(URL_SEARCH_PARAMS_ITERATOR); + +var plus = /\+/g; +var sequences = Array(4); + +var percentSequence = function (bytes) { + return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi')); +}; + +var percentDecode = function (sequence) { + try { + return decodeURIComponent(sequence); + } catch (error) { + return sequence; + } +}; + +var deserialize = function (it) { + var result = it.replace(plus, ' '); + var bytes = 4; + try { + return decodeURIComponent(result); + } catch (error) { + while (bytes) { + result = result.replace(percentSequence(bytes--), percentDecode); + } + return result; + } +}; + +var find = /[!'()~]|%20/g; + +var replace = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+' +}; + +var replacer = function (match) { + return replace[match]; +}; + +var serialize = function (it) { + return encodeURIComponent(it).replace(find, replacer); +}; + +var parseSearchParams = function (result, query) { + if (query) { + var attributes = query.split('&'); + var index = 0; + var attribute, entry; + while (index < attributes.length) { + attribute = attributes[index++]; + if (attribute.length) { + entry = attribute.split('='); + result.push({ + key: deserialize(entry.shift()), + value: deserialize(entry.join('=')) + }); + } + } + } +}; + +var updateSearchParams = function (query) { + this.entries.length = 0; + parseSearchParams(this.entries, query); +}; + +var validateArgumentsLength = function (passed, required) { + if (passed < required) throw TypeError('Not enough arguments'); +}; + +var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) { + setInternalState(this, { + type: URL_SEARCH_PARAMS_ITERATOR, + iterator: getIterator(getInternalParamsState(params).entries), + kind: kind + }); +}, 'Iterator', function next() { + var state = getInternalIteratorState(this); + var kind = state.kind; + var step = state.iterator.next(); + var entry = step.value; + if (!step.done) { + step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value]; + } return step; +}); + +// `URLSearchParams` constructor +// https://url.spec.whatwg.org/#interface-urlsearchparams +var URLSearchParamsConstructor = function URLSearchParams(/* init */) { + anInstance(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS); + var init = arguments.length > 0 ? arguments[0] : undefined; + var that = this; + var entries = []; + var iteratorMethod, iterator, next, step, entryIterator, entryNext, first, second, key; + + setInternalState(that, { + type: URL_SEARCH_PARAMS, + entries: entries, + updateURL: function () { /* empty */ }, + updateSearchParams: updateSearchParams + }); + + if (init !== undefined) { + if (isObject(init)) { + iteratorMethod = getIteratorMethod(init); + if (typeof iteratorMethod === 'function') { + iterator = iteratorMethod.call(init); + next = iterator.next; + while (!(step = next.call(iterator)).done) { + entryIterator = getIterator(anObject(step.value)); + entryNext = entryIterator.next; + if ( + (first = entryNext.call(entryIterator)).done || + (second = entryNext.call(entryIterator)).done || + !entryNext.call(entryIterator).done + ) throw TypeError('Expected sequence with length 2'); + entries.push({ key: first.value + '', value: second.value + '' }); + } + } else for (key in init) if (hasOwn(init, key)) entries.push({ key: key, value: init[key] + '' }); + } else { + parseSearchParams(entries, typeof init === 'string' ? init.charAt(0) === '?' ? init.slice(1) : init : init + ''); + } + } +}; + +var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype; + +redefineAll(URLSearchParamsPrototype, { + // `URLSearchParams.prototype.appent` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-append + append: function append(name, value) { + validateArgumentsLength(arguments.length, 2); + var state = getInternalParamsState(this); + state.entries.push({ key: name + '', value: value + '' }); + state.updateURL(); + }, + // `URLSearchParams.prototype.delete` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-delete + 'delete': function (name) { + validateArgumentsLength(arguments.length, 1); + var state = getInternalParamsState(this); + var entries = state.entries; + var key = name + ''; + var index = 0; + while (index < entries.length) { + if (entries[index].key === key) entries.splice(index, 1); + else index++; + } + state.updateURL(); + }, + // `URLSearchParams.prototype.get` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-get + get: function get(name) { + validateArgumentsLength(arguments.length, 1); + var entries = getInternalParamsState(this).entries; + var key = name + ''; + var index = 0; + for (; index < entries.length; index++) { + if (entries[index].key === key) return entries[index].value; + } + return null; + }, + // `URLSearchParams.prototype.getAll` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-getall + getAll: function getAll(name) { + validateArgumentsLength(arguments.length, 1); + var entries = getInternalParamsState(this).entries; + var key = name + ''; + var result = []; + var index = 0; + for (; index < entries.length; index++) { + if (entries[index].key === key) result.push(entries[index].value); + } + return result; + }, + // `URLSearchParams.prototype.has` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-has + has: function has(name) { + validateArgumentsLength(arguments.length, 1); + var entries = getInternalParamsState(this).entries; + var key = name + ''; + var index = 0; + while (index < entries.length) { + if (entries[index++].key === key) return true; + } + return false; + }, + // `URLSearchParams.prototype.set` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-set + set: function set(name, value) { + validateArgumentsLength(arguments.length, 1); + var state = getInternalParamsState(this); + var entries = state.entries; + var found = false; + var key = name + ''; + var val = value + ''; + var index = 0; + var entry; + for (; index < entries.length; index++) { + entry = entries[index]; + if (entry.key === key) { + if (found) entries.splice(index--, 1); + else { + found = true; + entry.value = val; + } + } + } + if (!found) entries.push({ key: key, value: val }); + state.updateURL(); + }, + // `URLSearchParams.prototype.sort` method + // https://url.spec.whatwg.org/#dom-urlsearchparams-sort + sort: function sort() { + var state = getInternalParamsState(this); + var entries = state.entries; + // Array#sort is not stable in some engines + var slice = entries.slice(); + var entry, entriesIndex, sliceIndex; + entries.length = 0; + for (sliceIndex = 0; sliceIndex < slice.length; sliceIndex++) { + entry = slice[sliceIndex]; + for (entriesIndex = 0; entriesIndex < sliceIndex; entriesIndex++) { + if (entries[entriesIndex].key > entry.key) { + entries.splice(entriesIndex, 0, entry); + break; + } + } + if (entriesIndex === sliceIndex) entries.push(entry); + } + state.updateURL(); + }, + // `URLSearchParams.prototype.forEach` method + forEach: function forEach(callback /* , thisArg */) { + var entries = getInternalParamsState(this).entries; + var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3); + var index = 0; + var entry; + while (index < entries.length) { + entry = entries[index++]; + boundFunction(entry.value, entry.key, this); + } + }, + // `URLSearchParams.prototype.keys` method + keys: function keys() { + return new URLSearchParamsIterator(this, 'keys'); + }, + // `URLSearchParams.prototype.values` method + values: function values() { + return new URLSearchParamsIterator(this, 'values'); + }, + // `URLSearchParams.prototype.entries` method + entries: function entries() { + return new URLSearchParamsIterator(this, 'entries'); + } +}, { enumerable: true }); + +// `URLSearchParams.prototype[@@iterator]` method +redefine(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries); + +// `URLSearchParams.prototype.toString` method +// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior +redefine(URLSearchParamsPrototype, 'toString', function toString() { + var entries = getInternalParamsState(this).entries; + var result = []; + var index = 0; + var entry; + while (index < entries.length) { + entry = entries[index++]; + result.push(serialize(entry.key) + '=' + serialize(entry.value)); + } return result.join('&'); +}, { enumerable: true }); + +setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS); + +$({ global: true, forced: !USE_NATIVE_URL }, { + URLSearchParams: URLSearchParamsConstructor +}); + +// Wrap `fetch` for correct work with polyfilled `URLSearchParams` +// https://github.com/zloirock/core-js/issues/674 +if (!USE_NATIVE_URL && typeof $fetch == 'function' && typeof Headers == 'function') { + $({ global: true, enumerable: true, forced: true }, { + fetch: function fetch(input /* , init */) { + var args = [input]; + var init, body, headers; + if (arguments.length > 1) { + init = arguments[1]; + if (isObject(init)) { + body = init.body; + if (classof(body) === URL_SEARCH_PARAMS) { + headers = init.headers ? new Headers(init.headers) : new Headers(); + if (!headers.has('content-type')) { + headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + init = create(init, { + body: createPropertyDescriptor(0, String(body)), + headers: createPropertyDescriptor(0, headers) + }); + } + } + args.push(init); + } return $fetch.apply(this, args); + } + }); +} + +module.exports = { + URLSearchParams: URLSearchParamsConstructor, + getState: getInternalParamsState +}; + +},{"../internals/an-instance":314,"../internals/an-object":315,"../internals/bind-context":330,"../internals/classof":334,"../internals/create-iterator-constructor":348,"../internals/create-property-descriptor":351,"../internals/export":361,"../internals/get-built-in":372,"../internals/get-iterator":374,"../internals/get-iterator-method":373,"../internals/has":378,"../internals/internal-state":386,"../internals/is-object":392,"../internals/native-url":407,"../internals/object-create":413,"../internals/redefine":435,"../internals/redefine-all":434,"../internals/set-to-string-tag":445,"../internals/well-known-symbol":473,"../modules/es.array.iterator":493}],794:[function(require,module,exports){ +'use strict'; +// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` +require('../modules/es.string.iterator'); +var $ = require('../internals/export'); +var DESCRIPTORS = require('../internals/descriptors'); +var USE_NATIVE_URL = require('../internals/native-url'); +var global = require('../internals/global'); +var defineProperties = require('../internals/object-define-properties'); +var redefine = require('../internals/redefine'); +var anInstance = require('../internals/an-instance'); +var has = require('../internals/has'); +var assign = require('../internals/object-assign'); +var arrayFrom = require('../internals/array-from'); +var codeAt = require('../internals/string-multibyte').codeAt; +var toASCII = require('../internals/punycode-to-ascii'); +var setToStringTag = require('../internals/set-to-string-tag'); +var URLSearchParamsModule = require('../modules/web.url-search-params'); +var InternalStateModule = require('../internals/internal-state'); + +var NativeURL = global.URL; +var URLSearchParams = URLSearchParamsModule.URLSearchParams; +var getInternalSearchParamsState = URLSearchParamsModule.getState; +var setInternalState = InternalStateModule.set; +var getInternalURLState = InternalStateModule.getterFor('URL'); +var floor = Math.floor; +var pow = Math.pow; + +var INVALID_AUTHORITY = 'Invalid authority'; +var INVALID_SCHEME = 'Invalid scheme'; +var INVALID_HOST = 'Invalid host'; +var INVALID_PORT = 'Invalid port'; + +var ALPHA = /[A-Za-z]/; +var ALPHANUMERIC = /[\d+\-.A-Za-z]/; +var DIGIT = /\d/; +var HEX_START = /^(0x|0X)/; +var OCT = /^[0-7]+$/; +var DEC = /^\d+$/; +var HEX = /^[\dA-Fa-f]+$/; +// eslint-disable-next-line no-control-regex +var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/; +// eslint-disable-next-line no-control-regex +var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/; +// eslint-disable-next-line no-control-regex +var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g; +// eslint-disable-next-line no-control-regex +var TAB_AND_NEW_LINE = /[\u0009\u000A\u000D]/g; +var EOF; + +var parseHost = function (url, input) { + var result, codePoints, index; + if (input.charAt(0) == '[') { + if (input.charAt(input.length - 1) != ']') return INVALID_HOST; + result = parseIPv6(input.slice(1, -1)); + if (!result) return INVALID_HOST; + url.host = result; + // opaque host + } else if (!isSpecial(url)) { + if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST; + result = ''; + codePoints = arrayFrom(input); + for (index = 0; index < codePoints.length; index++) { + result += percentEncode(codePoints[index], C0ControlPercentEncodeSet); + } + url.host = result; + } else { + input = toASCII(input); + if (FORBIDDEN_HOST_CODE_POINT.test(input)) return INVALID_HOST; + result = parseIPv4(input); + if (result === null) return INVALID_HOST; + url.host = result; + } +}; + +var parseIPv4 = function (input) { + var parts = input.split('.'); + var partsLength, numbers, index, part, radix, number, ipv4; + if (parts.length && parts[parts.length - 1] == '') { + parts.pop(); + } + partsLength = parts.length; + if (partsLength > 4) return input; + numbers = []; + for (index = 0; index < partsLength; index++) { + part = parts[index]; + if (part == '') return input; + radix = 10; + if (part.length > 1 && part.charAt(0) == '0') { + radix = HEX_START.test(part) ? 16 : 8; + part = part.slice(radix == 8 ? 1 : 2); + } + if (part === '') { + number = 0; + } else { + if (!(radix == 10 ? DEC : radix == 8 ? OCT : HEX).test(part)) return input; + number = parseInt(part, radix); + } + numbers.push(number); + } + for (index = 0; index < partsLength; index++) { + number = numbers[index]; + if (index == partsLength - 1) { + if (number >= pow(256, 5 - partsLength)) return null; + } else if (number > 255) return null; + } + ipv4 = numbers.pop(); + for (index = 0; index < numbers.length; index++) { + ipv4 += numbers[index] * pow(256, 3 - index); + } + return ipv4; +}; + +// eslint-disable-next-line max-statements +var parseIPv6 = function (input) { + var address = [0, 0, 0, 0, 0, 0, 0, 0]; + var pieceIndex = 0; + var compress = null; + var pointer = 0; + var value, length, numbersSeen, ipv4Piece, number, swaps, swap; + + var char = function () { + return input.charAt(pointer); + }; + + if (char() == ':') { + if (input.charAt(1) != ':') return; + pointer += 2; + pieceIndex++; + compress = pieceIndex; + } + while (char()) { + if (pieceIndex == 8) return; + if (char() == ':') { + if (compress !== null) return; + pointer++; + pieceIndex++; + compress = pieceIndex; + continue; + } + value = length = 0; + while (length < 4 && HEX.test(char())) { + value = value * 16 + parseInt(char(), 16); + pointer++; + length++; + } + if (char() == '.') { + if (length == 0) return; + pointer -= length; + if (pieceIndex > 6) return; + numbersSeen = 0; + while (char()) { + ipv4Piece = null; + if (numbersSeen > 0) { + if (char() == '.' && numbersSeen < 4) pointer++; + else return; + } + if (!DIGIT.test(char())) return; + while (DIGIT.test(char())) { + number = parseInt(char(), 10); + if (ipv4Piece === null) ipv4Piece = number; + else if (ipv4Piece == 0) return; + else ipv4Piece = ipv4Piece * 10 + number; + if (ipv4Piece > 255) return; + pointer++; + } + address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece; + numbersSeen++; + if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++; + } + if (numbersSeen != 4) return; + break; + } else if (char() == ':') { + pointer++; + if (!char()) return; + } else if (char()) return; + address[pieceIndex++] = value; + } + if (compress !== null) { + swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex != 0 && swaps > 0) { + swap = address[pieceIndex]; + address[pieceIndex--] = address[compress + swaps - 1]; + address[compress + --swaps] = swap; + } + } else if (pieceIndex != 8) return; + return address; +}; + +var findLongestZeroSequence = function (ipv6) { + var maxIndex = null; + var maxLength = 1; + var currStart = null; + var currLength = 0; + var index = 0; + for (; index < 8; index++) { + if (ipv6[index] !== 0) { + if (currLength > maxLength) { + maxIndex = currStart; + maxLength = currLength; + } + currStart = null; + currLength = 0; + } else { + if (currStart === null) currStart = index; + ++currLength; + } + } + if (currLength > maxLength) { + maxIndex = currStart; + maxLength = currLength; + } + return maxIndex; +}; + +var serializeHost = function (host) { + var result, index, compress, ignore0; + // ipv4 + if (typeof host == 'number') { + result = []; + for (index = 0; index < 4; index++) { + result.unshift(host % 256); + host = floor(host / 256); + } return result.join('.'); + // ipv6 + } else if (typeof host == 'object') { + result = ''; + compress = findLongestZeroSequence(host); + for (index = 0; index < 8; index++) { + if (ignore0 && host[index] === 0) continue; + if (ignore0) ignore0 = false; + if (compress === index) { + result += index ? ':' : '::'; + ignore0 = true; + } else { + result += host[index].toString(16); + if (index < 7) result += ':'; + } + } + return '[' + result + ']'; + } return host; +}; + +var C0ControlPercentEncodeSet = {}; +var fragmentPercentEncodeSet = assign({}, C0ControlPercentEncodeSet, { + ' ': 1, '"': 1, '<': 1, '>': 1, '`': 1 +}); +var pathPercentEncodeSet = assign({}, fragmentPercentEncodeSet, { + '#': 1, '?': 1, '{': 1, '}': 1 +}); +var userinfoPercentEncodeSet = assign({}, pathPercentEncodeSet, { + '/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1 +}); + +var percentEncode = function (char, set) { + var code = codeAt(char, 0); + return code > 0x20 && code < 0x7F && !has(set, char) ? char : encodeURIComponent(char); +}; + +var specialSchemes = { + ftp: 21, + file: null, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +var isSpecial = function (url) { + return has(specialSchemes, url.scheme); +}; + +var includesCredentials = function (url) { + return url.username != '' || url.password != ''; +}; + +var cannotHaveUsernamePasswordPort = function (url) { + return !url.host || url.cannotBeABaseURL || url.scheme == 'file'; +}; + +var isWindowsDriveLetter = function (string, normalized) { + var second; + return string.length == 2 && ALPHA.test(string.charAt(0)) + && ((second = string.charAt(1)) == ':' || (!normalized && second == '|')); +}; + +var startsWithWindowsDriveLetter = function (string) { + var third; + return string.length > 1 && isWindowsDriveLetter(string.slice(0, 2)) && ( + string.length == 2 || + ((third = string.charAt(2)) === '/' || third === '\\' || third === '?' || third === '#') + ); +}; + +var shortenURLsPath = function (url) { + var path = url.path; + var pathSize = path.length; + if (pathSize && (url.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) { + path.pop(); + } +}; + +var isSingleDot = function (segment) { + return segment === '.' || segment.toLowerCase() === '%2e'; +}; + +var isDoubleDot = function (segment) { + segment = segment.toLowerCase(); + return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e'; +}; + +// States: +var SCHEME_START = {}; +var SCHEME = {}; +var NO_SCHEME = {}; +var SPECIAL_RELATIVE_OR_AUTHORITY = {}; +var PATH_OR_AUTHORITY = {}; +var RELATIVE = {}; +var RELATIVE_SLASH = {}; +var SPECIAL_AUTHORITY_SLASHES = {}; +var SPECIAL_AUTHORITY_IGNORE_SLASHES = {}; +var AUTHORITY = {}; +var HOST = {}; +var HOSTNAME = {}; +var PORT = {}; +var FILE = {}; +var FILE_SLASH = {}; +var FILE_HOST = {}; +var PATH_START = {}; +var PATH = {}; +var CANNOT_BE_A_BASE_URL_PATH = {}; +var QUERY = {}; +var FRAGMENT = {}; + +// eslint-disable-next-line max-statements +var parseURL = function (url, input, stateOverride, base) { + var state = stateOverride || SCHEME_START; + var pointer = 0; + var buffer = ''; + var seenAt = false; + var seenBracket = false; + var seenPasswordToken = false; + var codePoints, char, bufferCodePoints, failure; + + if (!stateOverride) { + url.scheme = ''; + url.username = ''; + url.password = ''; + url.host = null; + url.port = null; + url.path = []; + url.query = null; + url.fragment = null; + url.cannotBeABaseURL = false; + input = input.replace(LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, ''); + } + + input = input.replace(TAB_AND_NEW_LINE, ''); + + codePoints = arrayFrom(input); + + while (pointer <= codePoints.length) { + char = codePoints[pointer]; + switch (state) { + case SCHEME_START: + if (char && ALPHA.test(char)) { + buffer += char.toLowerCase(); + state = SCHEME; + } else if (!stateOverride) { + state = NO_SCHEME; + continue; + } else return INVALID_SCHEME; + break; + + case SCHEME: + if (char && (ALPHANUMERIC.test(char) || char == '+' || char == '-' || char == '.')) { + buffer += char.toLowerCase(); + } else if (char == ':') { + if (stateOverride && ( + (isSpecial(url) != has(specialSchemes, buffer)) || + (buffer == 'file' && (includesCredentials(url) || url.port !== null)) || + (url.scheme == 'file' && !url.host) + )) return; + url.scheme = buffer; + if (stateOverride) { + if (isSpecial(url) && specialSchemes[url.scheme] == url.port) url.port = null; + return; + } + buffer = ''; + if (url.scheme == 'file') { + state = FILE; + } else if (isSpecial(url) && base && base.scheme == url.scheme) { + state = SPECIAL_RELATIVE_OR_AUTHORITY; + } else if (isSpecial(url)) { + state = SPECIAL_AUTHORITY_SLASHES; + } else if (codePoints[pointer + 1] == '/') { + state = PATH_OR_AUTHORITY; + pointer++; + } else { + url.cannotBeABaseURL = true; + url.path.push(''); + state = CANNOT_BE_A_BASE_URL_PATH; + } + } else if (!stateOverride) { + buffer = ''; + state = NO_SCHEME; + pointer = 0; + continue; + } else return INVALID_SCHEME; + break; + + case NO_SCHEME: + if (!base || (base.cannotBeABaseURL && char != '#')) return INVALID_SCHEME; + if (base.cannotBeABaseURL && char == '#') { + url.scheme = base.scheme; + url.path = base.path.slice(); + url.query = base.query; + url.fragment = ''; + url.cannotBeABaseURL = true; + state = FRAGMENT; + break; + } + state = base.scheme == 'file' ? FILE : RELATIVE; + continue; + + case SPECIAL_RELATIVE_OR_AUTHORITY: + if (char == '/' && codePoints[pointer + 1] == '/') { + state = SPECIAL_AUTHORITY_IGNORE_SLASHES; + pointer++; + } else { + state = RELATIVE; + continue; + } break; + + case PATH_OR_AUTHORITY: + if (char == '/') { + state = AUTHORITY; + break; + } else { + state = PATH; + continue; + } + + case RELATIVE: + url.scheme = base.scheme; + if (char == EOF) { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + url.path = base.path.slice(); + url.query = base.query; + } else if (char == '/' || (char == '\\' && isSpecial(url))) { + state = RELATIVE_SLASH; + } else if (char == '?') { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + url.path = base.path.slice(); + url.query = ''; + state = QUERY; + } else if (char == '#') { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + url.path = base.path.slice(); + url.query = base.query; + url.fragment = ''; + state = FRAGMENT; + } else { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + url.path = base.path.slice(); + url.path.pop(); + state = PATH; + continue; + } break; + + case RELATIVE_SLASH: + if (isSpecial(url) && (char == '/' || char == '\\')) { + state = SPECIAL_AUTHORITY_IGNORE_SLASHES; + } else if (char == '/') { + state = AUTHORITY; + } else { + url.username = base.username; + url.password = base.password; + url.host = base.host; + url.port = base.port; + state = PATH; + continue; + } break; + + case SPECIAL_AUTHORITY_SLASHES: + state = SPECIAL_AUTHORITY_IGNORE_SLASHES; + if (char != '/' || buffer.charAt(pointer + 1) != '/') continue; + pointer++; + break; + + case SPECIAL_AUTHORITY_IGNORE_SLASHES: + if (char != '/' && char != '\\') { + state = AUTHORITY; + continue; + } break; + + case AUTHORITY: + if (char == '@') { + if (seenAt) buffer = '%40' + buffer; + seenAt = true; + bufferCodePoints = arrayFrom(buffer); + for (var i = 0; i < bufferCodePoints.length; i++) { + var codePoint = bufferCodePoints[i]; + if (codePoint == ':' && !seenPasswordToken) { + seenPasswordToken = true; + continue; + } + var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet); + if (seenPasswordToken) url.password += encodedCodePoints; + else url.username += encodedCodePoints; + } + buffer = ''; + } else if ( + char == EOF || char == '/' || char == '?' || char == '#' || + (char == '\\' && isSpecial(url)) + ) { + if (seenAt && buffer == '') return INVALID_AUTHORITY; + pointer -= arrayFrom(buffer).length + 1; + buffer = ''; + state = HOST; + } else buffer += char; + break; + + case HOST: + case HOSTNAME: + if (stateOverride && url.scheme == 'file') { + state = FILE_HOST; + continue; + } else if (char == ':' && !seenBracket) { + if (buffer == '') return INVALID_HOST; + failure = parseHost(url, buffer); + if (failure) return failure; + buffer = ''; + state = PORT; + if (stateOverride == HOSTNAME) return; + } else if ( + char == EOF || char == '/' || char == '?' || char == '#' || + (char == '\\' && isSpecial(url)) + ) { + if (isSpecial(url) && buffer == '') return INVALID_HOST; + if (stateOverride && buffer == '' && (includesCredentials(url) || url.port !== null)) return; + failure = parseHost(url, buffer); + if (failure) return failure; + buffer = ''; + state = PATH_START; + if (stateOverride) return; + continue; + } else { + if (char == '[') seenBracket = true; + else if (char == ']') seenBracket = false; + buffer += char; + } break; + + case PORT: + if (DIGIT.test(char)) { + buffer += char; + } else if ( + char == EOF || char == '/' || char == '?' || char == '#' || + (char == '\\' && isSpecial(url)) || + stateOverride + ) { + if (buffer != '') { + var port = parseInt(buffer, 10); + if (port > 0xFFFF) return INVALID_PORT; + url.port = (isSpecial(url) && port === specialSchemes[url.scheme]) ? null : port; + buffer = ''; + } + if (stateOverride) return; + state = PATH_START; + continue; + } else return INVALID_PORT; + break; + + case FILE: + url.scheme = 'file'; + if (char == '/' || char == '\\') state = FILE_SLASH; + else if (base && base.scheme == 'file') { + if (char == EOF) { + url.host = base.host; + url.path = base.path.slice(); + url.query = base.query; + } else if (char == '?') { + url.host = base.host; + url.path = base.path.slice(); + url.query = ''; + state = QUERY; + } else if (char == '#') { + url.host = base.host; + url.path = base.path.slice(); + url.query = base.query; + url.fragment = ''; + state = FRAGMENT; + } else { + if (!startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { + url.host = base.host; + url.path = base.path.slice(); + shortenURLsPath(url); + } + state = PATH; + continue; + } + } else { + state = PATH; + continue; + } break; + + case FILE_SLASH: + if (char == '/' || char == '\\') { + state = FILE_HOST; + break; + } + if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { + if (isWindowsDriveLetter(base.path[0], true)) url.path.push(base.path[0]); + else url.host = base.host; + } + state = PATH; + continue; + + case FILE_HOST: + if (char == EOF || char == '/' || char == '\\' || char == '?' || char == '#') { + if (!stateOverride && isWindowsDriveLetter(buffer)) { + state = PATH; + } else if (buffer == '') { + url.host = ''; + if (stateOverride) return; + state = PATH_START; + } else { + failure = parseHost(url, buffer); + if (failure) return failure; + if (url.host == 'localhost') url.host = ''; + if (stateOverride) return; + buffer = ''; + state = PATH_START; + } continue; + } else buffer += char; + break; + + case PATH_START: + if (isSpecial(url)) { + state = PATH; + if (char != '/' && char != '\\') continue; + } else if (!stateOverride && char == '?') { + url.query = ''; + state = QUERY; + } else if (!stateOverride && char == '#') { + url.fragment = ''; + state = FRAGMENT; + } else if (char != EOF) { + state = PATH; + if (char != '/') continue; + } break; + + case PATH: + if ( + char == EOF || char == '/' || + (char == '\\' && isSpecial(url)) || + (!stateOverride && (char == '?' || char == '#')) + ) { + if (isDoubleDot(buffer)) { + shortenURLsPath(url); + if (char != '/' && !(char == '\\' && isSpecial(url))) { + url.path.push(''); + } + } else if (isSingleDot(buffer)) { + if (char != '/' && !(char == '\\' && isSpecial(url))) { + url.path.push(''); + } + } else { + if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) { + if (url.host) url.host = ''; + buffer = buffer.charAt(0) + ':'; // normalize windows drive letter + } + url.path.push(buffer); + } + buffer = ''; + if (url.scheme == 'file' && (char == EOF || char == '?' || char == '#')) { + while (url.path.length > 1 && url.path[0] === '') { + url.path.shift(); + } + } + if (char == '?') { + url.query = ''; + state = QUERY; + } else if (char == '#') { + url.fragment = ''; + state = FRAGMENT; + } + } else { + buffer += percentEncode(char, pathPercentEncodeSet); + } break; + + case CANNOT_BE_A_BASE_URL_PATH: + if (char == '?') { + url.query = ''; + state = QUERY; + } else if (char == '#') { + url.fragment = ''; + state = FRAGMENT; + } else if (char != EOF) { + url.path[0] += percentEncode(char, C0ControlPercentEncodeSet); + } break; + + case QUERY: + if (!stateOverride && char == '#') { + url.fragment = ''; + state = FRAGMENT; + } else if (char != EOF) { + if (char == "'" && isSpecial(url)) url.query += '%27'; + else if (char == '#') url.query += '%23'; + else url.query += percentEncode(char, C0ControlPercentEncodeSet); + } break; + + case FRAGMENT: + if (char != EOF) url.fragment += percentEncode(char, fragmentPercentEncodeSet); + break; + } + + pointer++; + } +}; + +// `URL` constructor +// https://url.spec.whatwg.org/#url-class +var URLConstructor = function URL(url /* , base */) { + var that = anInstance(this, URLConstructor, 'URL'); + var base = arguments.length > 1 ? arguments[1] : undefined; + var urlString = String(url); + var state = setInternalState(that, { type: 'URL' }); + var baseState, failure; + if (base !== undefined) { + if (base instanceof URLConstructor) baseState = getInternalURLState(base); + else { + failure = parseURL(baseState = {}, String(base)); + if (failure) throw TypeError(failure); + } + } + failure = parseURL(state, urlString, null, baseState); + if (failure) throw TypeError(failure); + var searchParams = state.searchParams = new URLSearchParams(); + var searchParamsState = getInternalSearchParamsState(searchParams); + searchParamsState.updateSearchParams(state.query); + searchParamsState.updateURL = function () { + state.query = String(searchParams) || null; + }; + if (!DESCRIPTORS) { + that.href = serializeURL.call(that); + that.origin = getOrigin.call(that); + that.protocol = getProtocol.call(that); + that.username = getUsername.call(that); + that.password = getPassword.call(that); + that.host = getHost.call(that); + that.hostname = getHostname.call(that); + that.port = getPort.call(that); + that.pathname = getPathname.call(that); + that.search = getSearch.call(that); + that.searchParams = getSearchParams.call(that); + that.hash = getHash.call(that); + } +}; + +var URLPrototype = URLConstructor.prototype; + +var serializeURL = function () { + var url = getInternalURLState(this); + var scheme = url.scheme; + var username = url.username; + var password = url.password; + var host = url.host; + var port = url.port; + var path = url.path; + var query = url.query; + var fragment = url.fragment; + var output = scheme + ':'; + if (host !== null) { + output += '//'; + if (includesCredentials(url)) { + output += username + (password ? ':' + password : '') + '@'; + } + output += serializeHost(host); + if (port !== null) output += ':' + port; + } else if (scheme == 'file') output += '//'; + output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; + if (query !== null) output += '?' + query; + if (fragment !== null) output += '#' + fragment; + return output; +}; + +var getOrigin = function () { + var url = getInternalURLState(this); + var scheme = url.scheme; + var port = url.port; + if (scheme == 'blob') try { + return new URL(scheme.path[0]).origin; + } catch (error) { + return 'null'; + } + if (scheme == 'file' || !isSpecial(url)) return 'null'; + return scheme + '://' + serializeHost(url.host) + (port !== null ? ':' + port : ''); +}; + +var getProtocol = function () { + return getInternalURLState(this).scheme + ':'; +}; + +var getUsername = function () { + return getInternalURLState(this).username; +}; + +var getPassword = function () { + return getInternalURLState(this).password; +}; + +var getHost = function () { + var url = getInternalURLState(this); + var host = url.host; + var port = url.port; + return host === null ? '' + : port === null ? serializeHost(host) + : serializeHost(host) + ':' + port; +}; + +var getHostname = function () { + var host = getInternalURLState(this).host; + return host === null ? '' : serializeHost(host); +}; + +var getPort = function () { + var port = getInternalURLState(this).port; + return port === null ? '' : String(port); +}; + +var getPathname = function () { + var url = getInternalURLState(this); + var path = url.path; + return url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; +}; + +var getSearch = function () { + var query = getInternalURLState(this).query; + return query ? '?' + query : ''; +}; + +var getSearchParams = function () { + return getInternalURLState(this).searchParams; +}; + +var getHash = function () { + var fragment = getInternalURLState(this).fragment; + return fragment ? '#' + fragment : ''; +}; + +var accessorDescriptor = function (getter, setter) { + return { get: getter, set: setter, configurable: true, enumerable: true }; +}; + +if (DESCRIPTORS) { + defineProperties(URLPrototype, { + // `URL.prototype.href` accessors pair + // https://url.spec.whatwg.org/#dom-url-href + href: accessorDescriptor(serializeURL, function (href) { + var url = getInternalURLState(this); + var urlString = String(href); + var failure = parseURL(url, urlString); + if (failure) throw TypeError(failure); + getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); + }), + // `URL.prototype.origin` getter + // https://url.spec.whatwg.org/#dom-url-origin + origin: accessorDescriptor(getOrigin), + // `URL.prototype.protocol` accessors pair + // https://url.spec.whatwg.org/#dom-url-protocol + protocol: accessorDescriptor(getProtocol, function (protocol) { + var url = getInternalURLState(this); + parseURL(url, String(protocol) + ':', SCHEME_START); + }), + // `URL.prototype.username` accessors pair + // https://url.spec.whatwg.org/#dom-url-username + username: accessorDescriptor(getUsername, function (username) { + var url = getInternalURLState(this); + var codePoints = arrayFrom(String(username)); + if (cannotHaveUsernamePasswordPort(url)) return; + url.username = ''; + for (var i = 0; i < codePoints.length; i++) { + url.username += percentEncode(codePoints[i], userinfoPercentEncodeSet); + } + }), + // `URL.prototype.password` accessors pair + // https://url.spec.whatwg.org/#dom-url-password + password: accessorDescriptor(getPassword, function (password) { + var url = getInternalURLState(this); + var codePoints = arrayFrom(String(password)); + if (cannotHaveUsernamePasswordPort(url)) return; + url.password = ''; + for (var i = 0; i < codePoints.length; i++) { + url.password += percentEncode(codePoints[i], userinfoPercentEncodeSet); + } + }), + // `URL.prototype.host` accessors pair + // https://url.spec.whatwg.org/#dom-url-host + host: accessorDescriptor(getHost, function (host) { + var url = getInternalURLState(this); + if (url.cannotBeABaseURL) return; + parseURL(url, String(host), HOST); + }), + // `URL.prototype.hostname` accessors pair + // https://url.spec.whatwg.org/#dom-url-hostname + hostname: accessorDescriptor(getHostname, function (hostname) { + var url = getInternalURLState(this); + if (url.cannotBeABaseURL) return; + parseURL(url, String(hostname), HOSTNAME); + }), + // `URL.prototype.port` accessors pair + // https://url.spec.whatwg.org/#dom-url-port + port: accessorDescriptor(getPort, function (port) { + var url = getInternalURLState(this); + if (cannotHaveUsernamePasswordPort(url)) return; + port = String(port); + if (port == '') url.port = null; + else parseURL(url, port, PORT); + }), + // `URL.prototype.pathname` accessors pair + // https://url.spec.whatwg.org/#dom-url-pathname + pathname: accessorDescriptor(getPathname, function (pathname) { + var url = getInternalURLState(this); + if (url.cannotBeABaseURL) return; + url.path = []; + parseURL(url, pathname + '', PATH_START); + }), + // `URL.prototype.search` accessors pair + // https://url.spec.whatwg.org/#dom-url-search + search: accessorDescriptor(getSearch, function (search) { + var url = getInternalURLState(this); + search = String(search); + if (search == '') { + url.query = null; + } else { + if ('?' == search.charAt(0)) search = search.slice(1); + url.query = ''; + parseURL(url, search, QUERY); + } + getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); + }), + // `URL.prototype.searchParams` getter + // https://url.spec.whatwg.org/#dom-url-searchparams + searchParams: accessorDescriptor(getSearchParams), + // `URL.prototype.hash` accessors pair + // https://url.spec.whatwg.org/#dom-url-hash + hash: accessorDescriptor(getHash, function (hash) { + var url = getInternalURLState(this); + hash = String(hash); + if (hash == '') { + url.fragment = null; + return; + } + if ('#' == hash.charAt(0)) hash = hash.slice(1); + url.fragment = ''; + parseURL(url, hash, FRAGMENT); + }) + }); +} + +// `URL.prototype.toJSON` method +// https://url.spec.whatwg.org/#dom-url-tojson +redefine(URLPrototype, 'toJSON', function toJSON() { + return serializeURL.call(this); +}, { enumerable: true }); + +// `URL.prototype.toString` method +// https://url.spec.whatwg.org/#URL-stringification-behavior +redefine(URLPrototype, 'toString', function toString() { + return serializeURL.call(this); +}, { enumerable: true }); + +if (NativeURL) { + var nativeCreateObjectURL = NativeURL.createObjectURL; + var nativeRevokeObjectURL = NativeURL.revokeObjectURL; + // `URL.createObjectURL` method + // https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL + // eslint-disable-next-line no-unused-vars + if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) { + return nativeCreateObjectURL.apply(NativeURL, arguments); + }); + // `URL.revokeObjectURL` method + // https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL + // eslint-disable-next-line no-unused-vars + if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) { + return nativeRevokeObjectURL.apply(NativeURL, arguments); + }); +} + +setToStringTag(URLConstructor, 'URL'); + +$({ global: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS }, { + URL: URLConstructor +}); + +},{"../internals/an-instance":314,"../internals/array-from":321,"../internals/descriptors":357,"../internals/export":361,"../internals/global":377,"../internals/has":378,"../internals/internal-state":386,"../internals/native-url":407,"../internals/object-assign":412,"../internals/object-define-properties":414,"../internals/punycode-to-ascii":433,"../internals/redefine":435,"../internals/set-to-string-tag":445,"../internals/string-multibyte":451,"../modules/es.string.iterator":610,"../modules/web.url-search-params":793}],795:[function(require,module,exports){ +'use strict'; +var $ = require('../internals/export'); + +// `URL.prototype.toJSON` method +// https://url.spec.whatwg.org/#dom-url-tojson +$({ target: 'URL', proto: true, enumerable: true }, { + toJSON: function toJSON() { + return URL.prototype.toString.call(this); + } +}); + +},{"../internals/export":361}],796:[function(require,module,exports){ +require('../modules/esnext.array.is-template-object'); + +},{"../modules/esnext.array.is-template-object":681}],797:[function(require,module,exports){ +require('../modules/esnext.array.last-index'); +require('../modules/esnext.array.last-item'); + +},{"../modules/esnext.array.last-index":682,"../modules/esnext.array.last-item":683}],798:[function(require,module,exports){ +require('../modules/esnext.map.group-by'); +require('../modules/esnext.map.key-by'); +require('../modules/esnext.map.delete-all'); +require('../modules/esnext.map.every'); +require('../modules/esnext.map.filter'); +require('../modules/esnext.map.find'); +require('../modules/esnext.map.find-key'); +require('../modules/esnext.map.includes'); +require('../modules/esnext.map.key-of'); +require('../modules/esnext.map.map-keys'); +require('../modules/esnext.map.map-values'); +require('../modules/esnext.map.merge'); +require('../modules/esnext.map.reduce'); +require('../modules/esnext.map.some'); +require('../modules/esnext.map.update'); +require('../modules/esnext.set.add-all'); +require('../modules/esnext.set.delete-all'); +require('../modules/esnext.set.every'); +require('../modules/esnext.set.filter'); +require('../modules/esnext.set.find'); +require('../modules/esnext.set.join'); +require('../modules/esnext.set.map'); +require('../modules/esnext.set.reduce'); +require('../modules/esnext.set.some'); +require('../modules/esnext.weak-map.delete-all'); +require('../modules/esnext.weak-set.add-all'); +require('../modules/esnext.weak-set.delete-all'); + +},{"../modules/esnext.map.delete-all":707,"../modules/esnext.map.every":708,"../modules/esnext.map.filter":709,"../modules/esnext.map.find":711,"../modules/esnext.map.find-key":710,"../modules/esnext.map.group-by":713,"../modules/esnext.map.includes":714,"../modules/esnext.map.key-by":715,"../modules/esnext.map.key-of":716,"../modules/esnext.map.map-keys":717,"../modules/esnext.map.map-values":718,"../modules/esnext.map.merge":719,"../modules/esnext.map.reduce":721,"../modules/esnext.map.some":722,"../modules/esnext.map.update":724,"../modules/esnext.set.add-all":753,"../modules/esnext.set.delete-all":754,"../modules/esnext.set.every":756,"../modules/esnext.set.filter":757,"../modules/esnext.set.find":758,"../modules/esnext.set.join":764,"../modules/esnext.set.map":765,"../modules/esnext.set.reduce":767,"../modules/esnext.set.some":768,"../modules/esnext.weak-map.delete-all":780,"../modules/esnext.weak-set.add-all":784,"../modules/esnext.weak-set.delete-all":785}],799:[function(require,module,exports){ +require('../modules/esnext.map.from'); +require('../modules/esnext.map.of'); +require('../modules/esnext.set.from'); +require('../modules/esnext.set.of'); +require('../modules/esnext.weak-map.from'); +require('../modules/esnext.weak-map.of'); +require('../modules/esnext.weak-set.from'); +require('../modules/esnext.weak-set.of'); + +},{"../modules/esnext.map.from":712,"../modules/esnext.map.of":720,"../modules/esnext.set.from":759,"../modules/esnext.set.of":766,"../modules/esnext.weak-map.from":781,"../modules/esnext.weak-map.of":782,"../modules/esnext.weak-set.from":786,"../modules/esnext.weak-set.of":787}],800:[function(require,module,exports){ +require('../modules/esnext.math.iaddh'); +require('../modules/esnext.math.isubh'); +require('../modules/esnext.math.imulh'); +require('../modules/esnext.math.umulh'); + +},{"../modules/esnext.math.iaddh":730,"../modules/esnext.math.imulh":731,"../modules/esnext.math.isubh":732,"../modules/esnext.math.umulh":738}],801:[function(require,module,exports){ +require('../modules/esnext.global-this'); + +module.exports = require('../internals/global'); + +},{"../internals/global":377,"../modules/esnext.global-this":693}],802:[function(require,module,exports){ +require('../stage'); + +},{"../stage":828}],803:[function(require,module,exports){ +require('../modules/esnext.async-iterator.constructor'); +require('../modules/esnext.async-iterator.drop'); +require('../modules/esnext.async-iterator.filter'); +require('../modules/esnext.async-iterator.from'); +require('../modules/esnext.async-iterator.map'); +require('../modules/esnext.async-iterator.take'); +require('../modules/esnext.async-iterator.to-array'); +require('../modules/esnext.iterator.constructor'); +require('../modules/esnext.iterator.as-indexed-pairs'); +require('../modules/esnext.iterator.drop'); +require('../modules/esnext.iterator.every'); +require('../modules/esnext.iterator.filter'); +require('../modules/esnext.iterator.find'); +require('../modules/esnext.iterator.for-each'); +require('../modules/esnext.iterator.from'); +require('../modules/esnext.iterator.map'); +require('../modules/esnext.iterator.reduce'); +require('../modules/esnext.iterator.some'); +require('../modules/esnext.iterator.take'); +require('../modules/esnext.iterator.to-array'); + +},{"../modules/esnext.async-iterator.constructor":684,"../modules/esnext.async-iterator.drop":685,"../modules/esnext.async-iterator.filter":686,"../modules/esnext.async-iterator.from":687,"../modules/esnext.async-iterator.map":688,"../modules/esnext.async-iterator.take":689,"../modules/esnext.async-iterator.to-array":690,"../modules/esnext.iterator.as-indexed-pairs":694,"../modules/esnext.iterator.constructor":695,"../modules/esnext.iterator.drop":696,"../modules/esnext.iterator.every":697,"../modules/esnext.iterator.filter":698,"../modules/esnext.iterator.find":699,"../modules/esnext.iterator.for-each":700,"../modules/esnext.iterator.from":701,"../modules/esnext.iterator.map":702,"../modules/esnext.iterator.reduce":703,"../modules/esnext.iterator.some":704,"../modules/esnext.iterator.take":705,"../modules/esnext.iterator.to-array":706}],804:[function(require,module,exports){ +require('../modules/esnext.composite-key'); +require('../modules/esnext.composite-symbol'); + +},{"../modules/esnext.composite-key":691,"../modules/esnext.composite-symbol":692}],805:[function(require,module,exports){ +// https://github.com/thumbsupep/proposal-upsert +// TODO: remove from `core-js@4` +require('../modules/esnext.map.update-or-insert'); +require('../modules/esnext.map.upsert'); +require('../modules/esnext.weak-map.upsert'); + +},{"../modules/esnext.map.update-or-insert":723,"../modules/esnext.map.upsert":725,"../modules/esnext.weak-map.upsert":783}],806:[function(require,module,exports){ +require('../modules/esnext.math.clamp'); +require('../modules/esnext.math.deg-per-rad'); +require('../modules/esnext.math.degrees'); +require('../modules/esnext.math.fscale'); +require('../modules/esnext.math.rad-per-deg'); +require('../modules/esnext.math.radians'); +require('../modules/esnext.math.scale'); + +},{"../modules/esnext.math.clamp":726,"../modules/esnext.math.deg-per-rad":727,"../modules/esnext.math.degrees":728,"../modules/esnext.math.fscale":729,"../modules/esnext.math.rad-per-deg":733,"../modules/esnext.math.radians":734,"../modules/esnext.math.scale":735}],807:[function(require,module,exports){ +require('../modules/esnext.math.signbit'); + +},{"../modules/esnext.math.signbit":737}],808:[function(require,module,exports){ +require('../modules/esnext.number.from-string'); + +},{"../modules/esnext.number.from-string":739}],809:[function(require,module,exports){ +require('../modules/esnext.observable'); +require('../modules/esnext.symbol.observable'); + +},{"../modules/esnext.observable":740,"../modules/esnext.symbol.observable":777}],810:[function(require,module,exports){ +require('../modules/esnext.symbol.pattern-match'); + +},{"../modules/esnext.symbol.pattern-match":778}],811:[function(require,module,exports){ +// TODO: Remove from `core-js@4` +require('../modules/esnext.promise.all-settled'); + +},{"../modules/esnext.promise.all-settled":741}],812:[function(require,module,exports){ +require('../modules/esnext.aggregate-error'); +require('../modules/esnext.promise.any'); + +},{"../modules/esnext.aggregate-error":680,"../modules/esnext.promise.any":742}],813:[function(require,module,exports){ +require('../modules/esnext.promise.try'); + +},{"../modules/esnext.promise.try":743}],814:[function(require,module,exports){ +require('../modules/esnext.reflect.define-metadata'); +require('../modules/esnext.reflect.delete-metadata'); +require('../modules/esnext.reflect.get-metadata'); +require('../modules/esnext.reflect.get-metadata-keys'); +require('../modules/esnext.reflect.get-own-metadata'); +require('../modules/esnext.reflect.get-own-metadata-keys'); +require('../modules/esnext.reflect.has-metadata'); +require('../modules/esnext.reflect.has-own-metadata'); +require('../modules/esnext.reflect.metadata'); + +},{"../modules/esnext.reflect.define-metadata":744,"../modules/esnext.reflect.delete-metadata":745,"../modules/esnext.reflect.get-metadata":747,"../modules/esnext.reflect.get-metadata-keys":746,"../modules/esnext.reflect.get-own-metadata":749,"../modules/esnext.reflect.get-own-metadata-keys":748,"../modules/esnext.reflect.has-metadata":750,"../modules/esnext.reflect.has-own-metadata":751,"../modules/esnext.reflect.metadata":752}],815:[function(require,module,exports){ +require('../modules/esnext.math.seeded-prng'); + +},{"../modules/esnext.math.seeded-prng":736}],816:[function(require,module,exports){ +require('../modules/esnext.set.difference'); +require('../modules/esnext.set.intersection'); +require('../modules/esnext.set.is-disjoint-from'); +require('../modules/esnext.set.is-subset-of'); +require('../modules/esnext.set.is-superset-of'); +require('../modules/esnext.set.union'); +require('../modules/esnext.set.symmetric-difference'); + +},{"../modules/esnext.set.difference":755,"../modules/esnext.set.intersection":760,"../modules/esnext.set.is-disjoint-from":761,"../modules/esnext.set.is-subset-of":762,"../modules/esnext.set.is-superset-of":763,"../modules/esnext.set.symmetric-difference":769,"../modules/esnext.set.union":770}],817:[function(require,module,exports){ +require('../modules/esnext.string.at'); + +},{"../modules/esnext.string.at":771}],818:[function(require,module,exports){ +require('../modules/esnext.string.code-points'); + +},{"../modules/esnext.string.code-points":772}],819:[function(require,module,exports){ +// TODO: Remove from `core-js@4` +require('../modules/esnext.string.match-all'); + +},{"../modules/esnext.string.match-all":773}],820:[function(require,module,exports){ +require('../modules/esnext.string.replace-all'); +require('../modules/esnext.symbol.replace-all'); + +},{"../modules/esnext.string.replace-all":774,"../modules/esnext.symbol.replace-all":779}],821:[function(require,module,exports){ +require('../modules/web.url'); +require('../modules/web.url.to-json'); +require('../modules/web.url-search-params'); + +},{"../modules/web.url":794,"../modules/web.url-search-params":793,"../modules/web.url.to-json":795}],822:[function(require,module,exports){ +// https://github.com/tc39/proposal-using-statement +require('../modules/esnext.symbol.async-dispose'); +require('../modules/esnext.symbol.dispose'); + +},{"../modules/esnext.symbol.async-dispose":775,"../modules/esnext.symbol.dispose":776}],823:[function(require,module,exports){ +require('../proposals/efficient-64-bit-arithmetic'); +require('../proposals/string-at'); +require('../proposals/url'); + +module.exports = require('./1'); + +},{"../proposals/efficient-64-bit-arithmetic":800,"../proposals/string-at":817,"../proposals/url":821,"./1":824}],824:[function(require,module,exports){ +require('../proposals/array-last'); +require('../proposals/collection-methods'); +require('../proposals/collection-of-from'); +require('../proposals/keys-composition'); +require('../proposals/math-extensions'); +require('../proposals/math-signbit'); +require('../proposals/number-from-string'); +require('../proposals/observable'); +require('../proposals/pattern-matching'); +require('../proposals/promise-try'); +require('../proposals/seeded-random'); +require('../proposals/string-code-points'); + +module.exports = require('./2'); + +},{"../proposals/array-last":797,"../proposals/collection-methods":798,"../proposals/collection-of-from":799,"../proposals/keys-composition":804,"../proposals/math-extensions":806,"../proposals/math-signbit":807,"../proposals/number-from-string":808,"../proposals/observable":809,"../proposals/pattern-matching":810,"../proposals/promise-try":813,"../proposals/seeded-random":815,"../proposals/string-code-points":818,"./2":825}],825:[function(require,module,exports){ +require('../proposals/array-is-template-object'); +require('../proposals/iterator-helpers'); +require('../proposals/map-upsert'); +require('../proposals/set-methods'); +require('../proposals/using-statement'); + +module.exports = require('./3'); + +},{"../proposals/array-is-template-object":796,"../proposals/iterator-helpers":803,"../proposals/map-upsert":805,"../proposals/set-methods":816,"../proposals/using-statement":822,"./3":826}],826:[function(require,module,exports){ +require('../proposals/promise-any'); +require('../proposals/string-replace-all'); + +module.exports = require('./4'); + +},{"../proposals/promise-any":812,"../proposals/string-replace-all":820,"./4":827}],827:[function(require,module,exports){ +require('../proposals/global-this'); +require('../proposals/promise-all-settled'); +require('../proposals/string-match-all'); + +module.exports = require('../internals/path'); + +},{"../internals/path":430,"../proposals/global-this":801,"../proposals/promise-all-settled":811,"../proposals/string-match-all":819}],828:[function(require,module,exports){ +module.exports = require('./pre'); + +},{"./pre":829}],829:[function(require,module,exports){ +require('../proposals/reflect-metadata'); + +module.exports = require('./0'); + +},{"../proposals/reflect-metadata":814,"./0":823}],830:[function(require,module,exports){ +require('../modules/web.dom-collections.for-each'); +require('../modules/web.dom-collections.iterator'); +require('../modules/web.immediate'); +require('../modules/web.queue-microtask'); +require('../modules/web.timers'); +require('../modules/web.url'); +require('../modules/web.url.to-json'); +require('../modules/web.url-search-params'); + +module.exports = require('../internals/path'); + +},{"../internals/path":430,"../modules/web.dom-collections.for-each":788,"../modules/web.dom-collections.iterator":789,"../modules/web.immediate":790,"../modules/web.queue-microtask":791,"../modules/web.timers":792,"../modules/web.url":794,"../modules/web.url-search-params":793,"../modules/web.url.to-json":795}],831:[function(require,module,exports){ +"use strict"; + +module.exports = { + "8.0": "79", + "7.1": "78", + "7.0": "78", + "6.1": "76", + "6.0": "76", + "5.0": "72", + "4.2": "69", + "4.1": "69", + "4.0": "69", + "3.1": "66", + "3.0": "66", + "2.1": "61", + "2.0": "61", + "1.8": "59", + "1.7": "58", + "1.6": "56", + "1.5": "54", + "1.4": "53", + "1.3": "52", + "1.2": "51", + "1.1": "50", + "1.0": "49", + "0.37": "49", + "0.36": "47", + "0.35": "45", + "0.34": "45", + "0.33": "45", + "0.32": "45", + "0.31": "44", + "0.30": "44", + "0.29": "43", + "0.28": "43", + "0.27": "42", + "0.26": "42", + "0.25": "42", + "0.24": "41", + "0.23": "41", + "0.22": "41", + "0.21": "40", + "0.20": "39" +}; + +},{}],832:[function(require,module,exports){ +'use strict'; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +},{}],833:[function(require,module,exports){ +"use strict"; + +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function () { + 'use strict'; + + function isExpression(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + + return false; + } + + function isIterationStatement(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + + return false; + } + + function isStatement(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + + if (node.alternate == null) { + return false; + } + + current = node.consequent; + + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + trailingStatement: trailingStatement + }; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{}],834:[function(require,module,exports){ +"use strict"; + +/* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function () { + 'use strict'; + + var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. + + ES5Regex = { + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ + }; + ES6Regex = { + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + + function isDecimalDigit(ch) { + return 0x30 <= ch && ch <= 0x39; // 0..9 + } + + function isHexDigit(ch) { + return 0x30 <= ch && ch <= 0x39 || // 0..9 + 0x61 <= ch && ch <= 0x66 || // a..f + 0x41 <= ch && ch <= 0x46; // A..F + } + + function isOctalDigit(ch) { + return ch >= 0x30 && ch <= 0x37; // 0..7 + } // 7.2 White Space + + + NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; + + function isWhiteSpace(ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; + } // 7.3 Line Terminators + + + function isLineTerminator(ch) { + return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; + } // 7.6 Identifier Names and Identifiers + + + function fromCodePoint(cp) { + if (cp <= 0xFFFF) { + return String.fromCharCode(cp); + } + + var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); + var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); + return cu1 + cu2; + } + + IDENTIFIER_START = new Array(0x80); + + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + IDENTIFIER_PART = new Array(0x80); + + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch >= 0x30 && ch <= 0x39 || // 0..9 + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + function isIdentifierStartES5(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES5(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + function isIdentifierStartES6(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES6(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStartES5: isIdentifierStartES5, + isIdentifierPartES5: isIdentifierPartES5, + isIdentifierStartES6: isIdentifierStartES6, + isIdentifierPartES6: isIdentifierPartES6 + }; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{}],835:[function(require,module,exports){ +"use strict"; + +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function () { + 'use strict'; + + var code = require('./code'); + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return id === 'if' || id === 'in' || id === 'do'; + + case 3: + return id === 'var' || id === 'for' || id === 'new' || id === 'try'; + + case 4: + return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum'; + + case 5: + return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super'; + + case 6: + return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import'; + + case 7: + return id === 'default' || id === 'finally' || id === 'extends'; + + case 8: + return id === 'function' || id === 'continue' || id === 'debugger'; + + case 10: + return id === 'instanceof'; + + default: + return false; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierNameES5(id) { + var i, iz, ch; + + if (id.length === 0) { + return false; + } + + ch = id.charCodeAt(0); + + if (!code.isIdentifierStartES5(ch)) { + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + + if (!code.isIdentifierPartES5(ch)) { + return false; + } + } + + return true; + } + + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } + + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; + + if (id.length === 0) { + return false; + } + + check = code.isIdentifierStartES6; + + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + + if (i >= iz) { + return false; + } + + lowCh = id.charCodeAt(i); + + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + + ch = decodeUtf16(ch, lowCh); + } + + if (!check(ch)) { + return false; + } + + check = code.isIdentifierPartES6; + } + + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{"./code":834}],836:[function(require,module,exports){ +"use strict"; + +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function () { + 'use strict'; + + exports.ast = require('./ast'); + exports.code = require('./code'); + exports.keyword = require('./keyword'); +})(); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{"./ast":833,"./code":834,"./keyword":835}],837:[function(require,module,exports){ +module.exports={ + "builtin": { + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es5": { + "Array": false, + "Boolean": false, + "constructor": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "propertyIsEnumerable": false, + "RangeError": false, + "ReferenceError": false, + "RegExp": false, + "String": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false + }, + "es2015": { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2017": { + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "browser": { + "AbortController": false, + "AbortSignal": false, + "addEventListener": false, + "alert": false, + "AnalyserNode": false, + "Animation": false, + "AnimationEffectReadOnly": false, + "AnimationEffectTiming": false, + "AnimationEffectTimingReadOnly": false, + "AnimationEvent": false, + "AnimationPlaybackEvent": false, + "AnimationTimeline": false, + "applicationCache": false, + "ApplicationCache": false, + "ApplicationCacheErrorEvent": false, + "atob": false, + "Attr": false, + "Audio": false, + "AudioBuffer": false, + "AudioBufferSourceNode": false, + "AudioContext": false, + "AudioDestinationNode": false, + "AudioListener": false, + "AudioNode": false, + "AudioParam": false, + "AudioProcessingEvent": false, + "AudioScheduledSourceNode": false, + "AudioWorkletGlobalScope ": false, + "AudioWorkletNode": false, + "AudioWorkletProcessor": false, + "BarProp": false, + "BaseAudioContext": false, + "BatteryManager": false, + "BeforeUnloadEvent": false, + "BiquadFilterNode": false, + "Blob": false, + "BlobEvent": false, + "blur": false, + "BroadcastChannel": false, + "btoa": false, + "BudgetService": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "CacheStorage": false, + "cancelAnimationFrame": false, + "cancelIdleCallback": false, + "CanvasCaptureMediaStreamTrack": false, + "CanvasGradient": false, + "CanvasPattern": false, + "CanvasRenderingContext2D": false, + "ChannelMergerNode": false, + "ChannelSplitterNode": false, + "CharacterData": false, + "clearInterval": false, + "clearTimeout": false, + "clientInformation": false, + "ClipboardEvent": false, + "close": false, + "closed": false, + "CloseEvent": false, + "Comment": false, + "CompositionEvent": false, + "confirm": false, + "console": false, + "ConstantSourceNode": false, + "ConvolverNode": false, + "CountQueuingStrategy": false, + "createImageBitmap": false, + "Credential": false, + "CredentialsContainer": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CSS": false, + "CSSConditionRule": false, + "CSSFontFaceRule": false, + "CSSGroupingRule": false, + "CSSImportRule": false, + "CSSKeyframeRule": false, + "CSSKeyframesRule": false, + "CSSMediaRule": false, + "CSSNamespaceRule": false, + "CSSPageRule": false, "CSSRule": false, "CSSRuleList": false, "CSSStyleDeclaration": false, "CSSStyleRule": false, "CSSStyleSheet": false, "CSSSupportsRule": false, - "CSSTransition": false, - "CSSUnknownRule": false, - "CSSViewportRule": false, + "CustomElementRegistry": false, "customElements": false, "CustomEvent": false, "DataTransfer": false, "DataTransferItem": false, "DataTransferItemList": false, - "Debug": false, - "defaultStatus": false, "defaultstatus": false, + "defaultStatus": false, "DelayNode": false, "DeviceMotionEvent": false, "DeviceOrientationEvent": false, @@ -36200,36 +101082,39 @@ module.exports={ "document": false, "Document": false, "DocumentFragment": false, - "DocumentTimeline": false, "DocumentType": false, "DOMError": false, "DOMException": false, "DOMImplementation": false, + "DOMMatrix": false, + "DOMMatrixReadOnly": false, "DOMParser": false, - "DOMSettableTokenList": false, + "DOMPoint": false, + "DOMPointReadOnly": false, + "DOMQuad": false, + "DOMRect": false, + "DOMRectReadOnly": false, "DOMStringList": false, "DOMStringMap": false, "DOMTokenList": false, "DragEvent": false, "DynamicsCompressorNode": false, "Element": false, - "ElementTimeControl": false, "ErrorEvent": false, "event": false, "Event": false, "EventSource": false, "EventTarget": false, "external": false, - "FederatedCredential": false, "fetch": false, "File": false, - "FileError": false, "FileList": false, "FileReader": false, "find": false, "focus": false, "FocusEvent": false, "FontFace": false, + "FontFaceSetLoadEvent": false, "FormData": false, "frameElement": false, "frames": false, @@ -36245,17 +101130,16 @@ module.exports={ "History": false, "HTMLAllCollection": false, "HTMLAnchorElement": false, - "HTMLAppletElement": false, "HTMLAreaElement": false, "HTMLAudioElement": false, "HTMLBaseElement": false, - "HTMLBlockquoteElement": false, "HTMLBodyElement": false, "HTMLBRElement": false, "HTMLButtonElement": false, "HTMLCanvasElement": false, "HTMLCollection": false, "HTMLContentElement": false, + "HTMLDataElement": false, "HTMLDataListElement": false, "HTMLDetailsElement": false, "HTMLDialogElement": false, @@ -36278,10 +101162,7 @@ module.exports={ "HTMLIFrameElement": false, "HTMLImageElement": false, "HTMLInputElement": false, - "HTMLIsIndexElement": false, - "HTMLKeygenElement": false, "HTMLLabelElement": false, - "HTMLLayerElement": false, "HTMLLegendElement": false, "HTMLLIElement": false, "HTMLLinkElement": false, @@ -36307,6 +101188,7 @@ module.exports={ "HTMLScriptElement": false, "HTMLSelectElement": false, "HTMLShadowElement": false, + "HTMLSlotElement": false, "HTMLSourceElement": false, "HTMLSpanElement": false, "HTMLStyleElement": false, @@ -36318,6 +101200,7 @@ module.exports={ "HTMLTableSectionElement": false, "HTMLTemplateElement": false, "HTMLTextAreaElement": false, + "HTMLTimeElement": false, "HTMLTitleElement": false, "HTMLTrackElement": false, "HTMLUListElement": false, @@ -36326,7 +101209,6 @@ module.exports={ "IDBCursor": false, "IDBCursorWithValue": false, "IDBDatabase": false, - "IDBEnvironment": false, "IDBFactory": false, "IDBIndex": false, "IDBKeyRange": false, @@ -36335,46 +101217,51 @@ module.exports={ "IDBRequest": false, "IDBTransaction": false, "IDBVersionChangeEvent": false, + "IdleDeadline": false, + "IIRFilterNode": false, "Image": false, "ImageBitmap": false, + "ImageBitmapRenderingContext": false, + "ImageCapture": false, "ImageData": false, "indexedDB": false, "innerHeight": false, "innerWidth": false, "InputEvent": false, - "InputMethodContext": false, "IntersectionObserver": false, "IntersectionObserverEntry": false, "Intl": false, + "isSecureContext": false, "KeyboardEvent": false, "KeyframeEffect": false, "KeyframeEffectReadOnly": false, "length": false, "localStorage": false, - "location": false, + "location": true, "Location": false, "locationbar": false, "matchMedia": false, + "MediaDeviceInfo": false, + "MediaDevices": false, "MediaElementAudioSourceNode": false, "MediaEncryptedEvent": false, "MediaError": false, - "MediaKeyError": false, - "MediaKeyEvent": false, "MediaKeyMessageEvent": false, - "MediaKeys": false, "MediaKeySession": false, "MediaKeyStatusMap": false, "MediaKeySystemAccess": false, "MediaList": false, "MediaQueryList": false, "MediaQueryListEvent": false, - "MediaSource": false, "MediaRecorder": false, + "MediaSettingsRange": false, + "MediaSource": false, "MediaStream": false, "MediaStreamAudioDestinationNode": false, "MediaStreamAudioSourceNode": false, "MediaStreamEvent": false, "MediaStreamTrack": false, + "MediaStreamTrackEvent": false, "menubar": false, "MessageChannel": false, "MessageEvent": false, @@ -36397,8 +101284,10 @@ module.exports={ "MutationRecord": false, "name": false, "NamedNodeMap": false, + "NavigationPreloadManager": false, "navigator": false, "Navigator": false, + "NetworkInformation": false, "Node": false, "NodeFilter": false, "NodeIterator": false, @@ -36407,43 +101296,152 @@ module.exports={ "OfflineAudioCompletionEvent": false, "OfflineAudioContext": false, "offscreenBuffering": false, + "OffscreenCanvas": true, + "onabort": true, + "onafterprint": true, + "onanimationend": true, + "onanimationiteration": true, + "onanimationstart": true, + "onappinstalled": true, + "onauxclick": true, + "onbeforeinstallprompt": true, + "onbeforeprint": true, "onbeforeunload": true, "onblur": true, + "oncancel": true, + "oncanplay": true, + "oncanplaythrough": true, + "onchange": true, + "onclick": true, + "onclose": true, + "oncontextmenu": true, + "oncuechange": true, + "ondblclick": true, + "ondevicemotion": true, + "ondeviceorientation": true, + "ondeviceorientationabsolute": true, + "ondrag": true, + "ondragend": true, + "ondragenter": true, + "ondragleave": true, + "ondragover": true, + "ondragstart": true, + "ondrop": true, + "ondurationchange": true, + "onemptied": true, + "onended": true, "onerror": true, "onfocus": true, + "ongotpointercapture": true, + "onhashchange": true, + "oninput": true, + "oninvalid": true, + "onkeydown": true, + "onkeypress": true, + "onkeyup": true, + "onlanguagechange": true, "onload": true, + "onloadeddata": true, + "onloadedmetadata": true, + "onloadstart": true, + "onlostpointercapture": true, + "onmessage": true, + "onmessageerror": true, + "onmousedown": true, + "onmouseenter": true, + "onmouseleave": true, + "onmousemove": true, + "onmouseout": true, + "onmouseover": true, + "onmouseup": true, + "onmousewheel": true, + "onoffline": true, + "ononline": true, + "onpagehide": true, + "onpageshow": true, + "onpause": true, + "onplay": true, + "onplaying": true, + "onpointercancel": true, + "onpointerdown": true, + "onpointerenter": true, + "onpointerleave": true, + "onpointermove": true, + "onpointerout": true, + "onpointerover": true, + "onpointerup": true, + "onpopstate": true, + "onprogress": true, + "onratechange": true, + "onrejectionhandled": true, + "onreset": true, "onresize": true, + "onscroll": true, + "onsearch": true, + "onseeked": true, + "onseeking": true, + "onselect": true, + "onstalled": true, + "onstorage": true, + "onsubmit": true, + "onsuspend": true, + "ontimeupdate": true, + "ontoggle": true, + "ontransitionend": true, + "onunhandledrejection": true, "onunload": true, + "onvolumechange": true, + "onwaiting": true, + "onwheel": true, "open": false, "openDatabase": false, "opener": false, - "opera": false, "Option": false, + "origin": false, "OscillatorNode": false, "outerHeight": false, "outerWidth": false, "PageTransitionEvent": false, "pageXOffset": false, "pageYOffset": false, + "PannerNode": false, "parent": false, - "PasswordCredential": false, "Path2D": false, + "PaymentAddress": false, + "PaymentRequest": false, + "PaymentRequestUpdateEvent": false, + "PaymentResponse": false, "performance": false, "Performance": false, "PerformanceEntry": false, + "PerformanceLongTaskTiming": false, "PerformanceMark": false, "PerformanceMeasure": false, "PerformanceNavigation": false, + "PerformanceNavigationTiming": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformancePaintTiming": false, "PerformanceResourceTiming": false, "PerformanceTiming": false, "PeriodicWave": false, "Permissions": false, "PermissionStatus": false, "personalbar": false, + "PhotoCapabilities": false, "Plugin": false, "PluginArray": false, + "PointerEvent": false, "PopStateEvent": false, "postMessage": false, + "Presentation": false, + "PresentationAvailability": false, + "PresentationConnection": false, + "PresentationConnectionAvailableEvent": false, + "PresentationConnectionCloseEvent": false, + "PresentationConnectionList": false, + "PresentationReceiver": false, + "PresentationRequest": false, "print": false, "ProcessingInstruction": false, "ProgressEvent": false, @@ -36451,20 +101449,38 @@ module.exports={ "prompt": false, "PushManager": false, "PushSubscription": false, + "PushSubscriptionOptions": false, + "queueMicrotask": false, "RadioNodeList": false, "Range": false, - "ReadableByteStream": false, "ReadableStream": false, + "registerProcessor": false, + "RemotePlayback": false, "removeEventListener": false, "Request": false, "requestAnimationFrame": false, "requestIdleCallback": false, "resizeBy": false, + "ResizeObserver": false, + "ResizeObserverEntry": false, "resizeTo": false, "Response": false, + "RTCCertificate": false, + "RTCDataChannel": false, + "RTCDataChannelEvent": false, + "RTCDtlsTransport": false, "RTCIceCandidate": false, - "RTCSessionDescription": false, + "RTCIceGatherer": false, + "RTCIceTransport": false, "RTCPeerConnection": false, + "RTCPeerConnectionIceEvent": false, + "RTCRtpContributingSource": false, + "RTCRtpReceiver": false, + "RTCRtpSender": false, + "RTCSctpTransport": false, + "RTCSessionDescription": false, + "RTCStatsReport": false, + "RTCTrackEvent": false, "screen": false, "Screen": false, "screenLeft": false, @@ -36489,28 +101505,26 @@ module.exports={ "setInterval": false, "setTimeout": false, "ShadowRoot": false, - "SharedKeyframeList": false, "SharedWorker": false, - "showModalDialog": false, - "SiteBoundCredential": false, + "SourceBuffer": false, + "SourceBufferList": false, "speechSynthesis": false, "SpeechSynthesisEvent": false, "SpeechSynthesisUtterance": false, + "StaticRange": false, "status": false, "statusbar": false, + "StereoPannerNode": false, "stop": false, "Storage": false, "StorageEvent": false, + "StorageManager": false, "styleMedia": false, "StyleSheet": false, "StyleSheetList": false, "SubtleCrypto": false, "SVGAElement": false, - "SVGAltGlyphDefElement": false, - "SVGAltGlyphElement": false, - "SVGAltGlyphItemElement": false, "SVGAngle": false, - "SVGAnimateColorElement": false, "SVGAnimatedAngle": false, "SVGAnimatedBoolean": false, "SVGAnimatedEnumeration": false, @@ -36519,8 +101533,6 @@ module.exports={ "SVGAnimatedLengthList": false, "SVGAnimatedNumber": false, "SVGAnimatedNumberList": false, - "SVGAnimatedPathData": false, - "SVGAnimatedPoints": false, "SVGAnimatedPreserveAspectRatio": false, "SVGAnimatedRect": false, "SVGAnimatedString": false, @@ -36531,22 +101543,12 @@ module.exports={ "SVGAnimationElement": false, "SVGCircleElement": false, "SVGClipPathElement": false, - "SVGColor": false, - "SVGColorProfileElement": false, - "SVGColorProfileRule": false, "SVGComponentTransferFunctionElement": false, - "SVGCSSRule": false, - "SVGCursorElement": false, "SVGDefsElement": false, "SVGDescElement": false, "SVGDiscardElement": false, - "SVGDocument": false, "SVGElement": false, - "SVGElementInstance": false, - "SVGElementInstanceList": false, "SVGEllipseElement": false, - "SVGEvent": false, - "SVGExternalResourcesRequired": false, "SVGFEBlendElement": false, "SVGFEColorMatrixElement": false, "SVGFEComponentTransferElement": false, @@ -36573,61 +101575,24 @@ module.exports={ "SVGFETileElement": false, "SVGFETurbulenceElement": false, "SVGFilterElement": false, - "SVGFilterPrimitiveStandardAttributes": false, - "SVGFitToViewBox": false, - "SVGFontElement": false, - "SVGFontFaceElement": false, - "SVGFontFaceFormatElement": false, - "SVGFontFaceNameElement": false, - "SVGFontFaceSrcElement": false, - "SVGFontFaceUriElement": false, "SVGForeignObjectElement": false, "SVGGElement": false, "SVGGeometryElement": false, - "SVGGlyphElement": false, - "SVGGlyphRefElement": false, "SVGGradientElement": false, "SVGGraphicsElement": false, - "SVGHKernElement": false, - "SVGICCColor": false, "SVGImageElement": false, - "SVGLangSpace": false, "SVGLength": false, "SVGLengthList": false, "SVGLinearGradientElement": false, "SVGLineElement": false, - "SVGLocatable": false, "SVGMarkerElement": false, "SVGMaskElement": false, "SVGMatrix": false, "SVGMetadataElement": false, - "SVGMissingGlyphElement": false, "SVGMPathElement": false, "SVGNumber": false, "SVGNumberList": false, - "SVGPaint": false, "SVGPathElement": false, - "SVGPathSeg": false, - "SVGPathSegArcAbs": false, - "SVGPathSegArcRel": false, - "SVGPathSegClosePath": false, - "SVGPathSegCurvetoCubicAbs": false, - "SVGPathSegCurvetoCubicRel": false, - "SVGPathSegCurvetoCubicSmoothAbs": false, - "SVGPathSegCurvetoCubicSmoothRel": false, - "SVGPathSegCurvetoQuadraticAbs": false, - "SVGPathSegCurvetoQuadraticRel": false, - "SVGPathSegCurvetoQuadraticSmoothAbs": false, - "SVGPathSegCurvetoQuadraticSmoothRel": false, - "SVGPathSegLinetoAbs": false, - "SVGPathSegLinetoHorizontalAbs": false, - "SVGPathSegLinetoHorizontalRel": false, - "SVGPathSegLinetoRel": false, - "SVGPathSegLinetoVerticalAbs": false, - "SVGPathSegLinetoVerticalRel": false, - "SVGPathSegList": false, - "SVGPathSegMovetoAbs": false, - "SVGPathSegMovetoRel": false, "SVGPatternElement": false, "SVGPoint": false, "SVGPointList": false, @@ -36637,35 +101602,26 @@ module.exports={ "SVGRadialGradientElement": false, "SVGRect": false, "SVGRectElement": false, - "SVGRenderingIntent": false, "SVGScriptElement": false, "SVGSetElement": false, "SVGStopElement": false, "SVGStringList": false, - "SVGStylable": false, "SVGStyleElement": false, "SVGSVGElement": false, "SVGSwitchElement": false, "SVGSymbolElement": false, - "SVGTests": false, "SVGTextContentElement": false, "SVGTextElement": false, "SVGTextPathElement": false, "SVGTextPositioningElement": false, "SVGTitleElement": false, "SVGTransform": false, - "SVGTransformable": false, "SVGTransformList": false, - "SVGTRefElement": false, "SVGTSpanElement": false, "SVGUnitTypes": false, - "SVGURIReference": false, "SVGUseElement": false, "SVGViewElement": false, - "SVGViewSpec": false, - "SVGVKernElement": false, - "SVGZoomAndPan": false, - "SVGZoomEvent": false, + "TaskAttributionTiming": false, "Text": false, "TextDecoder": false, "TextEncoder": false, @@ -36675,7 +101631,6 @@ module.exports={ "TextTrackCue": false, "TextTrackCueList": false, "TextTrackList": false, - "TimeEvent": false, "TimeRanges": false, "toolbar": false, "top": false, @@ -36689,40 +101644,46 @@ module.exports={ "URL": false, "URLSearchParams": false, "ValidityState": false, + "visualViewport": false, + "VisualViewport": false, "VTTCue": false, "WaveShaperNode": false, + "WebAssembly": false, + "WebGL2RenderingContext": false, "WebGLActiveInfo": false, "WebGLBuffer": false, "WebGLContextEvent": false, "WebGLFramebuffer": false, "WebGLProgram": false, + "WebGLQuery": false, "WebGLRenderbuffer": false, "WebGLRenderingContext": false, + "WebGLSampler": false, "WebGLShader": false, "WebGLShaderPrecisionFormat": false, + "WebGLSync": false, "WebGLTexture": false, + "WebGLTransformFeedback": false, "WebGLUniformLocation": false, + "WebGLVertexArrayObject": false, "WebSocket": false, "WheelEvent": false, "window": false, "Window": false, "Worker": false, - "XDomainRequest": false, + "WritableStream": false, "XMLDocument": false, "XMLHttpRequest": false, "XMLHttpRequestEventTarget": false, - "XMLHttpRequestProgressEvent": false, "XMLHttpRequestUpload": false, "XMLSerializer": false, "XPathEvaluator": false, - "XPathException": false, "XPathExpression": false, - "XPathNamespace": false, - "XPathNSResolver": false, "XPathResult": false, "XSLTProcessor": false }, "worker": { + "addEventListener": false, "applicationCache": false, "atob": false, "Blob": false, @@ -36777,6 +101738,8 @@ module.exports={ "PerformanceTiming": false, "postMessage": true, "Promise": false, + "queueMicrotask": false, + "removeEventListener": false, "Request": false, "Response": false, "self": true, @@ -36789,34 +101752,37 @@ module.exports={ "URLSearchParams": false, "WebSocket": false, "Worker": false, + "WorkerGlobalScope": false, "XMLHttpRequest": false }, "node": { "__dirname": false, "__filename": false, - "arguments": false, "Buffer": false, "clearImmediate": false, "clearInterval": false, "clearTimeout": false, "console": false, "exports": true, - "GLOBAL": false, "global": false, "Intl": false, "module": false, "process": false, + "queueMicrotask": false, "require": false, - "root": false, "setImmediate": false, "setInterval": false, - "setTimeout": false + "setTimeout": false, + "TextDecoder": false, + "TextEncoder": false, + "URL": false, + "URLSearchParams": false }, "commonjs": { "exports": true, + "global": false, "module": false, - "require": false, - "global": false + "require": false }, "amd": { "define": false, @@ -36870,13 +101836,11 @@ module.exports={ "afterEach": false, "beforeAll": false, "beforeEach": false, - "check": false, "describe": false, "expect": false, - "gen": false, - "it": false, "fdescribe": false, "fit": false, + "it": false, "jest": false, "pit": false, "require": false, @@ -36956,8 +101920,8 @@ module.exports={ "com": false, "edu": false, "exit": false, - "Java": false, "java": false, + "Java": false, "javafx": false, "JavaImporter": false, "javax": false, @@ -36987,7 +101951,8 @@ module.exports={ "jQuery": false }, "yui": { - "Y": false, + "YAHOO": false, + "YAHOO_config": false, "YUI": false, "YUI_config": false }, @@ -37005,8 +101970,8 @@ module.exports={ "exit": false, "find": false, "grep": false, - "ls": false, "ln": false, + "ls": false, "mkdir": false, "mv": false, "popd": false, @@ -37062,20 +102027,20 @@ module.exports={ "Try": false }, "meteor": { - "$": false, "_": false, + "$": false, "Accounts": false, "AccountsClient": false, - "AccountsServer": false, "AccountsCommon": false, + "AccountsServer": false, "App": false, "Assets": false, "Blaze": false, "check": false, "Cordova": false, "DDP": false, - "DDPServer": false, "DDPRateLimiter": false, + "DDPServer": false, "Deps": false, "EJSON": false, "Email": false, @@ -37152,25 +102117,99 @@ module.exports={ "Ref": false }, "serviceworker": { - "caches": false, + "addEventListener": false, + "applicationCache": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, "Cache": false, + "caches": false, "CacheStorage": false, + "clearInterval": false, + "clearTimeout": false, "Client": false, "clients": false, "Clients": false, + "close": true, + "console": false, "ExtendableEvent": false, "ExtendableMessageEvent": false, + "fetch": false, "FetchEvent": false, + "FileReaderSync": false, + "FormData": false, + "Headers": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "ImageData": false, "importScripts": false, + "indexedDB": false, + "location": false, + "MessageChannel": false, + "MessagePort": false, + "name": false, + "navigator": false, + "Notification": false, + "onclose": true, + "onconnect": true, + "onerror": true, + "onfetch": true, + "oninstall": true, + "onlanguagechange": true, + "onmessage": true, + "onmessageerror": true, + "onnotificationclick": true, + "onnotificationclose": true, + "onoffline": true, + "ononline": true, + "onpush": true, + "onpushsubscriptionchange": true, + "onrejectionhandled": true, + "onsync": true, + "onunhandledrejection": true, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "postMessage": true, + "Promise": false, + "queueMicrotask": false, "registration": false, + "removeEventListener": false, + "Request": false, + "Response": false, "self": false, "ServiceWorker": false, "ServiceWorkerContainer": false, "ServiceWorkerGlobalScope": false, "ServiceWorkerMessageEvent": false, "ServiceWorkerRegistration": false, + "setInterval": false, + "setTimeout": false, "skipWaiting": false, - "WindowClient": false + "TextDecoder": false, + "TextEncoder": false, + "URL": false, + "URLSearchParams": false, + "WebSocket": false, + "WindowClient": false, + "Worker": false, + "WorkerGlobalScope": false, + "XMLHttpRequest": false }, "atomtest": { "advanceClock": false, @@ -37189,19 +102228,21 @@ module.exports={ "currentURL": false, "fillIn": false, "find": false, + "findAll": false, "findWithAssert": false, "keyEvent": false, "pauseTest": false, "resumeTest": false, "triggerEvent": false, - "visit": false + "visit": false, + "wait": false }, "protractor": { "$": false, "$$": false, "browser": false, - "By": false, "by": false, + "By": false, "DartObject": false, "element": false, "protractor": false @@ -37211,7 +102252,9 @@ module.exports={ "clearTimeout": false, "console": false, "setInterval": false, - "setTimeout": false + "setTimeout": false, + "URL": false, + "URLSearchParams": false }, "webextensions": { "browser": false, @@ -37219,6 +102262,10 @@ module.exports={ "opr": false }, "greasemonkey": { + "cloneInto": false, + "createObjectIn": false, + "exportFunction": false, + "GM": false, "GM_addStyle": false, "GM_deleteValue": false, "GM_getResourceText": false, @@ -37233,2048 +102280,4383 @@ module.exports={ "GM_setValue": false, "GM_xmlhttpRequest": false, "unsafeWindow": false + }, + "devtools": { + "$": false, + "$_": false, + "$$": false, + "$0": false, + "$1": false, + "$2": false, + "$3": false, + "$4": false, + "$x": false, + "chrome": false, + "clear": false, + "copy": false, + "debug": false, + "dir": false, + "dirxml": false, + "getEventListeners": false, + "inspect": false, + "keys": false, + "monitor": false, + "monitorEvents": false, + "profile": false, + "profileEnd": false, + "queryObjects": false, + "table": false, + "undebug": false, + "unmonitor": false, + "unmonitorEvents": false, + "values": false } } -},{}],289:[function(require,module,exports){ -module.exports = require('./globals.json'); +},{}],838:[function(require,module,exports){ +'use strict'; + +module.exports = require('./globals.json'); + +},{"./globals.json":837}],839:[function(require,module,exports){ +"use strict"; + +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = e << mLen | m; + eLen += mLen; + + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +}; + +},{}],840:[function(require,module,exports){ +(function (process){ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict'; +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +var invariant = function invariant(condition, format, a, b, c, d, e, f) { + if (process.env.NODE_ENV !== 'production') { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + + if (format === undefined) { + error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error(format.replace(/%s/g, function () { + return args[argIndex++]; + })); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + + throw error; + } +}; + +module.exports = invariant; + +}).call(this,require('_process')) +},{"_process":1054}],841:[function(require,module,exports){ +"use strict"; + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer); +}; + +function isBuffer(obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); +} // For Node v0.10 support. Remove this eventually. + + +function isSlowBuffer(obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)); +} + +},{}],842:[function(require,module,exports){ +'use strict'; + +module.exports = function () { + function _min(d0, d1, d2, bx, ay) { + return d0 < d1 || d2 < d1 ? d0 > d2 ? d2 + 1 : d0 + 1 : bx === ay ? d1 : d1 + 1; + } + + return function (a, b) { + if (a === b) { + return 0; + } + + if (a.length > b.length) { + var tmp = a; + a = b; + b = tmp; + } + + var la = a.length; + var lb = b.length; + + while (la > 0 && a.charCodeAt(la - 1) === b.charCodeAt(lb - 1)) { + la--; + lb--; + } + + var offset = 0; + + while (offset < la && a.charCodeAt(offset) === b.charCodeAt(offset)) { + offset++; + } + + la -= offset; + lb -= offset; + + if (la === 0 || lb < 3) { + return lb; + } + + var x = 0; + var y; + var d0; + var d1; + var d2; + var d3; + var dd; + var dy; + var ay; + var bx0; + var bx1; + var bx2; + var bx3; + var vector = []; + + for (y = 0; y < la; y++) { + vector.push(y + 1); + vector.push(a.charCodeAt(offset + y)); + } + + var len = vector.length - 1; + + for (; x < lb - 3;) { + bx0 = b.charCodeAt(offset + (d0 = x)); + bx1 = b.charCodeAt(offset + (d1 = x + 1)); + bx2 = b.charCodeAt(offset + (d2 = x + 2)); + bx3 = b.charCodeAt(offset + (d3 = x + 3)); + dd = x += 4; + + for (y = 0; y < len; y += 2) { + dy = vector[y]; + ay = vector[y + 1]; + d0 = _min(dy, d0, d1, bx0, ay); + d1 = _min(d0, d1, d2, bx1, ay); + d2 = _min(d1, d2, d3, bx2, ay); + dd = _min(d2, d3, dd, bx3, ay); + vector[y] = dd; + d3 = d2; + d2 = d1; + d1 = d0; + d0 = dy; + } + } + + for (; x < lb;) { + bx0 = b.charCodeAt(offset + (d0 = x)); + dd = ++x; + + for (y = 0; y < len; y += 2) { + dy = vector[y]; + vector[y] = dd = _min(dy, d0, dd, bx0, vector[y + 1]); + d0 = dy; + } + } + + return dd; + }; +}(); + +},{}],843:[function(require,module,exports){ +"use strict"; + +// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell +// License: MIT. (See LICENSE.) +Object.defineProperty(exports, "__esModule", { + value: true +}); // This regex comes from regex.coffee, and is inserted here by generate-index.js +// (run `npm run build`). + +exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; + +exports.matchToToken = function (match) { + var token = { + type: "invalid", + value: match[0], + closed: undefined + }; + if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace"; + return token; +}; + +},{}],844:[function(require,module,exports){ +(function (Buffer){ +'use strict'; + +var object = {}; +var hasOwnProperty = object.hasOwnProperty; + +var forOwn = function forOwn(object, callback) { + for (var key in object) { + if (hasOwnProperty.call(object, key)) { + callback(key, object[key]); + } + } +}; + +var extend = function extend(destination, source) { + if (!source) { + return destination; + } + + forOwn(source, function (key, value) { + destination[key] = value; + }); + return destination; +}; + +var forEach = function forEach(array, callback) { + var length = array.length; + var index = -1; + + while (++index < length) { + callback(array[index]); + } +}; + +var toString = object.toString; +var isArray = Array.isArray; +var isBuffer = Buffer.isBuffer; + +var isObject = function isObject(value) { + // This is a very simple check, but it’s good enough for what we need. + return toString.call(value) == '[object Object]'; +}; + +var isString = function isString(value) { + return typeof value == 'string' || toString.call(value) == '[object String]'; +}; + +var isNumber = function isNumber(value) { + return typeof value == 'number' || toString.call(value) == '[object Number]'; +}; + +var isFunction = function isFunction(value) { + return typeof value == 'function'; +}; + +var isMap = function isMap(value) { + return toString.call(value) == '[object Map]'; +}; + +var isSet = function isSet(value) { + return toString.call(value) == '[object Set]'; +}; +/*--------------------------------------------------------------------------*/ +// https://mathiasbynens.be/notes/javascript-escapes#single + + +var singleEscapes = { + '"': '\\"', + '\'': '\\\'', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t' // `\v` is omitted intentionally, because in IE < 9, '\v' == 'v'. + // '\v': '\\x0B' + +}; +var regexSingleEscape = /["'\\\b\f\n\r\t]/; +var regexDigit = /[0-9]/; +var regexWhitelist = /[ !#-&\(-\[\]-_a-~]/; + +var jsesc = function jsesc(argument, options) { + var increaseIndentation = function increaseIndentation() { + oldIndent = indent; + ++options.indentLevel; + indent = options.indent.repeat(options.indentLevel); + }; // Handle options + + + var defaults = { + 'escapeEverything': false, + 'minimal': false, + 'isScriptContext': false, + 'quotes': 'single', + 'wrap': false, + 'es6': false, + 'json': false, + 'compact': true, + 'lowercaseHex': false, + 'numbers': 'decimal', + 'indent': '\t', + 'indentLevel': 0, + '__inline1__': false, + '__inline2__': false + }; + var json = options && options.json; + + if (json) { + defaults.quotes = 'double'; + defaults.wrap = true; + } + + options = extend(defaults, options); + + if (options.quotes != 'single' && options.quotes != 'double' && options.quotes != 'backtick') { + options.quotes = 'single'; + } + + var quote = options.quotes == 'double' ? '"' : options.quotes == 'backtick' ? '`' : '\''; + var compact = options.compact; + var lowercaseHex = options.lowercaseHex; + var indent = options.indent.repeat(options.indentLevel); + var oldIndent = ''; + var inline1 = options.__inline1__; + var inline2 = options.__inline2__; + var newLine = compact ? '' : '\n'; + var result; + var isEmpty = true; + var useBinNumbers = options.numbers == 'binary'; + var useOctNumbers = options.numbers == 'octal'; + var useDecNumbers = options.numbers == 'decimal'; + var useHexNumbers = options.numbers == 'hexadecimal'; + + if (json && argument && isFunction(argument.toJSON)) { + argument = argument.toJSON(); + } + + if (!isString(argument)) { + if (isMap(argument)) { + if (argument.size == 0) { + return 'new Map()'; + } + + if (!compact) { + options.__inline1__ = true; + options.__inline2__ = false; + } + + return 'new Map(' + jsesc(Array.from(argument), options) + ')'; + } + + if (isSet(argument)) { + if (argument.size == 0) { + return 'new Set()'; + } + + return 'new Set(' + jsesc(Array.from(argument), options) + ')'; + } + + if (isBuffer(argument)) { + if (argument.length == 0) { + return 'Buffer.from([])'; + } + + return 'Buffer.from(' + jsesc(Array.from(argument), options) + ')'; + } + + if (isArray(argument)) { + result = []; + options.wrap = true; + + if (inline1) { + options.__inline1__ = false; + options.__inline2__ = true; + } + + if (!inline2) { + increaseIndentation(); + } + + forEach(argument, function (value) { + isEmpty = false; + + if (inline2) { + options.__inline2__ = false; + } + + result.push((compact || inline2 ? '' : indent) + jsesc(value, options)); + }); + + if (isEmpty) { + return '[]'; + } + + if (inline2) { + return '[' + result.join(', ') + ']'; + } + + return '[' + newLine + result.join(',' + newLine) + newLine + (compact ? '' : oldIndent) + ']'; + } else if (isNumber(argument)) { + if (json) { + // Some number values (e.g. `Infinity`) cannot be represented in JSON. + return JSON.stringify(argument); + } + + if (useDecNumbers) { + return String(argument); + } + + if (useHexNumbers) { + var hexadecimal = argument.toString(16); + + if (!lowercaseHex) { + hexadecimal = hexadecimal.toUpperCase(); + } + + return '0x' + hexadecimal; + } + + if (useBinNumbers) { + return '0b' + argument.toString(2); + } + + if (useOctNumbers) { + return '0o' + argument.toString(8); + } + } else if (!isObject(argument)) { + if (json) { + // For some values (e.g. `undefined`, `function` objects), + // `JSON.stringify(value)` returns `undefined` (which isn’t valid + // JSON) instead of `'null'`. + return JSON.stringify(argument) || 'null'; + } + + return String(argument); + } else { + // it’s an object + result = []; + options.wrap = true; + increaseIndentation(); + forOwn(argument, function (key, value) { + isEmpty = false; + result.push((compact ? '' : indent) + jsesc(key, options) + ':' + (compact ? '' : ' ') + jsesc(value, options)); + }); + + if (isEmpty) { + return '{}'; + } + + return '{' + newLine + result.join(',' + newLine) + newLine + (compact ? '' : oldIndent) + '}'; + } + } + + var string = argument; // Loop over each code unit in the string and escape it + + var index = -1; + var length = string.length; + result = ''; + + while (++index < length) { + var character = string.charAt(index); + + if (options.es6) { + var first = string.charCodeAt(index); + + if ( // check if it’s the start of a surrogate pair + first >= 0xD800 && first <= 0xDBFF && // high surrogate + length > index + 1 // there is a next code unit + ) { + var second = string.charCodeAt(index + 1); + + if (second >= 0xDC00 && second <= 0xDFFF) { + // low surrogate + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + var codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + + var _hexadecimal2 = codePoint.toString(16); + + if (!lowercaseHex) { + _hexadecimal2 = _hexadecimal2.toUpperCase(); + } + + result += "\\u{" + _hexadecimal2 + '}'; + ++index; + continue; + } + } + } + + if (!options.escapeEverything) { + if (regexWhitelist.test(character)) { + // It’s a printable ASCII character that is not `"`, `'` or `\`, + // so don’t escape it. + result += character; + continue; + } + + if (character == '"') { + result += quote == character ? '\\"' : character; + continue; + } + + if (character == '`') { + result += quote == character ? '\\`' : character; + continue; + } + + if (character == '\'') { + result += quote == character ? '\\\'' : character; + continue; + } + } + + if (character == '\0' && !json && !regexDigit.test(string.charAt(index + 1))) { + result += '\\0'; + continue; + } + + if (regexSingleEscape.test(character)) { + // no need for a `hasOwnProperty` check here + result += singleEscapes[character]; + continue; + } + + var charCode = character.charCodeAt(0); + + if (options.minimal && charCode != 0x2028 && charCode != 0x2029) { + result += character; + continue; + } + + var _hexadecimal = charCode.toString(16); + + if (!lowercaseHex) { + _hexadecimal = _hexadecimal.toUpperCase(); + } + + var longhand = _hexadecimal.length > 2 || json; + + var escaped = '\\' + (longhand ? 'u' : 'x') + ('0000' + _hexadecimal).slice(longhand ? -4 : -2); + + result += escaped; + continue; + } + + if (options.wrap) { + result = quote + result + quote; + } + + if (quote == '`') { + result = result.replace(/\$\{/g, '\\\$\{'); + } + + if (options.isScriptContext) { + // https://mathiasbynens.be/notes/etago + return result.replace(/<\/(script|style)/gi, '<\\/$1').replace(/ regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + case "BreakStatement": + self.emitAbruptCompletion({ + type: "break", + target: self.leapManager.getBreakLoc(stmt.label) + }); + break; - this.debug(this.pattern, set) + case "ContinueStatement": + self.emitAbruptCompletion({ + type: "continue", + target: self.leapManager.getContinueLoc(stmt.label) + }); + break; - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + case "SwitchStatement": + // Always save the discriminant into a temporary variable in case the + // test expressions overwrite values like context.sent. + var disc = self.emitAssign(self.makeTempVar(), self.explodeExpression(path.get("discriminant"))); + after = this.loc(); + var defaultLoc = this.loc(); + var condition = defaultLoc; + var caseLocs = []; // If there are no cases, .cases might be undefined. - this.debug(this.pattern, set) + var cases = stmt.cases || []; - this.set = set -} + for (var i = cases.length - 1; i >= 0; --i) { + var c = cases[i]; + t.assertSwitchCase(c); -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 + if (c.test) { + condition = t.conditionalExpression(t.binaryExpression("===", t.cloneDeep(disc), c.test), caseLocs[i] = this.loc(), condition); + } else { + caseLocs[i] = defaultLoc; + } + } - if (options.nonegate) return + var discriminant = path.get("discriminant"); + util.replaceWithOrRemove(discriminant, condition); + self.jump(self.explodeExpression(discriminant)); + self.leapManager.withEntry(new leap.SwitchEntry(after), function () { + path.get("cases").forEach(function (casePath) { + var i = casePath.key; + self.mark(caseLocs[i]); + casePath.get("consequent").forEach(function (path) { + self.explodeStatement(path); + }); + }); + }); + self.mark(after); - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } + if (defaultLoc.value === -1) { + self.mark(defaultLoc); - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + _assert["default"].strictEqual(after.value, defaultLoc.value); + } -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} + break; -Minimatch.prototype.braceExpand = braceExpand + case "IfStatement": + var elseLoc = stmt.alternate && this.loc(); + after = this.loc(); + self.jumpIfNot(self.explodeExpression(path.get("test")), elseLoc || after); + self.explodeStatement(path.get("consequent")); -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } + if (elseLoc) { + self.jump(after); + self.mark(elseLoc); + self.explodeStatement(path.get("alternate")); + } - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + self.mark(after); + break; - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } + case "ReturnStatement": + self.emitAbruptCompletion({ + type: "return", + value: self.explodeExpression(path.get("argument")) + }); + break; - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } + case "WithStatement": + throw new Error("WithStatement not supported in generator functions."); - return expand(pattern) -} + case "TryStatement": + after = this.loc(); + var handler = stmt.handler; + var catchLoc = handler && this.loc(); + var catchEntry = catchLoc && new leap.CatchEntry(catchLoc, handler.param); + var finallyLoc = stmt.finalizer && this.loc(); + var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); + var tryEntry = new leap.TryEntry(self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry); + self.tryEntries.push(tryEntry); + self.updateContextPrevLoc(tryEntry.firstLoc); + self.leapManager.withEntry(tryEntry, function () { + self.explodeStatement(path.get("block")); -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } - - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } - - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } - - clearStateChar() - re += '|' - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += '\\' + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } - - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue + if (catchLoc) { + if (finallyLoc) { + // If we have both a catch block and a finally block, then + // because we emit the catch block first, we need to jump over + // it to the finally block. + self.jump(finallyLoc); + } else { + // If there is no finally block, then we need to jump over the + // catch block to the fall-through location. + self.jump(after); } - } - // finish up the class. - hasMagic = true - inClass = false - re += c - continue + self.updateContextPrevLoc(self.mark(catchLoc)); + var bodyPath = path.get("handler.body"); + var safeParam = self.makeTempVar(); + self.clearPendingException(tryEntry.firstLoc, safeParam); + bodyPath.traverse(catchParamVisitor, { + getSafeParam: function getSafeParam() { + return t.cloneDeep(safeParam); + }, + catchParamName: handler.param.name + }); + self.leapManager.withEntry(catchEntry, function () { + self.explodeStatement(bodyPath); + }); + } - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) + if (finallyLoc) { + self.updateContextPrevLoc(self.mark(finallyLoc)); + self.leapManager.withEntry(finallyEntry, function () { + self.explodeStatement(path.get("finalizer")); + }); + self.emit(t.returnStatement(t.callExpression(self.contextProperty("finish"), [finallyEntry.firstLoc]))); + } + }); + self.mark(after); + break; - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type + case "ThrowStatement": + self.emit(t.throwStatement(self.explodeExpression(path.get("argument")))); + break; - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail + default: + throw new Error("unknown Statement of type " + JSON.stringify(stmt.type)); } +}; - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' +var catchParamVisitor = { + Identifier: function Identifier(path, state) { + if (path.node.name === state.catchParamName && util.isReference(path)) { + util.replaceWithOrRemove(path, state.getSafeParam()); + } + }, + Scope: function Scope(path, state) { + if (path.scope.hasOwnBinding(state.catchParamName)) { + // Don't descend into nested scopes that shadow the catch + // parameter with their own declarations. + path.skip(); + } } +}; - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true +Ep.emitAbruptCompletion = function (record) { + if (!isValidCompletion(record)) { + _assert["default"].ok(false, "invalid completion record: " + JSON.stringify(record)); } - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] - - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) - - nlLast += nlAfter + _assert["default"].notStrictEqual(record.type, "normal", "normal completions are not abrupt"); - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter + var t = util.getTypes(); + var abruptArgs = [t.stringLiteral(record.type)]; - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + if (record.type === "break" || record.type === "continue") { + t.assertLiteral(record.target); + abruptArgs[1] = this.insertedLocs.has(record.target) ? record.target : t.cloneDeep(record.target); + } else if (record.type === "return" || record.type === "throw") { + if (record.value) { + t.assertExpression(record.value); + abruptArgs[1] = this.insertedLocs.has(record.value) ? record.value : t.cloneDeep(record.value); } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe } - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } + this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"), abruptArgs))); +}; - if (addPatternStart) { - re = patternStart + re - } +function isValidCompletion(record) { + var type = record.type; - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] + if (type === "normal") { + return !hasOwn.call(record, "target"); } - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) + if (type === "break" || type === "continue") { + return !hasOwn.call(record, "value") && util.getTypes().isLiteral(record.target); } - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') + if (type === "return" || type === "throw") { + return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); } - regExp._glob = pattern - regExp._src = re + return false; +} // Not all offsets into emitter.listing are potential jump targets. For +// example, execution typically falls into the beginning of a try block +// without jumping directly there. This method returns the current offset +// without marking it, so that a switch case will not necessarily be +// generated for this offset (I say "not necessarily" because the same +// location might end up being marked in the process of emitting other +// statements). There's no logical harm in marking such locations as jump +// targets, but minimizing the number of switch cases keeps the generated +// code shorter. - return regExp -} -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} +Ep.getUnmarkedCurrentLoc = function () { + return util.getTypes().numericLiteral(this.listing.length); +}; // The context.prev property takes the value of context.next whenever we +// evaluate the switch statement discriminant, which is generally good +// enough for tracking the last location we jumped to, but sometimes +// context.prev needs to be more precise, such as when we fall +// successfully out of a try block and into a finally block without +// jumping. This method exists to update context.prev to the freshest +// available location. If we were implementing a full interpreter, we +// would know the location of the current instruction with complete +// precision at all times, but we don't have that luxury here, as it would +// be costly and verbose to set context.prev before every statement. -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set +Ep.updateContextPrevLoc = function (loc) { + var t = util.getTypes(); - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options + if (loc) { + t.assertLiteral(loc); - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' + if (loc.value === -1) { + // If an uninitialized location literal was passed in, set its value + // to the current this.listing.length. + loc.value = this.listing.length; + } else { + // Otherwise assert that the location matches the current offset. + _assert["default"].strictEqual(loc.value, this.listing.length); + } + } else { + loc = this.getUnmarkedCurrentLoc(); + } // Make sure context.prev is up to date in case we fell into this try + // statement without jumping to it. TODO Consider avoiding this + // assignment when we know control must have jumped here. - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' + this.emitAssign(this.contextProperty("prev"), loc); +}; - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' +Ep.explodeExpression = function (path, ignoreResult) { + var t = util.getTypes(); + var expr = path.node; - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false + if (expr) { + t.assertExpression(expr); + } else { + return expr; } - return this.regexp -} -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list -} + var self = this; + var result; // Used optionally by several cases below. + + var after; -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' + function finish(expr) { + t.assertExpression(expr); - if (f === '/' && partial) return true + if (ignoreResult) { + self.emit(expr); + } else { + return expr; + } + } // If the expression does not contain a leap, then we either emit the + // expression as a standalone statement or return it whole. - var options = this.options - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } + if (!meta.containsLeap(expr)) { + return finish(expr); + } // If any child contains a leap (such as a yield or labeled continue or + // break statement), then any sibling subexpressions will almost + // certainly have to be exploded in order to maintain the order of their + // side effects relative to the leaping child(ren). - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. + var hasLeapingChildren = meta.containsLeap.onlyChildren(expr); // In order to save the rest of explodeExpression from a combinatorial + // trainwreck of special cases, explodeViaTempVar is responsible for + // deciding when a subexpression needs to be "exploded," which is my + // very technical term for emitting the subexpression as an assignment + // to a temporary variable and the substituting the temporary variable + // for the original subexpression. Think of exploded view diagrams, not + // Michael Bay movies. The point of exploding subexpressions is to + // control the precise order in which the generated code realizes the + // side effects of those subexpressions. - var set = this.set - this.debug(this.pattern, 'set', set) + function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { + _assert["default"].ok(!ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?"); - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } + var result = self.explodeExpression(childPath, ignoreChildResult); - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate + if (ignoreChildResult) {// Side effects already emitted above. + } else if (tempVar || hasLeapingChildren && !t.isLiteral(result)) { + // If tempVar was provided, then the result will always be assigned + // to it, even if the result does not otherwise need to be assigned + // to a temporary variable. When no tempVar is provided, we have + // the flexibility to decide whether a temporary variable is really + // necessary. Unfortunately, in general, a temporary variable is + // required whenever any child contains a yield expression, since it + // is difficult to prove (at all, let alone efficiently) whether + // this result would evaluate to the same value before and after the + // yield (see #206). One narrow case where we can prove it doesn't + // matter (and thus we do not need a temporary variable) is when the + // result in question is a Literal value. + result = self.emitAssign(tempVar || self.makeTempVar(), result); } - } - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} + return result; + } // If ignoreResult is true, then we must take full responsibility for + // emitting the expression with all its side effects, and we should not + // return a result. -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) + switch (expr.type) { + case "MemberExpression": + return finish(t.memberExpression(self.explodeExpression(path.get("object")), expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property, expr.computed)); - this.debug('matchOne', file.length, pattern.length) + case "CallExpression": + var calleePath = path.get("callee"); + var argsPath = path.get("arguments"); + var newCallee; + var newArgs = []; + var hasLeapingArgs = false; + argsPath.forEach(function (argPath) { + hasLeapingArgs = hasLeapingArgs || meta.containsLeap(argPath.node); + }); - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] + if (t.isMemberExpression(calleePath.node)) { + if (hasLeapingArgs) { + // If the arguments of the CallExpression contained any yield + // expressions, then we need to be sure to evaluate the callee + // before evaluating the arguments, but if the callee was a member + // expression, then we must be careful that the object of the + // member expression still gets bound to `this` for the call. + var newObject = explodeViaTempVar( // Assign the exploded callee.object expression to a temporary + // variable so that we can use it twice without reevaluating it. + self.makeTempVar(), calleePath.get("object")); + var newProperty = calleePath.node.computed ? explodeViaTempVar(null, calleePath.get("property")) : calleePath.node.property; + newArgs.unshift(newObject); + newCallee = t.memberExpression(t.memberExpression(t.cloneDeep(newObject), newProperty, calleePath.node.computed), t.identifier("call"), false); + } else { + newCallee = self.explodeExpression(calleePath); + } + } else { + newCallee = explodeViaTempVar(null, calleePath); - this.debug(pattern, p, f) + if (t.isMemberExpression(newCallee)) { + // If the callee was not previously a MemberExpression, then the + // CallExpression was "unqualified," meaning its `this` object + // should be the global object. If the exploded expression has + // become a MemberExpression (e.g. a context property, probably a + // temporary variable), then we need to force it to be unqualified + // by using the (0, object.property)(...) trick; otherwise, it + // will receive the object of the MemberExpression as its `this` + // object. + newCallee = t.sequenceExpression([t.numericLiteral(0), t.cloneDeep(newCallee)]); + } + } - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false + argsPath.forEach(function (argPath) { + newArgs.push(explodeViaTempVar(null, argPath)); + }); + return finish(t.callExpression(newCallee, newArgs.map(function (arg) { + return t.cloneDeep(arg); + }))); - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) + case "NewExpression": + return finish(t.newExpression(explodeViaTempVar(null, path.get("callee")), path.get("arguments").map(function (argPath) { + return explodeViaTempVar(null, argPath); + }))); - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true + case "ObjectExpression": + return finish(t.objectExpression(path.get("properties").map(function (propPath) { + if (propPath.isObjectProperty()) { + return t.objectProperty(propPath.node.key, explodeViaTempVar(null, propPath.get("value")), propPath.node.computed); } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ + return propPath.node; } - } + }))); - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } + case "ArrayExpression": + return finish(t.arrayExpression(path.get("elements").map(function (elemPath) { + return explodeViaTempVar(null, elemPath); + }))); - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } + case "SequenceExpression": + var lastIndex = expr.expressions.length - 1; + path.get("expressions").forEach(function (exprPath) { + if (exprPath.key === lastIndex) { + result = self.explodeExpression(exprPath, ignoreResult); + } else { + self.explodeExpression(exprPath, true); + } + }); + return result; - if (!hit) return false - } + case "LogicalExpression": + after = this.loc(); - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* + if (!ignoreResult) { + result = self.makeTempVar(); + } - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } + var left = explodeViaTempVar(result, path.get("left")); - // should be unreachable. - throw new Error('wtf?') -} + if (expr.operator === "&&") { + self.jumpIfNot(left, after); + } else { + _assert["default"].strictEqual(expr.operator, "||"); -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} + self.jumpIf(left, after); + } -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} + explodeViaTempVar(result, path.get("right"), ignoreResult); + self.mark(after); + return result; -},{"brace-expansion":158,"path":522}],520:[function(require,module,exports){ -/** - * Helpers. - */ + case "ConditionalExpression": + var elseLoc = this.loc(); + after = this.loc(); + var test = self.explodeExpression(path.get("test")); + self.jumpIfNot(test, elseLoc); -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + if (!ignoreResult) { + result = self.makeTempVar(); + } -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ + explodeViaTempVar(result, path.get("consequent"), ignoreResult); + self.jump(after); + self.mark(elseLoc); + explodeViaTempVar(result, path.get("alternate"), ignoreResult); + self.mark(after); + return result; -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; + case "UnaryExpression": + return finish(t.unaryExpression(expr.operator, // Can't (and don't need to) break up the syntax of the argument. + // Think about delete a[b]. + self.explodeExpression(path.get("argument")), !!expr.prefix)); -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ + case "BinaryExpression": + return finish(t.binaryExpression(expr.operator, explodeViaTempVar(null, path.get("left")), explodeViaTempVar(null, path.get("right")))); -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} + case "AssignmentExpression": + if (expr.operator === "=") { + // If this is a simple assignment, the left hand side does not need + // to be read before the right hand side is evaluated, so we can + // avoid the more complicated logic below. + return finish(t.assignmentExpression(expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")))); + } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + var lhs = self.explodeExpression(path.get("left")); + var temp = self.emitAssign(self.makeTempVar(), lhs); // For example, + // + // x += yield y + // + // becomes + // + // context.t0 = x + // x = context.t0 += yield y + // + // so that the left-hand side expression is read before the yield. + // Fixes https://github.com/facebook/regenerator/issues/345. -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} + return finish(t.assignmentExpression("=", t.cloneDeep(lhs), t.assignmentExpression(expr.operator, t.cloneDeep(temp), self.explodeExpression(path.get("right"))))); -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + case "UpdateExpression": + return finish(t.updateExpression(expr.operator, self.explodeExpression(path.get("argument")), expr.prefix)); -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} + case "YieldExpression": + after = this.loc(); + var arg = expr.argument && self.explodeExpression(path.get("argument")); -/** - * Pluralization helper. - */ + if (arg && expr.delegate) { + var _result = self.makeTempVar(); -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} + var _ret = t.returnStatement(t.callExpression(self.contextProperty("delegateYield"), [arg, t.stringLiteral(_result.property.name), after])); -},{}],521:[function(require,module,exports){ -'use strict'; -module.exports = Number.isNaN || function (x) { - return x !== x; -}; + _ret.loc = expr.loc; + self.emit(_ret); + self.mark(after); + return _result; + } -},{}],522:[function(require,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + self.emitAssign(self.contextProperty("next"), after); + var ret = t.returnStatement(t.cloneDeep(arg) || null); // Preserve the `yield` location so that source mappings for the statements + // link back to the yield properly. -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } + ret.loc = expr.loc; + self.emit(ret); + self.mark(after); + return self.contextProperty("sent"); - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } + default: + throw new Error("unknown Expression of type " + JSON.stringify(expr.type)); } +}; - return parts; -} +},{"./leap":1059,"./meta":1060,"./util":1062,"assert":278}],1057:[function(require,module,exports){ +"use strict"; -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); -}; +var util = _interopRequireWildcard(require("./util")); -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } } - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; + newObj["default"] = obj; + return newObj; } +} +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); +var hasOwn = Object.prototype.hasOwnProperty; // The hoist function takes a FunctionExpression or FunctionDeclaration +// and replaces any Declaration nodes in its body with assignments, then +// returns a VariableDeclaration containing just the names of the removed +// declarations. - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; +exports.hoist = function (funPath) { + var t = util.getTypes(); + t.assertFunction(funPath.node); + var vars = {}; -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; + function varDeclToExpr(_ref, includeIdentifiers) { + var vdec = _ref.node, + scope = _ref.scope; + t.assertVariableDeclaration(vdec); // TODO assert.equal(vdec.kind, "var"); - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); + var exprs = []; + vdec.declarations.forEach(function (dec) { + // Note: We duplicate 'dec.id' here to ensure that the variable declaration IDs don't + // have the same 'loc' value, since that can make sourcemaps and retainLines behave poorly. + vars[dec.id.name] = t.identifier(dec.id.name); // Remove the binding, to avoid "duplicate declaration" errors when it will + // be injected again. - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; + scope.removeBinding(dec.id.name); + + if (dec.init) { + exprs.push(t.assignmentExpression("=", dec.id, dec.init)); + } else if (includeIdentifiers) { + exprs.push(dec.id); + } + }); + if (exprs.length === 0) return null; + if (exprs.length === 1) return exprs[0]; + return t.sequenceExpression(exprs); } - return (isAbsolute ? '/' : '') + path; -}; + funPath.get("body").traverse({ + VariableDeclaration: { + exit: function exit(path) { + var expr = varDeclToExpr(path, false); -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; + if (expr === null) { + path.remove(); + } else { + // We don't need to traverse this expression any further because + // there can't be any new declarations inside an expression. + util.replaceWithOrRemove(path, t.expressionStatement(expr)); + } // Since the original node has been either removed or replaced, + // avoid traversing it any further. -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); -}; + path.skip(); + } + }, + ForStatement: function ForStatement(path) { + var init = path.get("init"); -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); + if (init.isVariableDeclaration()) { + util.replaceWithOrRemove(init, varDeclToExpr(init, false)); + } + }, + ForXStatement: function ForXStatement(path) { + var left = path.get("left"); - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } + if (left.isVariableDeclaration()) { + util.replaceWithOrRemove(left, varDeclToExpr(left, true)); + } + }, + FunctionDeclaration: function FunctionDeclaration(path) { + var node = path.node; + vars[node.id.name] = node.id; + var assignment = t.expressionStatement(t.assignmentExpression("=", t.clone(node.id), t.functionExpression(path.scope.generateUidIdentifierBasedOnNode(node), node.params, node.body, node.generator, node.expression))); - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } + if (path.parentPath.isBlockStatement()) { + // Insert the assignment form before the first statement in the + // enclosing block. + path.parentPath.unshiftContainer("body", assignment); // Remove the function declaration now that we've inserted the + // equivalent assignment form at the beginning of the block. - if (start > end) return []; - return arr.slice(start, end - start + 1); - } + path.remove(); + } else { + // If the parent node is not a block statement, then we can just + // replace the declaration with the equivalent assignment form + // without worrying about hoisting it. + util.replaceWithOrRemove(path, assignment); + } // Remove the binding, to avoid "duplicate declaration" errors when it will + // be injected again. - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; + path.scope.removeBinding(node.id.name); // Don't hoist variables out of inner functions. + + path.skip(); + }, + FunctionExpression: function FunctionExpression(path) { + // Don't descend into nested function expressions. + path.skip(); + }, + ArrowFunctionExpression: function ArrowFunctionExpression(path) { + // Don't descend into nested function expressions. + path.skip(); } - } + }); + var paramNames = {}; + funPath.get("params").forEach(function (paramPath) { + var param = paramPath.node; - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } + if (t.isIdentifier(param)) { + paramNames[param.name] = param; + } else {// Variables declared by destructuring parameter patterns will be + // harmlessly re-declared. + } + }); + var declarations = []; + Object.keys(vars).forEach(function (name) { + if (!hasOwn.call(paramNames, name)) { + declarations.push(t.variableDeclarator(vars[name], null)); + } + }); - outputParts = outputParts.concat(toParts.slice(samePartsLength)); + if (declarations.length === 0) { + return null; // Be sure to handle this case! + } - return outputParts.join('/'); + return t.variableDeclaration("var", declarations); }; -exports.sep = '/'; -exports.delimiter = ':'; +},{"./util":1062}],1058:[function(require,module,exports){ +"use strict"; -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; +exports.__esModule = true; +exports["default"] = _default; - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } +var _visit = require("./visit"); +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - return root + dir; -}; +function _default(context) { + var plugin = { + visitor: (0, _visit.getVisitor)(context) + }; // Some presets manually call child presets, but fail to pass along the + // context object. Out of an abundance of caution, we verify that it + // exists first to avoid causing unnecessary breaking changes. + var version = context && context.version; // The "name" property is not allowed in older versions of Babel (6.x) + // and will cause the plugin validator to throw an exception. -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); + if (version && parseInt(version, 10) >= 7) { + plugin.name = "regenerator-transform"; } - return f; -}; + return plugin; +} -exports.extname = function(path) { - return splitPath(path)[3]; -}; +},{"./visit":1063}],1059:[function(require,module,exports){ +"use strict"; -function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} +var _assert = _interopRequireDefault(require("assert")); -// String.prototype.substr - negative index don't work in IE8 -var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } -; +var _emit = require("./emit"); -}).call(this,require('_process')) -},{"_process":525}],523:[function(require,module,exports){ -(function (process){ -'use strict'; +var _util = require("util"); -function posix(path) { - return path.charAt(0) === '/'; +var _util2 = require("./util"); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; } +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - // UNC paths are always absolute - return Boolean(result[2] || isUnc); +function Entry() { + _assert["default"].ok(this instanceof Entry); } -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; +function FunctionEntry(returnLoc) { + Entry.call(this); + (0, _util2.getTypes)().assertLiteral(returnLoc); + this.returnLoc = returnLoc; +} -}).call(this,require('_process')) -},{"_process":525}],524:[function(require,module,exports){ -"use strict"; +(0, _util.inherits)(FunctionEntry, Entry); +exports.FunctionEntry = FunctionEntry; -var originalObject = Object; -var originalDefProp = Object.defineProperty; -var originalCreate = Object.create; +function LoopEntry(breakLoc, continueLoc, label) { + Entry.call(this); + var t = (0, _util2.getTypes)(); + t.assertLiteral(breakLoc); + t.assertLiteral(continueLoc); -function defProp(obj, name, value) { - if (originalDefProp) try { - originalDefProp.call(originalObject, obj, name, { value: value }); - } catch (definePropertyIsBrokenInIE8) { - obj[name] = value; + if (label) { + t.assertIdentifier(label); } else { - obj[name] = value; + label = null; } + + this.breakLoc = breakLoc; + this.continueLoc = continueLoc; + this.label = label; } -// For functions that will be invoked using .call or .apply, we need to -// define those methods on the function objects themselves, rather than -// inheriting them from Function.prototype, so that a malicious or clumsy -// third party cannot interfere with the functionality of this module by -// redefining Function.prototype.call or .apply. -function makeSafeToCall(fun) { - if (fun) { - defProp(fun, "call", fun.call); - defProp(fun, "apply", fun.apply); - } - return fun; +(0, _util.inherits)(LoopEntry, Entry); +exports.LoopEntry = LoopEntry; + +function SwitchEntry(breakLoc) { + Entry.call(this); + (0, _util2.getTypes)().assertLiteral(breakLoc); + this.breakLoc = breakLoc; } -makeSafeToCall(originalDefProp); -makeSafeToCall(originalCreate); +(0, _util.inherits)(SwitchEntry, Entry); +exports.SwitchEntry = SwitchEntry; -var hasOwn = makeSafeToCall(Object.prototype.hasOwnProperty); -var numToStr = makeSafeToCall(Number.prototype.toString); -var strSlice = makeSafeToCall(String.prototype.slice); +function TryEntry(firstLoc, catchEntry, finallyEntry) { + Entry.call(this); + var t = (0, _util2.getTypes)(); + t.assertLiteral(firstLoc); -var cloner = function(){}; -function create(prototype) { - if (originalCreate) { - return originalCreate.call(originalObject, prototype); + if (catchEntry) { + _assert["default"].ok(catchEntry instanceof CatchEntry); + } else { + catchEntry = null; } - cloner.prototype = prototype || null; - return new cloner; + + if (finallyEntry) { + _assert["default"].ok(finallyEntry instanceof FinallyEntry); + } else { + finallyEntry = null; + } // Have to have one or the other (or both). + + + _assert["default"].ok(catchEntry || finallyEntry); + + this.firstLoc = firstLoc; + this.catchEntry = catchEntry; + this.finallyEntry = finallyEntry; } -var rand = Math.random; -var uniqueKeys = create(null); +(0, _util.inherits)(TryEntry, Entry); +exports.TryEntry = TryEntry; -function makeUniqueKey() { - // Collisions are highly unlikely, but this module is in the business of - // making guarantees rather than safe bets. - do var uniqueKey = internString(strSlice.call(numToStr.call(rand(), 36), 2)); - while (hasOwn.call(uniqueKeys, uniqueKey)); - return uniqueKeys[uniqueKey] = uniqueKey; +function CatchEntry(firstLoc, paramId) { + Entry.call(this); + var t = (0, _util2.getTypes)(); + t.assertLiteral(firstLoc); + t.assertIdentifier(paramId); + this.firstLoc = firstLoc; + this.paramId = paramId; } -function internString(str) { - var obj = {}; - obj[str] = true; - return Object.keys(obj)[0]; +(0, _util.inherits)(CatchEntry, Entry); +exports.CatchEntry = CatchEntry; + +function FinallyEntry(firstLoc, afterLoc) { + Entry.call(this); + var t = (0, _util2.getTypes)(); + t.assertLiteral(firstLoc); + t.assertLiteral(afterLoc); + this.firstLoc = firstLoc; + this.afterLoc = afterLoc; } -// External users might find this function useful, but it is not necessary -// for the typical use of this module. -exports.makeUniqueKey = makeUniqueKey; +(0, _util.inherits)(FinallyEntry, Entry); +exports.FinallyEntry = FinallyEntry; -// Object.getOwnPropertyNames is the only way to enumerate non-enumerable -// properties, so if we wrap it to ignore our secret keys, there should be -// no way (except guessing) to access those properties. -var originalGetOPNs = Object.getOwnPropertyNames; -Object.getOwnPropertyNames = function getOwnPropertyNames(object) { - for (var names = originalGetOPNs(object), - src = 0, - dst = 0, - len = names.length; - src < len; - ++src) { - if (!hasOwn.call(uniqueKeys, names[src])) { - if (src > dst) { - names[dst] = names[src]; +function LabeledEntry(breakLoc, label) { + Entry.call(this); + var t = (0, _util2.getTypes)(); + t.assertLiteral(breakLoc); + t.assertIdentifier(label); + this.breakLoc = breakLoc; + this.label = label; +} + +(0, _util.inherits)(LabeledEntry, Entry); +exports.LabeledEntry = LabeledEntry; + +function LeapManager(emitter) { + _assert["default"].ok(this instanceof LeapManager); + + _assert["default"].ok(emitter instanceof _emit.Emitter); + + this.emitter = emitter; + this.entryStack = [new FunctionEntry(emitter.finalLoc)]; +} + +var LMp = LeapManager.prototype; +exports.LeapManager = LeapManager; + +LMp.withEntry = function (entry, callback) { + _assert["default"].ok(entry instanceof Entry); + + this.entryStack.push(entry); + + try { + callback.call(this.emitter); + } finally { + var popped = this.entryStack.pop(); + + _assert["default"].strictEqual(popped, entry); + } +}; + +LMp._findLeapLocation = function (property, label) { + for (var i = this.entryStack.length - 1; i >= 0; --i) { + var entry = this.entryStack[i]; + var loc = entry[property]; + + if (loc) { + if (label) { + if (entry.label && entry.label.name === label.name) { + return loc; + } + } else if (entry instanceof LabeledEntry) {// Ignore LabeledEntry entries unless we are actually breaking to + // a label. + } else { + return loc; } - ++dst; } } - names.length = dst; - return names; + + return null; }; -function defaultCreatorFn(object) { - return create(null); +LMp.getBreakLoc = function (label) { + return this._findLeapLocation("breakLoc", label); +}; + +LMp.getContinueLoc = function (label) { + return this._findLeapLocation("continueLoc", label); +}; + +},{"./emit":1056,"./util":1062,"assert":278,"util":1091}],1060:[function(require,module,exports){ +"use strict"; + +var _assert = _interopRequireDefault(require("assert")); + +var _util = require("./util.js"); + +var _private = require("private"); + +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; } +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ -function makeAccessor(secretCreatorFn) { - var brand = makeUniqueKey(); - var passkey = create(null); - secretCreatorFn = secretCreatorFn || defaultCreatorFn; +var m = (0, _private.makeAccessor)(); +var hasOwn = Object.prototype.hasOwnProperty; - function register(object) { - var secret; // Created lazily. +function makePredicate(propertyName, knownTypes) { + function onlyChildren(node) { + var t = (0, _util.getTypes)(); + t.assertNode(node); // Assume no side effects until we find out otherwise. - function vault(key, forget) { - // Only code that has access to the passkey can retrieve (or forget) - // the secret object. - if (key === passkey) { - return forget - ? secret = null - : secret || (secret = secretCreatorFn(object)); + var result = false; + + function check(child) { + if (result) {// Do nothing. + } else if (Array.isArray(child)) { + child.some(check); + } else if (t.isNode(child)) { + _assert["default"].strictEqual(result, false); + + result = predicate(child); } + + return result; } - defProp(object, brand, vault); - } + var keys = t.VISITOR_KEYS[node.type]; - function accessor(object) { - if (!hasOwn.call(object, brand)) - register(object); - return object[brand](passkey); + if (keys) { + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var child = node[key]; + check(child); + } + } + + return result; } - accessor.forget = function(object) { - if (hasOwn.call(object, brand)) - object[brand](passkey, true); - }; + function predicate(node) { + (0, _util.getTypes)().assertNode(node); + var meta = m(node); + if (hasOwn.call(meta, propertyName)) return meta[propertyName]; // Certain types are "opaque," which means they have no side + // effects or leaps and we don't care about their subexpressions. - return accessor; + if (hasOwn.call(opaqueTypes, node.type)) return meta[propertyName] = false; + if (hasOwn.call(knownTypes, node.type)) return meta[propertyName] = true; + return meta[propertyName] = onlyChildren(node); + } + + predicate.onlyChildren = onlyChildren; + return predicate; } -exports.makeAccessor = makeAccessor; +var opaqueTypes = { + FunctionExpression: true, + ArrowFunctionExpression: true +}; // These types potentially have side effects regardless of what side +// effects their subexpressions have. -},{}],525:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; +var sideEffectTypes = { + CallExpression: true, + // Anything could happen! + ForInStatement: true, + // Modifies the key variable. + UnaryExpression: true, + // Think delete. + BinaryExpression: true, + // Might invoke .toString() or .valueOf(). + AssignmentExpression: true, + // Side-effecting by definition. + UpdateExpression: true, + // Updates are essentially assignments. + NewExpression: true // Similar to CallExpression. -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. +}; // These types are the direct cause of all leaps in control flow. -var cachedSetTimeout; -var cachedClearTimeout; +var leapTypes = { + YieldExpression: true, + BreakStatement: true, + ContinueStatement: true, + ReturnStatement: true, + ThrowStatement: true +}; // All leap types are also side effect types. -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); +for (var type in leapTypes) { + if (hasOwn.call(leapTypes, type)) { + sideEffectTypes[type] = leapTypes[type]; + } } -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } +exports.hasSideEffects = makePredicate("hasSideEffects", sideEffectTypes); +exports.containsLeap = makePredicate("containsLeap", leapTypes); +},{"./util.js":1062,"assert":278,"private":1053}],1061:[function(require,module,exports){ +"use strict"; +exports.__esModule = true; +exports["default"] = replaceShorthandObjectMethod; -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; +var util = _interopRequireWildcard(require("./util")); -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } } - queueIndex = -1; - len = queue.length; + } } - currentQueue = null; - draining = false; - runClearTimeout(timeout); + + newObj["default"] = obj; + return newObj; + } } +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +// this function converts a shorthand object generator method into a normal +// (non-shorthand) object property which is a generator function expression. for +// example, this: +// +// var foo = { +// *bar(baz) { return 5; } +// } +// +// should be replaced with: +// +// var foo = { +// bar: function*(baz) { return 5; } +// } +// +// to do this, it clones the parameter array and the body of the object generator +// method into a new FunctionExpression. +// +// this method can be passed any Function AST node path, and it will return +// either: +// a) the path that was passed in (iff the path did not need to be replaced) or +// b) the path of the new FunctionExpression that was created as a replacement +// (iff the path did need to be replaced) +// +// In either case, though, the caller can count on the fact that the return value +// is a Function AST node path. +// +// If this function is called with an AST node path that is not a Function (or with an +// argument that isn't an AST node path), it will throw an error. -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; +function replaceShorthandObjectMethod(path) { + var t = util.getTypes(); -function noop() {} + if (!path.node || !t.isFunction(path.node)) { + throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths."); + } // this function only replaces shorthand object methods (called ObjectMethod + // in Babel-speak). -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; -process.listeners = function (name) { return [] } + if (!t.isObjectMethod(path.node)) { + return path; + } // this function only replaces generators. -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + if (!path.node.generator) { + return path; + } -},{}],526:[function(require,module,exports){ -(function (global){ -/*! https://mths.be/regenerate v1.3.3 by @mathias | MIT license */ -;(function(root) { + var parameters = path.node.params.map(function (param) { + return t.cloneDeep(param); + }); + var functionExpression = t.functionExpression(null, // id + parameters, // params + t.cloneDeep(path.node.body), // body + path.node.generator, path.node.async); + util.replaceWithOrRemove(path, t.objectProperty(t.cloneDeep(path.node.key), // key + functionExpression, //value + path.node.computed, // computed + false // shorthand + )); // path now refers to the ObjectProperty AST node path, but we want to return a + // Function AST node path for the function expression we created. we know that + // the FunctionExpression we just created is the value of the ObjectProperty, + // so return the "value" path off of this path. - // Detect free variables `exports`. - var freeExports = typeof exports == 'object' && exports; + return path.get("value"); +} - // Detect free variable `module`. - var freeModule = typeof module == 'object' && module && - module.exports == freeExports && module; +},{"./util":1062}],1062:[function(require,module,exports){ +"use strict"; - // Detect free variable `global`, from Node.js/io.js or Browserified code, - // and use it as `root`. - var freeGlobal = typeof global == 'object' && global; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - root = freeGlobal; - } +exports.__esModule = true; +exports.wrapWithTypes = wrapWithTypes; +exports.getTypes = getTypes; +exports.runtimeProperty = runtimeProperty; +exports.isReference = isReference; +exports.replaceWithOrRemove = replaceWithOrRemove; +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ - /*--------------------------------------------------------------------------*/ - - var ERRORS = { - 'rangeOrder': 'A range\u2019s `stop` value must be greater than or equal ' + - 'to the `start` value.', - 'codePointRange': 'Invalid code point value. Code points range from ' + - 'U+000000 to U+10FFFF.' - }; - - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-pairs - var HIGH_SURROGATE_MIN = 0xD800; - var HIGH_SURROGATE_MAX = 0xDBFF; - var LOW_SURROGATE_MIN = 0xDC00; - var LOW_SURROGATE_MAX = 0xDFFF; - - // In Regenerate output, `\0` is never preceded by `\` because we sort by - // code point value, so let’s keep this regular expression simple. - var regexNull = /\\x00([^0123456789]|$)/g; - - var object = {}; - var hasOwnProperty = object.hasOwnProperty; - var extend = function(destination, source) { - var key; - for (key in source) { - if (hasOwnProperty.call(source, key)) { - destination[key] = source[key]; - } - } - return destination; - }; - - var forEach = function(array, callback) { - var index = -1; - var length = array.length; - while (++index < length) { - callback(array[index], index); - } - }; - - var toString = object.toString; - var isArray = function(value) { - return toString.call(value) == '[object Array]'; - }; - var isNumber = function(value) { - return typeof value == 'number' || - toString.call(value) == '[object Number]'; - }; - - // This assumes that `number` is a positive integer that `toString()`s nicely - // (which is the case for all code point values). - var zeroes = '0000'; - var pad = function(number, totalCharacters) { - var string = String(number); - return string.length < totalCharacters - ? (zeroes + string).slice(-totalCharacters) - : string; - }; - - var hex = function(number) { - return Number(number).toString(16).toUpperCase(); - }; - - var slice = [].slice; - - /*--------------------------------------------------------------------------*/ - - var dataFromCodePoints = function(codePoints) { - var index = -1; - var length = codePoints.length; - var max = length - 1; - var result = []; - var isStart = true; - var tmp; - var previous = 0; - while (++index < length) { - tmp = codePoints[index]; - if (isStart) { - result.push(tmp); - previous = tmp; - isStart = false; - } else { - if (tmp == previous + 1) { - if (index != max) { - previous = tmp; - continue; - } else { - isStart = true; - result.push(tmp + 1); - } - } else { - // End the previous range and start a new one. - result.push(previous + 1, tmp); - previous = tmp; - } - } - } - if (!isStart) { - result.push(tmp + 1); - } - return result; - }; - - var dataRemove = function(data, codePoint) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1]; - if (codePoint >= start && codePoint < end) { - // Modify this pair. - if (codePoint == start) { - if (end == start + 1) { - // Just remove `start` and `end`. - data.splice(index, 2); - return data; - } else { - // Just replace `start` with a new value. - data[index] = codePoint + 1; - return data; - } - } else if (codePoint == end - 1) { - // Just replace `end` with a new value. - data[index + 1] = codePoint; - return data; - } else { - // Replace `[start, end]` with `[startA, endA, startB, endB]`. - data.splice(index, 2, start, codePoint, codePoint + 1, end); - return data; - } - } - index += 2; - } - return data; - }; - - var dataRemoveRange = function(data, rangeStart, rangeEnd) { - if (rangeEnd < rangeStart) { - throw Error(ERRORS.rangeOrder); - } - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - while (index < data.length) { - start = data[index]; - end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. - - // Exit as soon as no more matching pairs can be found. - if (start > rangeEnd) { - return data; - } - - // Check if this range pair is equal to, or forms a subset of, the range - // to be removed. - // E.g. we have `[0, 11, 40, 51]` and want to remove 0-10 → `[40, 51]`. - // E.g. we have `[40, 51]` and want to remove 0-100 → `[]`. - if (rangeStart <= start && rangeEnd >= end) { - // Remove this pair. - data.splice(index, 2); - continue; - } - - // Check if both `rangeStart` and `rangeEnd` are within the bounds of - // this pair. - // E.g. we have `[0, 11]` and want to remove 4-6 → `[0, 4, 7, 11]`. - if (rangeStart >= start && rangeEnd < end) { - if (rangeStart == start) { - // Replace `[start, end]` with `[startB, endB]`. - data[index] = rangeEnd + 1; - data[index + 1] = end + 1; - return data; - } - // Replace `[start, end]` with `[startA, endA, startB, endB]`. - data.splice(index, 2, start, rangeStart, rangeEnd + 1, end + 1); - return data; - } - - // Check if only `rangeStart` is within the bounds of this pair. - // E.g. we have `[0, 11]` and want to remove 4-20 → `[0, 4]`. - if (rangeStart >= start && rangeStart <= end) { - // Replace `end` with `rangeStart`. - data[index + 1] = rangeStart; - // Note: we cannot `return` just yet, in case any following pairs still - // contain matching code points. - // E.g. we have `[0, 11, 14, 31]` and want to remove 4-20 - // → `[0, 4, 21, 31]`. - } - - // Check if only `rangeEnd` is within the bounds of this pair. - // E.g. we have `[14, 31]` and want to remove 4-20 → `[21, 31]`. - else if (rangeEnd >= start && rangeEnd <= end) { - // Just replace `start`. - data[index] = rangeEnd + 1; - return data; - } - - index += 2; - } - return data; - }; - - var dataAdd = function(data, codePoint) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var lastIndex = null; - var length = data.length; - if (codePoint < 0x0 || codePoint > 0x10FFFF) { - throw RangeError(ERRORS.codePointRange); - } - while (index < length) { - start = data[index]; - end = data[index + 1]; - - // Check if the code point is already in the set. - if (codePoint >= start && codePoint < end) { - return data; - } - - if (codePoint == start - 1) { - // Just replace `start` with a new value. - data[index] = codePoint; - return data; - } - - // At this point, if `start` is `greater` than `codePoint`, insert a new - // `[start, end]` pair before the current pair, or after the current pair - // if there is a known `lastIndex`. - if (start > codePoint) { - data.splice( - lastIndex != null ? lastIndex + 2 : 0, - 0, - codePoint, - codePoint + 1 - ); - return data; - } - - if (codePoint == end) { - // Check if adding this code point causes two separate ranges to become - // a single range, e.g. `dataAdd([0, 4, 5, 10], 4)` → `[0, 10]`. - if (codePoint + 1 == data[index + 2]) { - data.splice(index, 4, start, data[index + 3]); - return data; - } - // Else, just replace `end` with a new value. - data[index + 1] = codePoint + 1; - return data; - } - lastIndex = index; - index += 2; - } - // The loop has finished; add the new pair to the end of the data set. - data.push(codePoint, codePoint + 1); - return data; - }; - - var dataAddData = function(dataA, dataB) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var data = dataA.slice(); - var length = dataB.length; - while (index < length) { - start = dataB[index]; - end = dataB[index + 1] - 1; - if (start == end) { - data = dataAdd(data, start); - } else { - data = dataAddRange(data, start, end); - } - index += 2; - } - return data; - }; - - var dataRemoveData = function(dataA, dataB) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var data = dataA.slice(); - var length = dataB.length; - while (index < length) { - start = dataB[index]; - end = dataB[index + 1] - 1; - if (start == end) { - data = dataRemove(data, start); - } else { - data = dataRemoveRange(data, start, end); - } - index += 2; - } - return data; - }; - - var dataAddRange = function(data, rangeStart, rangeEnd) { - if (rangeEnd < rangeStart) { - throw Error(ERRORS.rangeOrder); - } - if ( - rangeStart < 0x0 || rangeStart > 0x10FFFF || - rangeEnd < 0x0 || rangeEnd > 0x10FFFF - ) { - throw RangeError(ERRORS.codePointRange); - } - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var added = false; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1]; - - if (added) { - // The range has already been added to the set; at this point, we just - // need to get rid of the following ranges in case they overlap. - - // Check if this range can be combined with the previous range. - if (start == rangeEnd + 1) { - data.splice(index - 1, 2); - return data; - } - - // Exit as soon as no more possibly overlapping pairs can be found. - if (start > rangeEnd) { - return data; - } - - // E.g. `[0, 11, 12, 16]` and we’ve added 5-15, so we now have - // `[0, 16, 12, 16]`. Remove the `12,16` part, as it lies within the - // `0,16` range that was previously added. - if (start >= rangeStart && start <= rangeEnd) { - // `start` lies within the range that was previously added. - - if (end > rangeStart && end - 1 <= rangeEnd) { - // `end` lies within the range that was previously added as well, - // so remove this pair. - data.splice(index, 2); - index -= 2; - // Note: we cannot `return` just yet, as there may still be other - // overlapping pairs. - } else { - // `start` lies within the range that was previously added, but - // `end` doesn’t. E.g. `[0, 11, 12, 31]` and we’ve added 5-15, so - // now we have `[0, 16, 12, 31]`. This must be written as `[0, 31]`. - // Remove the previously added `end` and the current `start`. - data.splice(index - 1, 2); - index -= 2; - } - - // Note: we cannot return yet. - } - - } - - else if (start == rangeEnd + 1) { - data[index] = rangeStart; - return data; - } - - // Check if a new pair must be inserted *before* the current one. - else if (start > rangeEnd) { - data.splice(index, 0, rangeStart, rangeEnd + 1); - return data; - } - - else if (rangeStart >= start && rangeStart < end && rangeEnd + 1 <= end) { - // The new range lies entirely within an existing range pair. No action - // needed. - return data; - } - - else if ( - // E.g. `[0, 11]` and you add 5-15 → `[0, 16]`. - (rangeStart >= start && rangeStart < end) || - // E.g. `[0, 3]` and you add 3-6 → `[0, 7]`. - end == rangeStart - ) { - // Replace `end` with the new value. - data[index + 1] = rangeEnd + 1; - // Make sure the next range pair doesn’t overlap, e.g. `[0, 11, 12, 14]` - // and you add 5-15 → `[0, 16]`, i.e. remove the `12,14` part. - added = true; - // Note: we cannot `return` just yet. - } - - else if (rangeStart <= start && rangeEnd + 1 >= end) { - // The new range is a superset of the old range. - data[index] = rangeStart; - data[index + 1] = rangeEnd + 1; - added = true; - } - - index += 2; - } - // The loop has finished without doing anything; add the new pair to the end - // of the data set. - if (!added) { - data.push(rangeStart, rangeEnd + 1); - } - return data; - }; - - var dataContains = function(data, codePoint) { - var index = 0; - var length = data.length; - // Exit early if `codePoint` is not within `data`’s overall range. - var start = data[index]; - var end = data[length - 1]; - if (length >= 2) { - if (codePoint < start || codePoint > end) { - return false; - } - } - // Iterate over the data per `(start, end)` pair. - while (index < length) { - start = data[index]; - end = data[index + 1]; - if (codePoint >= start && codePoint < end) { - return true; - } - index += 2; - } - return false; - }; - - var dataIntersection = function(data, codePoints) { - var index = 0; - var length = codePoints.length; - var codePoint; - var result = []; - while (index < length) { - codePoint = codePoints[index]; - if (dataContains(data, codePoint)) { - result.push(codePoint); - } - ++index; - } - return dataFromCodePoints(result); - }; - - var dataIsEmpty = function(data) { - return !data.length; - }; - - var dataIsSingleton = function(data) { - // Check if the set only represents a single code point. - return data.length == 2 && data[0] + 1 == data[1]; - }; - - var dataToArray = function(data) { - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var result = []; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1]; - while (start < end) { - result.push(start); - ++start; - } - index += 2; - } - return result; - }; - - /*--------------------------------------------------------------------------*/ - - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - var floor = Math.floor; - var highSurrogate = function(codePoint) { - return parseInt( - floor((codePoint - 0x10000) / 0x400) + HIGH_SURROGATE_MIN, - 10 - ); - }; - - var lowSurrogate = function(codePoint) { - return parseInt( - (codePoint - 0x10000) % 0x400 + LOW_SURROGATE_MIN, - 10 - ); - }; - - var stringFromCharCode = String.fromCharCode; - var codePointToString = function(codePoint) { - var string; - // https://mathiasbynens.be/notes/javascript-escapes#single - // Note: the `\b` escape sequence for U+0008 BACKSPACE in strings has a - // different meaning in regular expressions (word boundary), so it cannot - // be used here. - if (codePoint == 0x09) { - string = '\\t'; - } - // Note: IE < 9 treats `'\v'` as `'v'`, so avoid using it. - // else if (codePoint == 0x0B) { - // string = '\\v'; - // } - else if (codePoint == 0x0A) { - string = '\\n'; - } - else if (codePoint == 0x0C) { - string = '\\f'; - } - else if (codePoint == 0x0D) { - string = '\\r'; - } - else if (codePoint == 0x5C) { - string = '\\\\'; - } - else if ( - codePoint == 0x24 || - (codePoint >= 0x28 && codePoint <= 0x2B) || - (codePoint >= 0x2D && codePoint <= 0x2F) || - codePoint == 0x3F || - (codePoint >= 0x5B && codePoint <= 0x5E) || - (codePoint >= 0x7B && codePoint <= 0x7D) - ) { - // The code point maps to an unsafe printable ASCII character; - // backslash-escape it. Here’s the list of those symbols: - // - // $()*+-./?[\]^{|} - // - // See #7 for more info. - string = '\\' + stringFromCharCode(codePoint); - } - else if (codePoint >= 0x20 && codePoint <= 0x7E) { - // The code point maps to one of these printable ASCII symbols - // (including the space character): - // - // !"#%&',/0123456789:;<=>@ABCDEFGHIJKLMNO - // PQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz~ - // - // These can safely be used directly. - string = stringFromCharCode(codePoint); - } - else if (codePoint <= 0xFF) { - // https://mathiasbynens.be/notes/javascript-escapes#hexadecimal - string = '\\x' + pad(hex(codePoint), 2); - } - else { // `codePoint <= 0xFFFF` holds true. - // https://mathiasbynens.be/notes/javascript-escapes#unicode - string = '\\u' + pad(hex(codePoint), 4); - } - - // There’s no need to account for astral symbols / surrogate pairs here, - // since `codePointToString` is private and only used for BMP code points. - // But if that’s what you need, just add an `else` block with this code: - // - // string = '\\u' + pad(hex(highSurrogate(codePoint)), 4) - // + '\\u' + pad(hex(lowSurrogate(codePoint)), 4); - - return string; - }; - - var codePointToStringUnicode = function(codePoint) { - if (codePoint <= 0xFFFF) { - return codePointToString(codePoint); - } - return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; - }; - - var symbolToCodePoint = function(symbol) { - var length = symbol.length; - var first = symbol.charCodeAt(0); - var second; - if ( - first >= HIGH_SURROGATE_MIN && first <= HIGH_SURROGATE_MAX && - length > 1 // There is a next code unit. - ) { - // `first` is a high surrogate, and there is a next character. Assume - // it’s a low surrogate (else it’s invalid usage of Regenerate anyway). - second = symbol.charCodeAt(1); - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - HIGH_SURROGATE_MIN) * 0x400 + - second - LOW_SURROGATE_MIN + 0x10000; - } - return first; - }; - - var createBMPCharacterClasses = function(data) { - // Iterate over the data per `(start, end)` pair. - var result = ''; - var index = 0; - var start; - var end; - var length = data.length; - if (dataIsSingleton(data)) { - return codePointToString(data[0]); - } - while (index < length) { - start = data[index]; - end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. - if (start == end) { - result += codePointToString(start); - } else if (start + 1 == end) { - result += codePointToString(start) + codePointToString(end); - } else { - result += codePointToString(start) + '-' + codePointToString(end); - } - index += 2; - } - return '[' + result + ']'; - }; - - var createUnicodeCharacterClasses = function(data) { - // Iterate over the data per `(start, end)` pair. - var result = ''; - var index = 0; - var start; - var end; - var length = data.length; - if (dataIsSingleton(data)) { - return codePointToStringUnicode(data[0]); - } - while (index < length) { - start = data[index]; - end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. - if (start == end) { - result += codePointToStringUnicode(start); - } else if (start + 1 == end) { - result += codePointToStringUnicode(start) + codePointToStringUnicode(end); - } else { - result += codePointToStringUnicode(start) + '-' + codePointToStringUnicode(end); - } - index += 2; - } - return '[' + result + ']'; - }; - - var splitAtBMP = function(data) { - // Iterate over the data per `(start, end)` pair. - var loneHighSurrogates = []; - var loneLowSurrogates = []; - var bmp = []; - var astral = []; - var index = 0; - var start; - var end; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. - - if (start < HIGH_SURROGATE_MIN) { - - // The range starts and ends before the high surrogate range. - // E.g. (0, 0x10). - if (end < HIGH_SURROGATE_MIN) { - bmp.push(start, end + 1); - } - - // The range starts before the high surrogate range and ends within it. - // E.g. (0, 0xD855). - if (end >= HIGH_SURROGATE_MIN && end <= HIGH_SURROGATE_MAX) { - bmp.push(start, HIGH_SURROGATE_MIN); - loneHighSurrogates.push(HIGH_SURROGATE_MIN, end + 1); - } - - // The range starts before the high surrogate range and ends in the low - // surrogate range. E.g. (0, 0xDCFF). - if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { - bmp.push(start, HIGH_SURROGATE_MIN); - loneHighSurrogates.push(HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX + 1); - loneLowSurrogates.push(LOW_SURROGATE_MIN, end + 1); - } - - // The range starts before the high surrogate range and ends after the - // low surrogate range. E.g. (0, 0x10FFFF). - if (end > LOW_SURROGATE_MAX) { - bmp.push(start, HIGH_SURROGATE_MIN); - loneHighSurrogates.push(HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX + 1); - loneLowSurrogates.push(LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1); - if (end <= 0xFFFF) { - bmp.push(LOW_SURROGATE_MAX + 1, end + 1); - } else { - bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); - astral.push(0xFFFF + 1, end + 1); - } - } - - } else if (start >= HIGH_SURROGATE_MIN && start <= HIGH_SURROGATE_MAX) { - - // The range starts and ends in the high surrogate range. - // E.g. (0xD855, 0xD866). - if (end >= HIGH_SURROGATE_MIN && end <= HIGH_SURROGATE_MAX) { - loneHighSurrogates.push(start, end + 1); - } - - // The range starts in the high surrogate range and ends in the low - // surrogate range. E.g. (0xD855, 0xDCFF). - if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { - loneHighSurrogates.push(start, HIGH_SURROGATE_MAX + 1); - loneLowSurrogates.push(LOW_SURROGATE_MIN, end + 1); - } - - // The range starts in the high surrogate range and ends after the low - // surrogate range. E.g. (0xD855, 0x10FFFF). - if (end > LOW_SURROGATE_MAX) { - loneHighSurrogates.push(start, HIGH_SURROGATE_MAX + 1); - loneLowSurrogates.push(LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1); - if (end <= 0xFFFF) { - bmp.push(LOW_SURROGATE_MAX + 1, end + 1); - } else { - bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); - astral.push(0xFFFF + 1, end + 1); - } - } - - } else if (start >= LOW_SURROGATE_MIN && start <= LOW_SURROGATE_MAX) { - - // The range starts and ends in the low surrogate range. - // E.g. (0xDCFF, 0xDDFF). - if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { - loneLowSurrogates.push(start, end + 1); - } - - // The range starts in the low surrogate range and ends after the low - // surrogate range. E.g. (0xDCFF, 0x10FFFF). - if (end > LOW_SURROGATE_MAX) { - loneLowSurrogates.push(start, LOW_SURROGATE_MAX + 1); - if (end <= 0xFFFF) { - bmp.push(LOW_SURROGATE_MAX + 1, end + 1); - } else { - bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); - astral.push(0xFFFF + 1, end + 1); - } - } - - } else if (start > LOW_SURROGATE_MAX && start <= 0xFFFF) { - - // The range starts and ends after the low surrogate range. - // E.g. (0xFFAA, 0x10FFFF). - if (end <= 0xFFFF) { - bmp.push(start, end + 1); - } else { - bmp.push(start, 0xFFFF + 1); - astral.push(0xFFFF + 1, end + 1); - } - - } else { - - // The range starts and ends in the astral range. - astral.push(start, end + 1); - - } - - index += 2; - } - return { - 'loneHighSurrogates': loneHighSurrogates, - 'loneLowSurrogates': loneLowSurrogates, - 'bmp': bmp, - 'astral': astral - }; - }; - - var optimizeSurrogateMappings = function(surrogateMappings) { - var result = []; - var tmpLow = []; - var addLow = false; - var mapping; - var nextMapping; - var highSurrogates; - var lowSurrogates; - var nextHighSurrogates; - var nextLowSurrogates; - var index = -1; - var length = surrogateMappings.length; - while (++index < length) { - mapping = surrogateMappings[index]; - nextMapping = surrogateMappings[index + 1]; - if (!nextMapping) { - result.push(mapping); - continue; - } - highSurrogates = mapping[0]; - lowSurrogates = mapping[1]; - nextHighSurrogates = nextMapping[0]; - nextLowSurrogates = nextMapping[1]; - - // Check for identical high surrogate ranges. - tmpLow = lowSurrogates; - while ( - nextHighSurrogates && - highSurrogates[0] == nextHighSurrogates[0] && - highSurrogates[1] == nextHighSurrogates[1] - ) { - // Merge with the next item. - if (dataIsSingleton(nextLowSurrogates)) { - tmpLow = dataAdd(tmpLow, nextLowSurrogates[0]); - } else { - tmpLow = dataAddRange( - tmpLow, - nextLowSurrogates[0], - nextLowSurrogates[1] - 1 - ); - } - ++index; - mapping = surrogateMappings[index]; - highSurrogates = mapping[0]; - lowSurrogates = mapping[1]; - nextMapping = surrogateMappings[index + 1]; - nextHighSurrogates = nextMapping && nextMapping[0]; - nextLowSurrogates = nextMapping && nextMapping[1]; - addLow = true; - } - result.push([ - highSurrogates, - addLow ? tmpLow : lowSurrogates - ]); - addLow = false; - } - return optimizeByLowSurrogates(result); - }; - - var optimizeByLowSurrogates = function(surrogateMappings) { - if (surrogateMappings.length == 1) { - return surrogateMappings; - } - var index = -1; - var innerIndex = -1; - while (++index < surrogateMappings.length) { - var mapping = surrogateMappings[index]; - var lowSurrogates = mapping[1]; - var lowSurrogateStart = lowSurrogates[0]; - var lowSurrogateEnd = lowSurrogates[1]; - innerIndex = index; // Note: the loop starts at the next index. - while (++innerIndex < surrogateMappings.length) { - var otherMapping = surrogateMappings[innerIndex]; - var otherLowSurrogates = otherMapping[1]; - var otherLowSurrogateStart = otherLowSurrogates[0]; - var otherLowSurrogateEnd = otherLowSurrogates[1]; - if ( - lowSurrogateStart == otherLowSurrogateStart && - lowSurrogateEnd == otherLowSurrogateEnd - ) { - // Add the code points in the other item to this one. - if (dataIsSingleton(otherMapping[0])) { - mapping[0] = dataAdd(mapping[0], otherMapping[0][0]); - } else { - mapping[0] = dataAddRange( - mapping[0], - otherMapping[0][0], - otherMapping[0][1] - 1 - ); - } - // Remove the other, now redundant, item. - surrogateMappings.splice(innerIndex, 1); - --innerIndex; - } - } - } - return surrogateMappings; - }; - - var surrogateSet = function(data) { - // Exit early if `data` is an empty set. - if (!data.length) { - return []; - } - - // Iterate over the data per `(start, end)` pair. - var index = 0; - var start; - var end; - var startHigh; - var startLow; - var endHigh; - var endLow; - var surrogateMappings = []; - var length = data.length; - while (index < length) { - start = data[index]; - end = data[index + 1] - 1; - - startHigh = highSurrogate(start); - startLow = lowSurrogate(start); - endHigh = highSurrogate(end); - endLow = lowSurrogate(end); - - var startsWithLowestLowSurrogate = startLow == LOW_SURROGATE_MIN; - var endsWithHighestLowSurrogate = endLow == LOW_SURROGATE_MAX; - var complete = false; - - // Append the previous high-surrogate-to-low-surrogate mappings. - // Step 1: `(startHigh, startLow)` to `(startHigh, LOW_SURROGATE_MAX)`. - if ( - startHigh == endHigh || - startsWithLowestLowSurrogate && endsWithHighestLowSurrogate - ) { - surrogateMappings.push([ - [startHigh, endHigh + 1], - [startLow, endLow + 1] - ]); - complete = true; - } else { - surrogateMappings.push([ - [startHigh, startHigh + 1], - [startLow, LOW_SURROGATE_MAX + 1] - ]); - } - - // Step 2: `(startHigh + 1, LOW_SURROGATE_MIN)` to - // `(endHigh - 1, LOW_SURROGATE_MAX)`. - if (!complete && startHigh + 1 < endHigh) { - if (endsWithHighestLowSurrogate) { - // Combine step 2 and step 3. - surrogateMappings.push([ - [startHigh + 1, endHigh + 1], - [LOW_SURROGATE_MIN, endLow + 1] - ]); - complete = true; - } else { - surrogateMappings.push([ - [startHigh + 1, endHigh], - [LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1] - ]); - } - } - - // Step 3. `(endHigh, LOW_SURROGATE_MIN)` to `(endHigh, endLow)`. - if (!complete) { - surrogateMappings.push([ - [endHigh, endHigh + 1], - [LOW_SURROGATE_MIN, endLow + 1] - ]); - } - - index += 2; - } - - // The format of `surrogateMappings` is as follows: - // - // [ surrogateMapping1, surrogateMapping2 ] - // - // i.e.: - // - // [ - // [ highSurrogates1, lowSurrogates1 ], - // [ highSurrogates2, lowSurrogates2 ] - // ] - return optimizeSurrogateMappings(surrogateMappings); - }; - - var createSurrogateCharacterClasses = function(surrogateMappings) { - var result = []; - forEach(surrogateMappings, function(surrogateMapping) { - var highSurrogates = surrogateMapping[0]; - var lowSurrogates = surrogateMapping[1]; - result.push( - createBMPCharacterClasses(highSurrogates) + - createBMPCharacterClasses(lowSurrogates) - ); - }); - return result.join('|'); - }; - - var createCharacterClassesFromData = function(data, bmpOnly, hasUnicodeFlag) { - if (hasUnicodeFlag) { - return createUnicodeCharacterClasses(data); - } - var result = []; - - var parts = splitAtBMP(data); - var loneHighSurrogates = parts.loneHighSurrogates; - var loneLowSurrogates = parts.loneLowSurrogates; - var bmp = parts.bmp; - var astral = parts.astral; - var hasLoneHighSurrogates = !dataIsEmpty(loneHighSurrogates); - var hasLoneLowSurrogates = !dataIsEmpty(loneLowSurrogates); - - var surrogateMappings = surrogateSet(astral); - - if (bmpOnly) { - bmp = dataAddData(bmp, loneHighSurrogates); - hasLoneHighSurrogates = false; - bmp = dataAddData(bmp, loneLowSurrogates); - hasLoneLowSurrogates = false; - } - - if (!dataIsEmpty(bmp)) { - // The data set contains BMP code points that are not high surrogates - // needed for astral code points in the set. - result.push(createBMPCharacterClasses(bmp)); - } - if (surrogateMappings.length) { - // The data set contains astral code points; append character classes - // based on their surrogate pairs. - result.push(createSurrogateCharacterClasses(surrogateMappings)); - } - // https://gist.github.com/mathiasbynens/bbe7f870208abcfec860 - if (hasLoneHighSurrogates) { - result.push( - createBMPCharacterClasses(loneHighSurrogates) + - // Make sure the high surrogates aren’t part of a surrogate pair. - '(?![\\uDC00-\\uDFFF])' - ); - } - if (hasLoneLowSurrogates) { - result.push( - // It is not possible to accurately assert the low surrogates aren’t - // part of a surrogate pair, since JavaScript regular expressions do - // not support lookbehind. - '(?:[^\\uD800-\\uDBFF]|^)' + - createBMPCharacterClasses(loneLowSurrogates) - ); - } - return result.join('|'); - }; - - /*--------------------------------------------------------------------------*/ - - // `regenerate` can be used as a constructor (and new methods can be added to - // its prototype) but also as a regular function, the latter of which is the - // documented and most common usage. For that reason, it’s not capitalized. - var regenerate = function(value) { - if (arguments.length > 1) { - value = slice.call(arguments); - } - if (this instanceof regenerate) { - this.data = []; - return value ? this.add(value) : this; - } - return (new regenerate).add(value); - }; - - regenerate.version = '1.3.3'; - - var proto = regenerate.prototype; - extend(proto, { - 'add': function(value) { - var $this = this; - if (value == null) { - return $this; - } - if (value instanceof regenerate) { - // Allow passing other Regenerate instances. - $this.data = dataAddData($this.data, value.data); - return $this; - } - if (arguments.length > 1) { - value = slice.call(arguments); - } - if (isArray(value)) { - forEach(value, function(item) { - $this.add(item); - }); - return $this; - } - $this.data = dataAdd( - $this.data, - isNumber(value) ? value : symbolToCodePoint(value) - ); - return $this; - }, - 'remove': function(value) { - var $this = this; - if (value == null) { - return $this; - } - if (value instanceof regenerate) { - // Allow passing other Regenerate instances. - $this.data = dataRemoveData($this.data, value.data); - return $this; - } - if (arguments.length > 1) { - value = slice.call(arguments); - } - if (isArray(value)) { - forEach(value, function(item) { - $this.remove(item); - }); - return $this; - } - $this.data = dataRemove( - $this.data, - isNumber(value) ? value : symbolToCodePoint(value) - ); - return $this; - }, - 'addRange': function(start, end) { - var $this = this; - $this.data = dataAddRange($this.data, - isNumber(start) ? start : symbolToCodePoint(start), - isNumber(end) ? end : symbolToCodePoint(end) - ); - return $this; - }, - 'removeRange': function(start, end) { - var $this = this; - var startCodePoint = isNumber(start) ? start : symbolToCodePoint(start); - var endCodePoint = isNumber(end) ? end : symbolToCodePoint(end); - $this.data = dataRemoveRange( - $this.data, - startCodePoint, - endCodePoint - ); - return $this; - }, - 'intersection': function(argument) { - var $this = this; - // Allow passing other Regenerate instances. - // TODO: Optimize this by writing and using `dataIntersectionData()`. - var array = argument instanceof regenerate ? - dataToArray(argument.data) : - argument; - $this.data = dataIntersection($this.data, array); - return $this; - }, - 'contains': function(codePoint) { - return dataContains( - this.data, - isNumber(codePoint) ? codePoint : symbolToCodePoint(codePoint) - ); - }, - 'clone': function() { - var set = new regenerate; - set.data = this.data.slice(0); - return set; - }, - 'toString': function(options) { - var result = createCharacterClassesFromData( - this.data, - options ? options.bmpOnly : false, - options ? options.hasUnicodeFlag : false - ); - if (!result) { - // For an empty set, return something that can be inserted `/here/` to - // form a valid regular expression. Avoid `(?:)` since that matches the - // empty string. - return '[]'; - } - // Use `\0` instead of `\x00` where possible. - return result.replace(regexNull, '\\0$1'); - }, - 'toRegExp': function(flags) { - var pattern = this.toString( - flags && flags.indexOf('u') != -1 ? - { 'hasUnicodeFlag': true } : - null - ); - return RegExp(pattern, flags || ''); - }, - 'valueOf': function() { // Note: `valueOf` is aliased as `toArray`. - return dataToArray(this.data); - } - }); - - proto.toArray = proto.valueOf; - - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define(function() { - return regenerate; - }); - } else if (freeExports && !freeExports.nodeType) { - if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+ - freeModule.exports = regenerate; - } else { // in Narwhal or RingoJS v0.7.0- - freeExports.regenerate = regenerate; - } - } else { // in Rhino or a web browser - root.regenerate = regenerate; - } +var currentTypes = null; -}(this)); +function wrapWithTypes(types, fn) { + return function () { + var oldTypes = currentTypes; + currentTypes = types; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],527:[function(require,module,exports){ -"use strict"; + try { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } -var _stringify = require("babel-runtime/core-js/json/stringify"); + return fn.apply(this, args); + } finally { + currentTypes = oldTypes; + } + }; +} -var _stringify2 = _interopRequireDefault(_stringify); +function getTypes() { + return currentTypes; +} -var _assert = require("assert"); +function runtimeProperty(name) { + var t = getTypes(); + return t.memberExpression(t.identifier("regeneratorRuntime"), t.identifier(name), false); +} -var _assert2 = _interopRequireDefault(_assert); +function isReference(path) { + return path.isReferenced() || path.parentPath.isAssignmentExpression({ + left: path.node + }); +} -var _babelTypes = require("babel-types"); +function replaceWithOrRemove(path, replacement) { + if (replacement) { + path.replaceWith(replacement); + } else { + path.remove(); + } +} -var t = _interopRequireWildcard(_babelTypes); +},{}],1063:[function(require,module,exports){ +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +"use strict"; -var _leap = require("./leap"); +var _assert = _interopRequireDefault(require("assert")); -var leap = _interopRequireWildcard(_leap); +var _hoist = require("./hoist"); -var _meta = require("./meta"); +var _emit = require("./emit"); -var meta = _interopRequireWildcard(_meta); +var _replaceShorthandObjectMethod = _interopRequireDefault(require("./replaceShorthandObjectMethod")); -var _util = require("./util"); +var util = _interopRequireWildcard(require("./util")); -var util = _interopRequireWildcard(_util); +var _private = require("private"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; -var hasOwn = Object.prototype.hasOwnProperty; /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } -function Emitter(contextId) { - _assert2.default.ok(this instanceof Emitter); - t.assertIdentifier(contextId); + newObj["default"] = obj; + return newObj; + } +} - // Used to generate unique temporary names. - this.nextTempId = 0; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} - // In order to make sure the context object does not collide with - // anything in the local scope, we might have to rename it, so we - // refer to it symbolically instead of just assuming that it will be - // called "context". - this.contextId = contextId; +exports.getVisitor = function (_ref) { + var t = _ref.types; + return { + Method: function Method(path, state) { + var node = path.node; + if (!shouldRegenerate(node, state)) return; + var container = t.functionExpression(null, [], t.cloneNode(node.body, false), node.generator, node.async); + path.get("body").set("body", [t.returnStatement(t.callExpression(container, []))]); // Regardless of whether or not the wrapped function is a an async method + // or generator the outer function should not be - // An append-only list of Statements that grows each time this.emit is - // called. - this.listing = []; + node.async = false; + node.generator = false; // Unwrap the wrapper IIFE's environment so super and this and such still work. + + path.get("body.body.0.argument.callee").unwrapFunctionEnvironment(); + }, + Function: { + exit: util.wrapWithTypes(t, function (path, state) { + var node = path.node; + if (!shouldRegenerate(node, state)) return; // if this is an ObjectMethod, we need to convert it to an ObjectProperty + + path = (0, _replaceShorthandObjectMethod["default"])(path); + node = path.node; + var contextId = path.scope.generateUidIdentifier("context"); + var argsId = path.scope.generateUidIdentifier("args"); + path.ensureBlock(); + var bodyBlockPath = path.get("body"); + + if (node.async) { + bodyBlockPath.traverse(awaitVisitor); + } + + bodyBlockPath.traverse(functionSentVisitor, { + context: contextId + }); + var outerBody = []; + var innerBody = []; + bodyBlockPath.get("body").forEach(function (childPath) { + var node = childPath.node; + + if (t.isExpressionStatement(node) && t.isStringLiteral(node.expression)) { + // Babylon represents directives like "use strict" as elements + // of a bodyBlockPath.node.directives array, but they could just + // as easily be represented (by other parsers) as traditional + // string-literal-valued expression statements, so we need to + // handle that here. (#248) + outerBody.push(node); + } else if (node && node._blockHoist != null) { + outerBody.push(node); + } else { + innerBody.push(node); + } + }); - // A sparse array whose keys correspond to locations in this.listing - // that have been marked as branch/jump targets. - this.marked = [true]; + if (outerBody.length > 0) { + // Only replace the inner body if we actually hoisted any statements + // to the outer body. + bodyBlockPath.node.body = innerBody; + } - // The last location will be marked when this.getDispatchLoop is - // called. - this.finalLoc = loc(); + var outerFnExpr = getOuterFnExpr(path); // Note that getOuterFnExpr has the side-effect of ensuring that the + // function has a name (so node.id will always be an Identifier), even + // if a temporary name has to be synthesized. - // A list of all leap.TryEntry statements emitted. - this.tryEntries = []; + t.assertIdentifier(node.id); + var innerFnId = t.identifier(node.id.name + "$"); // Turn all declarations into vars, and replace the original + // declarations with equivalent assignment expressions. - // Each time we evaluate the body of a loop, we tell this.leapManager - // to enter a nested loop context that determines the meaning of break - // and continue statements therein. - this.leapManager = new leap.LeapManager(this); -} + var vars = (0, _hoist.hoist)(path); + var context = { + usesThis: false, + usesArguments: false, + getArgsId: function getArgsId() { + return t.clone(argsId); + } + }; + path.traverse(argumentsThisVisitor, context); -var Ep = Emitter.prototype; -exports.Emitter = Emitter; + if (context.usesArguments) { + vars = vars || t.variableDeclaration("var", []); + var argumentIdentifier = t.identifier("arguments"); // we need to do this as otherwise arguments in arrow functions gets hoisted -// Offsets into this.listing that could be used as targets for branches or -// jumps are represented as numeric Literal nodes. This representation has -// the amazingly convenient benefit of allowing the exact value of the -// location to be determined at any time, even after generating code that -// refers to the location. -function loc() { - return t.numericLiteral(-1); -} + argumentIdentifier._shadowedFunctionLiteral = path; + vars.declarations.push(t.variableDeclarator(t.clone(argsId), argumentIdentifier)); + } -// Sets the exact value of the given location to the offset of the next -// Statement emitted. -Ep.mark = function (loc) { - t.assertLiteral(loc); - var index = this.listing.length; - if (loc.value === -1) { - loc.value = index; - } else { - // Locations can be marked redundantly, but their values cannot change - // once set the first time. - _assert2.default.strictEqual(loc.value, index); - } - this.marked[index] = true; - return loc; -}; + var emitter = new _emit.Emitter(contextId); + emitter.explode(path.get("body")); -Ep.emit = function (node) { - if (t.isExpression(node)) { - node = t.expressionStatement(node); - } + if (vars && vars.declarations.length > 0) { + outerBody.push(vars); + } - t.assertStatement(node); - this.listing.push(node); -}; + var wrapArgs = [emitter.getContextFunction(innerFnId)]; + var tryLocsList = emitter.getTryLocsList(); -// Shorthand for emitting assignment statements. This will come in handy -// for assignments to temporary variables. -Ep.emitAssign = function (lhs, rhs) { - this.emit(this.assign(lhs, rhs)); - return lhs; -}; + if (node.generator) { + wrapArgs.push(outerFnExpr); + } else if (context.usesThis || tryLocsList) { + // Async functions that are not generators don't care about the + // outer function because they don't need it to be marked and don't + // inherit from its .prototype. + wrapArgs.push(t.nullLiteral()); + } -// Shorthand for an assignment statement. -Ep.assign = function (lhs, rhs) { - return t.expressionStatement(t.assignmentExpression("=", lhs, rhs)); -}; + if (context.usesThis) { + wrapArgs.push(t.thisExpression()); + } else if (tryLocsList) { + wrapArgs.push(t.nullLiteral()); + } -// Convenience function for generating expressions like context.next, -// context.sent, and context.rval. -Ep.contextProperty = function (name, computed) { - return t.memberExpression(this.contextId, computed ? t.stringLiteral(name) : t.identifier(name), !!computed); -}; + if (tryLocsList) { + wrapArgs.push(tryLocsList); + } -// Shorthand for setting context.rval and jumping to `context.stop()`. -Ep.stop = function (rval) { - if (rval) { - this.setReturnValue(rval); - } + var wrapCall = t.callExpression(util.runtimeProperty(node.async ? "async" : "wrap"), wrapArgs); + outerBody.push(t.returnStatement(wrapCall)); + node.body = t.blockStatement(outerBody); // We injected a few new variable declarations (for every hoisted var), + // so we need to add them to the scope. - this.jump(this.finalLoc); -}; + path.get("body.body").forEach(function (p) { + return p.scope.registerDeclaration(p); + }); + var oldDirectives = bodyBlockPath.node.directives; -Ep.setReturnValue = function (valuePath) { - t.assertExpression(valuePath.value); + if (oldDirectives) { + // Babylon represents directives like "use strict" as elements of + // a bodyBlockPath.node.directives array. (#248) + node.body.directives = oldDirectives; + } - this.emitAssign(this.contextProperty("rval"), this.explodeExpression(valuePath)); -}; + var wasGeneratorFunction = node.generator; -Ep.clearPendingException = function (tryLoc, assignee) { - t.assertLiteral(tryLoc); + if (wasGeneratorFunction) { + node.generator = false; + } - var catchCall = t.callExpression(this.contextProperty("catch", true), [tryLoc]); + if (node.async) { + node.async = false; + } - if (assignee) { - this.emitAssign(assignee, catchCall); - } else { - this.emit(catchCall); - } -}; + if (wasGeneratorFunction && t.isExpression(node)) { + util.replaceWithOrRemove(path, t.callExpression(util.runtimeProperty("mark"), [node])); + path.addComment("leading", "#__PURE__"); + } -// Emits code for an unconditional jump to the given location, even if the -// exact value of the location is not yet known. -Ep.jump = function (toLoc) { - this.emitAssign(this.contextProperty("next"), toLoc); - this.emit(t.breakStatement()); -}; + var insertedLocs = emitter.getInsertedLocs(); + path.traverse({ + NumericLiteral: function NumericLiteral(path) { + if (!insertedLocs.has(path.node)) { + return; + } -// Conditional jump. -Ep.jumpIf = function (test, toLoc) { - t.assertExpression(test); - t.assertLiteral(toLoc); + path.replaceWith(t.numericLiteral(path.node.value)); + } + }); // Generators are processed in 'exit' handlers so that regenerator only has to run on + // an ES5 AST, but that means traversal will not pick up newly inserted references + // to things like 'regeneratorRuntime'. To avoid this, we explicitly requeue. - this.emit(t.ifStatement(test, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); -}; + path.requeue(); + }) + } + }; +}; // Check if a node should be transformed by regenerator -// Conditional jump, with the condition negated. -Ep.jumpIfNot = function (test, toLoc) { - t.assertExpression(test); - t.assertLiteral(toLoc); - var negatedTest = void 0; - if (t.isUnaryExpression(test) && test.operator === "!") { - // Avoid double negation. - negatedTest = test.argument; +function shouldRegenerate(node, state) { + if (node.generator) { + if (node.async) { + // Async generator + return state.opts.asyncGenerators !== false; + } else { + // Plain generator + return state.opts.generators !== false; + } + } else if (node.async) { + // Async function + return state.opts.async !== false; } else { - negatedTest = t.unaryExpression("!", test); + // Not a generator or async function. + return false; } +} // Given a NodePath for a Function, return an Expression node that can be +// used to refer reliably to the function object from inside the function. +// This expression is essentially a replacement for arguments.callee, with +// the key advantage that it works in strict mode. - this.emit(t.ifStatement(negatedTest, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); -}; -// Returns a unique MemberExpression that can be used to store and -// retrieve temporary values. Since the object of the member expression is -// the context object, which is presumed to coexist peacefully with all -// other local variables, and since we just increment `nextTempId` -// monotonically, uniqueness is assured. -Ep.makeTempVar = function () { - return this.contextProperty("t" + this.nextTempId++); -}; +function getOuterFnExpr(funPath) { + var t = util.getTypes(); + var node = funPath.node; + t.assertFunction(node); -Ep.getContextFunction = function (id) { - return t.functionExpression(id || null /*Anonymous*/ - , [this.contextId], t.blockStatement([this.getDispatchLoop()]), false, // Not a generator anymore! - false // Nor an expression. - ); -}; + if (!node.id) { + // Default-exported function declarations, and function expressions may not + // have a name to reference, so we explicitly add one. + node.id = funPath.scope.parent.generateUidIdentifier("callee"); + } -// Turns this.listing into a loop of the form -// -// while (1) switch (context.next) { -// case 0: -// ... -// case n: -// return context.stop(); -// } -// -// Each marked location in this.listing will correspond to one generated -// case statement. -Ep.getDispatchLoop = function () { - var self = this; - var cases = []; - var current = void 0; + if (node.generator && // Non-generator functions don't need to be marked. + t.isFunctionDeclaration(node)) { + // Return the identifier returned by runtime.mark(). + return getMarkedFunctionId(funPath); + } - // If we encounter a break, continue, or return statement in a switch - // case, we can skip the rest of the statements until the next case. - var alreadyEnded = false; + return t.clone(node.id); +} - self.listing.forEach(function (stmt, i) { - if (self.marked.hasOwnProperty(i)) { - cases.push(t.switchCase(t.numericLiteral(i), current = [])); - alreadyEnded = false; - } +var getMarkInfo = (0, _private.makeAccessor)(); - if (!alreadyEnded) { - current.push(stmt); - if (t.isCompletionStatement(stmt)) alreadyEnded = true; - } +function getMarkedFunctionId(funPath) { + var t = util.getTypes(); + var node = funPath.node; + t.assertIdentifier(node.id); + var blockPath = funPath.findParent(function (path) { + return path.isProgram() || path.isBlockStatement(); }); - // Now that we know how many statements there will be in this.listing, - // we can finally resolve this.finalLoc.value. - this.finalLoc.value = this.listing.length; + if (!blockPath) { + return node.id; + } - cases.push(t.switchCase(this.finalLoc, [ - // Intentionally fall through to the "end" case... - ]), + var block = blockPath.node; - // So that the runtime can jump to the final location without having - // to know its offset, we provide the "end" case as a synonym. - t.switchCase(t.stringLiteral("end"), [ - // This will check/clear both context.thrown and context.rval. - t.returnStatement(t.callExpression(this.contextProperty("stop"), []))])); + _assert["default"].ok(Array.isArray(block.body)); - return t.whileStatement(t.numericLiteral(1), t.switchStatement(t.assignmentExpression("=", this.contextProperty("prev"), this.contextProperty("next")), cases)); -}; + var info = getMarkInfo(block); -Ep.getTryLocsList = function () { - if (this.tryEntries.length === 0) { - // To avoid adding a needless [] to the majority of runtime.wrap - // argument lists, force the caller to handle this case specially. - return null; + if (!info.decl) { + info.decl = t.variableDeclaration("var", []); + blockPath.unshiftContainer("body", info.decl); + info.declPath = blockPath.get("body.0"); } - var lastLocValue = 0; + _assert["default"].strictEqual(info.declPath.node, info.decl); // Get a new unique identifier for our marked variable. - return t.arrayExpression(this.tryEntries.map(function (tryEntry) { - var thisLocValue = tryEntry.firstLoc.value; - _assert2.default.ok(thisLocValue >= lastLocValue, "try entries out of order"); - lastLocValue = thisLocValue; - var ce = tryEntry.catchEntry; - var fe = tryEntry.finallyEntry; + var markedId = blockPath.scope.generateUidIdentifier("marked"); + var markCallExp = t.callExpression(util.runtimeProperty("mark"), [t.clone(node.id)]); + var index = info.decl.declarations.push(t.variableDeclarator(markedId, markCallExp)) - 1; + var markCallExpPath = info.declPath.get("declarations." + index + ".init"); - var locs = [tryEntry.firstLoc, - // The null here makes a hole in the array. - ce ? ce.firstLoc : null]; + _assert["default"].strictEqual(markCallExpPath.node, markCallExp); - if (fe) { - locs[2] = fe.firstLoc; - locs[3] = fe.afterLoc; + markCallExpPath.addComment("leading", "#__PURE__"); + return t.clone(markedId); +} + +var argumentsThisVisitor = { + "FunctionExpression|FunctionDeclaration|Method": function FunctionExpressionFunctionDeclarationMethod(path) { + path.skip(); + }, + Identifier: function Identifier(path, state) { + if (path.node.name === "arguments" && util.isReference(path)) { + util.replaceWithOrRemove(path, state.getArgsId()); + state.usesArguments = true; } + }, + ThisExpression: function ThisExpression(path, state) { + state.usesThis = true; + } +}; +var functionSentVisitor = { + MetaProperty: function MetaProperty(path) { + var node = path.node; - return t.arrayExpression(locs); - })); + if (node.meta.name === "function" && node.property.name === "sent") { + var t = util.getTypes(); + util.replaceWithOrRemove(path, t.memberExpression(t.clone(this.context), t.identifier("_sent"))); + } + } }; +var awaitVisitor = { + Function: function Function(path) { + path.skip(); // Don't descend into nested function scopes. + }, + AwaitExpression: function AwaitExpression(path) { + var t = util.getTypes(); // Convert await expressions to yield expressions. -// All side effects must be realized in order. + var argument = path.node.argument; // Transforming `await x` to `yield regeneratorRuntime.awrap(x)` + // causes the argument to be wrapped in such a way that the runtime + // can distinguish between awaited and merely yielded values. -// If any subexpression harbors a leap, all subexpressions must be -// neutered of side effects. + util.replaceWithOrRemove(path, t.yieldExpression(t.callExpression(util.runtimeProperty("awrap"), [argument]), false)); + } +}; -// No destructive modification of AST nodes. +},{"./emit":1056,"./hoist":1057,"./replaceShorthandObjectMethod":1061,"./util":1062,"assert":278,"private":1053}],1064:[function(require,module,exports){ +// Generated using `npm run build`. Do not edit. +'use strict'; -Ep.explode = function (path, ignoreResult) { - var node = path.node; - var self = this; +var regenerate = require('regenerate'); - t.assertNode(node); +exports.REGULAR = new Map([['d', regenerate().addRange(0x30, 0x39)], ['D', regenerate().addRange(0x0, 0x2F).addRange(0x3A, 0xFFFF)], ['s', regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF).addRange(0x9, 0xD).addRange(0x2000, 0x200A).addRange(0x2028, 0x2029)], ['S', regenerate().addRange(0x0, 0x8).addRange(0xE, 0x1F).addRange(0x21, 0x9F).addRange(0xA1, 0x167F).addRange(0x1681, 0x1FFF).addRange(0x200B, 0x2027).addRange(0x202A, 0x202E).addRange(0x2030, 0x205E).addRange(0x2060, 0x2FFF).addRange(0x3001, 0xFEFE).addRange(0xFF00, 0xFFFF)], ['w', regenerate(0x5F).addRange(0x30, 0x39).addRange(0x41, 0x5A).addRange(0x61, 0x7A)], ['W', regenerate(0x60).addRange(0x0, 0x2F).addRange(0x3A, 0x40).addRange(0x5B, 0x5E).addRange(0x7B, 0xFFFF)]]); +exports.UNICODE = new Map([['d', regenerate().addRange(0x30, 0x39)], ['D', regenerate().addRange(0x0, 0x2F).addRange(0x3A, 0x10FFFF)], ['s', regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF).addRange(0x9, 0xD).addRange(0x2000, 0x200A).addRange(0x2028, 0x2029)], ['S', regenerate().addRange(0x0, 0x8).addRange(0xE, 0x1F).addRange(0x21, 0x9F).addRange(0xA1, 0x167F).addRange(0x1681, 0x1FFF).addRange(0x200B, 0x2027).addRange(0x202A, 0x202E).addRange(0x2030, 0x205E).addRange(0x2060, 0x2FFF).addRange(0x3001, 0xFEFE).addRange(0xFF00, 0x10FFFF)], ['w', regenerate(0x5F).addRange(0x30, 0x39).addRange(0x41, 0x5A).addRange(0x61, 0x7A)], ['W', regenerate(0x60).addRange(0x0, 0x2F).addRange(0x3A, 0x40).addRange(0x5B, 0x5E).addRange(0x7B, 0x10FFFF)]]); +exports.UNICODE_IGNORE_CASE = new Map([['d', regenerate().addRange(0x30, 0x39)], ['D', regenerate().addRange(0x0, 0x2F).addRange(0x3A, 0x10FFFF)], ['s', regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF).addRange(0x9, 0xD).addRange(0x2000, 0x200A).addRange(0x2028, 0x2029)], ['S', regenerate().addRange(0x0, 0x8).addRange(0xE, 0x1F).addRange(0x21, 0x9F).addRange(0xA1, 0x167F).addRange(0x1681, 0x1FFF).addRange(0x200B, 0x2027).addRange(0x202A, 0x202E).addRange(0x2030, 0x205E).addRange(0x2060, 0x2FFF).addRange(0x3001, 0xFEFE).addRange(0xFF00, 0x10FFFF)], ['w', regenerate(0x5F, 0x17F, 0x212A).addRange(0x30, 0x39).addRange(0x41, 0x5A).addRange(0x61, 0x7A)], ['W', regenerate(0x60).addRange(0x0, 0x2F).addRange(0x3A, 0x40).addRange(0x5B, 0x5E).addRange(0x7B, 0x17E).addRange(0x180, 0x2129).addRange(0x212B, 0x10FFFF)]]); - if (t.isDeclaration(node)) throw getDeclError(node); +},{"regenerate":1055}],1065:[function(require,module,exports){ +"use strict"; - if (t.isStatement(node)) return self.explodeStatement(path); +module.exports = new Map([[0x4B, 0x212A], [0x53, 0x17F], [0x6B, 0x212A], [0x73, 0x17F], [0xB5, 0x39C], [0xC5, 0x212B], [0xDF, 0x1E9E], [0xE5, 0x212B], [0x17F, 0x53], [0x1C4, 0x1C5], [0x1C5, 0x1C4], [0x1C7, 0x1C8], [0x1C8, 0x1C7], [0x1CA, 0x1CB], [0x1CB, 0x1CA], [0x1F1, 0x1F2], [0x1F2, 0x1F1], [0x26A, 0xA7AE], [0x282, 0xA7C5], [0x29D, 0xA7B2], [0x345, 0x1FBE], [0x392, 0x3D0], [0x395, 0x3F5], [0x398, 0x3F4], [0x399, 0x1FBE], [0x39A, 0x3F0], [0x39C, 0xB5], [0x3A0, 0x3D6], [0x3A1, 0x3F1], [0x3A3, 0x3C2], [0x3A6, 0x3D5], [0x3A9, 0x2126], [0x3B8, 0x3F4], [0x3C2, 0x3A3], [0x3C9, 0x2126], [0x3D0, 0x392], [0x3D1, 0x3F4], [0x3D5, 0x3A6], [0x3D6, 0x3A0], [0x3F0, 0x39A], [0x3F1, 0x3A1], [0x3F4, [0x398, 0x3D1, 0x3B8]], [0x3F5, 0x395], [0x412, 0x1C80], [0x414, 0x1C81], [0x41E, 0x1C82], [0x421, 0x1C83], [0x422, 0x1C85], [0x42A, 0x1C86], [0x432, 0x1C80], [0x434, 0x1C81], [0x43E, 0x1C82], [0x441, 0x1C83], [0x442, [0x1C84, 0x1C85]], [0x44A, 0x1C86], [0x462, 0x1C87], [0x463, 0x1C87], [0x10D0, 0x1C90], [0x10D1, 0x1C91], [0x10D2, 0x1C92], [0x10D3, 0x1C93], [0x10D4, 0x1C94], [0x10D5, 0x1C95], [0x10D6, 0x1C96], [0x10D7, 0x1C97], [0x10D8, 0x1C98], [0x10D9, 0x1C99], [0x10DA, 0x1C9A], [0x10DB, 0x1C9B], [0x10DC, 0x1C9C], [0x10DD, 0x1C9D], [0x10DE, 0x1C9E], [0x10DF, 0x1C9F], [0x10E0, 0x1CA0], [0x10E1, 0x1CA1], [0x10E2, 0x1CA2], [0x10E3, 0x1CA3], [0x10E4, 0x1CA4], [0x10E5, 0x1CA5], [0x10E6, 0x1CA6], [0x10E7, 0x1CA7], [0x10E8, 0x1CA8], [0x10E9, 0x1CA9], [0x10EA, 0x1CAA], [0x10EB, 0x1CAB], [0x10EC, 0x1CAC], [0x10ED, 0x1CAD], [0x10EE, 0x1CAE], [0x10EF, 0x1CAF], [0x10F0, 0x1CB0], [0x10F1, 0x1CB1], [0x10F2, 0x1CB2], [0x10F3, 0x1CB3], [0x10F4, 0x1CB4], [0x10F5, 0x1CB5], [0x10F6, 0x1CB6], [0x10F7, 0x1CB7], [0x10F8, 0x1CB8], [0x10F9, 0x1CB9], [0x10FA, 0x1CBA], [0x10FD, 0x1CBD], [0x10FE, 0x1CBE], [0x10FF, 0x1CBF], [0x13A0, 0xAB70], [0x13A1, 0xAB71], [0x13A2, 0xAB72], [0x13A3, 0xAB73], [0x13A4, 0xAB74], [0x13A5, 0xAB75], [0x13A6, 0xAB76], [0x13A7, 0xAB77], [0x13A8, 0xAB78], [0x13A9, 0xAB79], [0x13AA, 0xAB7A], [0x13AB, 0xAB7B], [0x13AC, 0xAB7C], [0x13AD, 0xAB7D], [0x13AE, 0xAB7E], [0x13AF, 0xAB7F], [0x13B0, 0xAB80], [0x13B1, 0xAB81], [0x13B2, 0xAB82], [0x13B3, 0xAB83], [0x13B4, 0xAB84], [0x13B5, 0xAB85], [0x13B6, 0xAB86], [0x13B7, 0xAB87], [0x13B8, 0xAB88], [0x13B9, 0xAB89], [0x13BA, 0xAB8A], [0x13BB, 0xAB8B], [0x13BC, 0xAB8C], [0x13BD, 0xAB8D], [0x13BE, 0xAB8E], [0x13BF, 0xAB8F], [0x13C0, 0xAB90], [0x13C1, 0xAB91], [0x13C2, 0xAB92], [0x13C3, 0xAB93], [0x13C4, 0xAB94], [0x13C5, 0xAB95], [0x13C6, 0xAB96], [0x13C7, 0xAB97], [0x13C8, 0xAB98], [0x13C9, 0xAB99], [0x13CA, 0xAB9A], [0x13CB, 0xAB9B], [0x13CC, 0xAB9C], [0x13CD, 0xAB9D], [0x13CE, 0xAB9E], [0x13CF, 0xAB9F], [0x13D0, 0xABA0], [0x13D1, 0xABA1], [0x13D2, 0xABA2], [0x13D3, 0xABA3], [0x13D4, 0xABA4], [0x13D5, 0xABA5], [0x13D6, 0xABA6], [0x13D7, 0xABA7], [0x13D8, 0xABA8], [0x13D9, 0xABA9], [0x13DA, 0xABAA], [0x13DB, 0xABAB], [0x13DC, 0xABAC], [0x13DD, 0xABAD], [0x13DE, 0xABAE], [0x13DF, 0xABAF], [0x13E0, 0xABB0], [0x13E1, 0xABB1], [0x13E2, 0xABB2], [0x13E3, 0xABB3], [0x13E4, 0xABB4], [0x13E5, 0xABB5], [0x13E6, 0xABB6], [0x13E7, 0xABB7], [0x13E8, 0xABB8], [0x13E9, 0xABB9], [0x13EA, 0xABBA], [0x13EB, 0xABBB], [0x13EC, 0xABBC], [0x13ED, 0xABBD], [0x13EE, 0xABBE], [0x13EF, 0xABBF], [0x13F0, 0x13F8], [0x13F1, 0x13F9], [0x13F2, 0x13FA], [0x13F3, 0x13FB], [0x13F4, 0x13FC], [0x13F5, 0x13FD], [0x13F8, 0x13F0], [0x13F9, 0x13F1], [0x13FA, 0x13F2], [0x13FB, 0x13F3], [0x13FC, 0x13F4], [0x13FD, 0x13F5], [0x1C80, [0x412, 0x432]], [0x1C81, [0x414, 0x434]], [0x1C82, [0x41E, 0x43E]], [0x1C83, [0x421, 0x441]], [0x1C84, [0x1C85, 0x442]], [0x1C85, [0x422, 0x1C84, 0x442]], [0x1C86, [0x42A, 0x44A]], [0x1C87, [0x462, 0x463]], [0x1C88, [0xA64A, 0xA64B]], [0x1C90, 0x10D0], [0x1C91, 0x10D1], [0x1C92, 0x10D2], [0x1C93, 0x10D3], [0x1C94, 0x10D4], [0x1C95, 0x10D5], [0x1C96, 0x10D6], [0x1C97, 0x10D7], [0x1C98, 0x10D8], [0x1C99, 0x10D9], [0x1C9A, 0x10DA], [0x1C9B, 0x10DB], [0x1C9C, 0x10DC], [0x1C9D, 0x10DD], [0x1C9E, 0x10DE], [0x1C9F, 0x10DF], [0x1CA0, 0x10E0], [0x1CA1, 0x10E1], [0x1CA2, 0x10E2], [0x1CA3, 0x10E3], [0x1CA4, 0x10E4], [0x1CA5, 0x10E5], [0x1CA6, 0x10E6], [0x1CA7, 0x10E7], [0x1CA8, 0x10E8], [0x1CA9, 0x10E9], [0x1CAA, 0x10EA], [0x1CAB, 0x10EB], [0x1CAC, 0x10EC], [0x1CAD, 0x10ED], [0x1CAE, 0x10EE], [0x1CAF, 0x10EF], [0x1CB0, 0x10F0], [0x1CB1, 0x10F1], [0x1CB2, 0x10F2], [0x1CB3, 0x10F3], [0x1CB4, 0x10F4], [0x1CB5, 0x10F5], [0x1CB6, 0x10F6], [0x1CB7, 0x10F7], [0x1CB8, 0x10F8], [0x1CB9, 0x10F9], [0x1CBA, 0x10FA], [0x1CBD, 0x10FD], [0x1CBE, 0x10FE], [0x1CBF, 0x10FF], [0x1D8E, 0xA7C6], [0x1E60, 0x1E9B], [0x1E9B, 0x1E60], [0x1E9E, 0xDF], [0x1F80, 0x1F88], [0x1F81, 0x1F89], [0x1F82, 0x1F8A], [0x1F83, 0x1F8B], [0x1F84, 0x1F8C], [0x1F85, 0x1F8D], [0x1F86, 0x1F8E], [0x1F87, 0x1F8F], [0x1F88, 0x1F80], [0x1F89, 0x1F81], [0x1F8A, 0x1F82], [0x1F8B, 0x1F83], [0x1F8C, 0x1F84], [0x1F8D, 0x1F85], [0x1F8E, 0x1F86], [0x1F8F, 0x1F87], [0x1F90, 0x1F98], [0x1F91, 0x1F99], [0x1F92, 0x1F9A], [0x1F93, 0x1F9B], [0x1F94, 0x1F9C], [0x1F95, 0x1F9D], [0x1F96, 0x1F9E], [0x1F97, 0x1F9F], [0x1F98, 0x1F90], [0x1F99, 0x1F91], [0x1F9A, 0x1F92], [0x1F9B, 0x1F93], [0x1F9C, 0x1F94], [0x1F9D, 0x1F95], [0x1F9E, 0x1F96], [0x1F9F, 0x1F97], [0x1FA0, 0x1FA8], [0x1FA1, 0x1FA9], [0x1FA2, 0x1FAA], [0x1FA3, 0x1FAB], [0x1FA4, 0x1FAC], [0x1FA5, 0x1FAD], [0x1FA6, 0x1FAE], [0x1FA7, 0x1FAF], [0x1FA8, 0x1FA0], [0x1FA9, 0x1FA1], [0x1FAA, 0x1FA2], [0x1FAB, 0x1FA3], [0x1FAC, 0x1FA4], [0x1FAD, 0x1FA5], [0x1FAE, 0x1FA6], [0x1FAF, 0x1FA7], [0x1FB3, 0x1FBC], [0x1FBC, 0x1FB3], [0x1FBE, [0x345, 0x399]], [0x1FC3, 0x1FCC], [0x1FCC, 0x1FC3], [0x1FF3, 0x1FFC], [0x1FFC, 0x1FF3], [0x2126, [0x3A9, 0x3C9]], [0x212A, 0x4B], [0x212B, [0xC5, 0xE5]], [0xA64A, 0x1C88], [0xA64B, 0x1C88], [0xA794, 0xA7C4], [0xA7AE, 0x26A], [0xA7B2, 0x29D], [0xA7B3, 0xAB53], [0xA7B4, 0xA7B5], [0xA7B5, 0xA7B4], [0xA7B6, 0xA7B7], [0xA7B7, 0xA7B6], [0xA7B8, 0xA7B9], [0xA7B9, 0xA7B8], [0xA7BA, 0xA7BB], [0xA7BB, 0xA7BA], [0xA7BC, 0xA7BD], [0xA7BD, 0xA7BC], [0xA7BE, 0xA7BF], [0xA7BF, 0xA7BE], [0xA7C2, 0xA7C3], [0xA7C3, 0xA7C2], [0xA7C4, 0xA794], [0xA7C5, 0x282], [0xA7C6, 0x1D8E], [0xAB53, 0xA7B3], [0xAB70, 0x13A0], [0xAB71, 0x13A1], [0xAB72, 0x13A2], [0xAB73, 0x13A3], [0xAB74, 0x13A4], [0xAB75, 0x13A5], [0xAB76, 0x13A6], [0xAB77, 0x13A7], [0xAB78, 0x13A8], [0xAB79, 0x13A9], [0xAB7A, 0x13AA], [0xAB7B, 0x13AB], [0xAB7C, 0x13AC], [0xAB7D, 0x13AD], [0xAB7E, 0x13AE], [0xAB7F, 0x13AF], [0xAB80, 0x13B0], [0xAB81, 0x13B1], [0xAB82, 0x13B2], [0xAB83, 0x13B3], [0xAB84, 0x13B4], [0xAB85, 0x13B5], [0xAB86, 0x13B6], [0xAB87, 0x13B7], [0xAB88, 0x13B8], [0xAB89, 0x13B9], [0xAB8A, 0x13BA], [0xAB8B, 0x13BB], [0xAB8C, 0x13BC], [0xAB8D, 0x13BD], [0xAB8E, 0x13BE], [0xAB8F, 0x13BF], [0xAB90, 0x13C0], [0xAB91, 0x13C1], [0xAB92, 0x13C2], [0xAB93, 0x13C3], [0xAB94, 0x13C4], [0xAB95, 0x13C5], [0xAB96, 0x13C6], [0xAB97, 0x13C7], [0xAB98, 0x13C8], [0xAB99, 0x13C9], [0xAB9A, 0x13CA], [0xAB9B, 0x13CB], [0xAB9C, 0x13CC], [0xAB9D, 0x13CD], [0xAB9E, 0x13CE], [0xAB9F, 0x13CF], [0xABA0, 0x13D0], [0xABA1, 0x13D1], [0xABA2, 0x13D2], [0xABA3, 0x13D3], [0xABA4, 0x13D4], [0xABA5, 0x13D5], [0xABA6, 0x13D6], [0xABA7, 0x13D7], [0xABA8, 0x13D8], [0xABA9, 0x13D9], [0xABAA, 0x13DA], [0xABAB, 0x13DB], [0xABAC, 0x13DC], [0xABAD, 0x13DD], [0xABAE, 0x13DE], [0xABAF, 0x13DF], [0xABB0, 0x13E0], [0xABB1, 0x13E1], [0xABB2, 0x13E2], [0xABB3, 0x13E3], [0xABB4, 0x13E4], [0xABB5, 0x13E5], [0xABB6, 0x13E6], [0xABB7, 0x13E7], [0xABB8, 0x13E8], [0xABB9, 0x13E9], [0xABBA, 0x13EA], [0xABBB, 0x13EB], [0xABBC, 0x13EC], [0xABBD, 0x13ED], [0xABBE, 0x13EE], [0xABBF, 0x13EF], [0x10400, 0x10428], [0x10401, 0x10429], [0x10402, 0x1042A], [0x10403, 0x1042B], [0x10404, 0x1042C], [0x10405, 0x1042D], [0x10406, 0x1042E], [0x10407, 0x1042F], [0x10408, 0x10430], [0x10409, 0x10431], [0x1040A, 0x10432], [0x1040B, 0x10433], [0x1040C, 0x10434], [0x1040D, 0x10435], [0x1040E, 0x10436], [0x1040F, 0x10437], [0x10410, 0x10438], [0x10411, 0x10439], [0x10412, 0x1043A], [0x10413, 0x1043B], [0x10414, 0x1043C], [0x10415, 0x1043D], [0x10416, 0x1043E], [0x10417, 0x1043F], [0x10418, 0x10440], [0x10419, 0x10441], [0x1041A, 0x10442], [0x1041B, 0x10443], [0x1041C, 0x10444], [0x1041D, 0x10445], [0x1041E, 0x10446], [0x1041F, 0x10447], [0x10420, 0x10448], [0x10421, 0x10449], [0x10422, 0x1044A], [0x10423, 0x1044B], [0x10424, 0x1044C], [0x10425, 0x1044D], [0x10426, 0x1044E], [0x10427, 0x1044F], [0x10428, 0x10400], [0x10429, 0x10401], [0x1042A, 0x10402], [0x1042B, 0x10403], [0x1042C, 0x10404], [0x1042D, 0x10405], [0x1042E, 0x10406], [0x1042F, 0x10407], [0x10430, 0x10408], [0x10431, 0x10409], [0x10432, 0x1040A], [0x10433, 0x1040B], [0x10434, 0x1040C], [0x10435, 0x1040D], [0x10436, 0x1040E], [0x10437, 0x1040F], [0x10438, 0x10410], [0x10439, 0x10411], [0x1043A, 0x10412], [0x1043B, 0x10413], [0x1043C, 0x10414], [0x1043D, 0x10415], [0x1043E, 0x10416], [0x1043F, 0x10417], [0x10440, 0x10418], [0x10441, 0x10419], [0x10442, 0x1041A], [0x10443, 0x1041B], [0x10444, 0x1041C], [0x10445, 0x1041D], [0x10446, 0x1041E], [0x10447, 0x1041F], [0x10448, 0x10420], [0x10449, 0x10421], [0x1044A, 0x10422], [0x1044B, 0x10423], [0x1044C, 0x10424], [0x1044D, 0x10425], [0x1044E, 0x10426], [0x1044F, 0x10427], [0x104B0, 0x104D8], [0x104B1, 0x104D9], [0x104B2, 0x104DA], [0x104B3, 0x104DB], [0x104B4, 0x104DC], [0x104B5, 0x104DD], [0x104B6, 0x104DE], [0x104B7, 0x104DF], [0x104B8, 0x104E0], [0x104B9, 0x104E1], [0x104BA, 0x104E2], [0x104BB, 0x104E3], [0x104BC, 0x104E4], [0x104BD, 0x104E5], [0x104BE, 0x104E6], [0x104BF, 0x104E7], [0x104C0, 0x104E8], [0x104C1, 0x104E9], [0x104C2, 0x104EA], [0x104C3, 0x104EB], [0x104C4, 0x104EC], [0x104C5, 0x104ED], [0x104C6, 0x104EE], [0x104C7, 0x104EF], [0x104C8, 0x104F0], [0x104C9, 0x104F1], [0x104CA, 0x104F2], [0x104CB, 0x104F3], [0x104CC, 0x104F4], [0x104CD, 0x104F5], [0x104CE, 0x104F6], [0x104CF, 0x104F7], [0x104D0, 0x104F8], [0x104D1, 0x104F9], [0x104D2, 0x104FA], [0x104D3, 0x104FB], [0x104D8, 0x104B0], [0x104D9, 0x104B1], [0x104DA, 0x104B2], [0x104DB, 0x104B3], [0x104DC, 0x104B4], [0x104DD, 0x104B5], [0x104DE, 0x104B6], [0x104DF, 0x104B7], [0x104E0, 0x104B8], [0x104E1, 0x104B9], [0x104E2, 0x104BA], [0x104E3, 0x104BB], [0x104E4, 0x104BC], [0x104E5, 0x104BD], [0x104E6, 0x104BE], [0x104E7, 0x104BF], [0x104E8, 0x104C0], [0x104E9, 0x104C1], [0x104EA, 0x104C2], [0x104EB, 0x104C3], [0x104EC, 0x104C4], [0x104ED, 0x104C5], [0x104EE, 0x104C6], [0x104EF, 0x104C7], [0x104F0, 0x104C8], [0x104F1, 0x104C9], [0x104F2, 0x104CA], [0x104F3, 0x104CB], [0x104F4, 0x104CC], [0x104F5, 0x104CD], [0x104F6, 0x104CE], [0x104F7, 0x104CF], [0x104F8, 0x104D0], [0x104F9, 0x104D1], [0x104FA, 0x104D2], [0x104FB, 0x104D3], [0x10C80, 0x10CC0], [0x10C81, 0x10CC1], [0x10C82, 0x10CC2], [0x10C83, 0x10CC3], [0x10C84, 0x10CC4], [0x10C85, 0x10CC5], [0x10C86, 0x10CC6], [0x10C87, 0x10CC7], [0x10C88, 0x10CC8], [0x10C89, 0x10CC9], [0x10C8A, 0x10CCA], [0x10C8B, 0x10CCB], [0x10C8C, 0x10CCC], [0x10C8D, 0x10CCD], [0x10C8E, 0x10CCE], [0x10C8F, 0x10CCF], [0x10C90, 0x10CD0], [0x10C91, 0x10CD1], [0x10C92, 0x10CD2], [0x10C93, 0x10CD3], [0x10C94, 0x10CD4], [0x10C95, 0x10CD5], [0x10C96, 0x10CD6], [0x10C97, 0x10CD7], [0x10C98, 0x10CD8], [0x10C99, 0x10CD9], [0x10C9A, 0x10CDA], [0x10C9B, 0x10CDB], [0x10C9C, 0x10CDC], [0x10C9D, 0x10CDD], [0x10C9E, 0x10CDE], [0x10C9F, 0x10CDF], [0x10CA0, 0x10CE0], [0x10CA1, 0x10CE1], [0x10CA2, 0x10CE2], [0x10CA3, 0x10CE3], [0x10CA4, 0x10CE4], [0x10CA5, 0x10CE5], [0x10CA6, 0x10CE6], [0x10CA7, 0x10CE7], [0x10CA8, 0x10CE8], [0x10CA9, 0x10CE9], [0x10CAA, 0x10CEA], [0x10CAB, 0x10CEB], [0x10CAC, 0x10CEC], [0x10CAD, 0x10CED], [0x10CAE, 0x10CEE], [0x10CAF, 0x10CEF], [0x10CB0, 0x10CF0], [0x10CB1, 0x10CF1], [0x10CB2, 0x10CF2], [0x10CC0, 0x10C80], [0x10CC1, 0x10C81], [0x10CC2, 0x10C82], [0x10CC3, 0x10C83], [0x10CC4, 0x10C84], [0x10CC5, 0x10C85], [0x10CC6, 0x10C86], [0x10CC7, 0x10C87], [0x10CC8, 0x10C88], [0x10CC9, 0x10C89], [0x10CCA, 0x10C8A], [0x10CCB, 0x10C8B], [0x10CCC, 0x10C8C], [0x10CCD, 0x10C8D], [0x10CCE, 0x10C8E], [0x10CCF, 0x10C8F], [0x10CD0, 0x10C90], [0x10CD1, 0x10C91], [0x10CD2, 0x10C92], [0x10CD3, 0x10C93], [0x10CD4, 0x10C94], [0x10CD5, 0x10C95], [0x10CD6, 0x10C96], [0x10CD7, 0x10C97], [0x10CD8, 0x10C98], [0x10CD9, 0x10C99], [0x10CDA, 0x10C9A], [0x10CDB, 0x10C9B], [0x10CDC, 0x10C9C], [0x10CDD, 0x10C9D], [0x10CDE, 0x10C9E], [0x10CDF, 0x10C9F], [0x10CE0, 0x10CA0], [0x10CE1, 0x10CA1], [0x10CE2, 0x10CA2], [0x10CE3, 0x10CA3], [0x10CE4, 0x10CA4], [0x10CE5, 0x10CA5], [0x10CE6, 0x10CA6], [0x10CE7, 0x10CA7], [0x10CE8, 0x10CA8], [0x10CE9, 0x10CA9], [0x10CEA, 0x10CAA], [0x10CEB, 0x10CAB], [0x10CEC, 0x10CAC], [0x10CED, 0x10CAD], [0x10CEE, 0x10CAE], [0x10CEF, 0x10CAF], [0x10CF0, 0x10CB0], [0x10CF1, 0x10CB1], [0x10CF2, 0x10CB2], [0x118A0, 0x118C0], [0x118A1, 0x118C1], [0x118A2, 0x118C2], [0x118A3, 0x118C3], [0x118A4, 0x118C4], [0x118A5, 0x118C5], [0x118A6, 0x118C6], [0x118A7, 0x118C7], [0x118A8, 0x118C8], [0x118A9, 0x118C9], [0x118AA, 0x118CA], [0x118AB, 0x118CB], [0x118AC, 0x118CC], [0x118AD, 0x118CD], [0x118AE, 0x118CE], [0x118AF, 0x118CF], [0x118B0, 0x118D0], [0x118B1, 0x118D1], [0x118B2, 0x118D2], [0x118B3, 0x118D3], [0x118B4, 0x118D4], [0x118B5, 0x118D5], [0x118B6, 0x118D6], [0x118B7, 0x118D7], [0x118B8, 0x118D8], [0x118B9, 0x118D9], [0x118BA, 0x118DA], [0x118BB, 0x118DB], [0x118BC, 0x118DC], [0x118BD, 0x118DD], [0x118BE, 0x118DE], [0x118BF, 0x118DF], [0x118C0, 0x118A0], [0x118C1, 0x118A1], [0x118C2, 0x118A2], [0x118C3, 0x118A3], [0x118C4, 0x118A4], [0x118C5, 0x118A5], [0x118C6, 0x118A6], [0x118C7, 0x118A7], [0x118C8, 0x118A8], [0x118C9, 0x118A9], [0x118CA, 0x118AA], [0x118CB, 0x118AB], [0x118CC, 0x118AC], [0x118CD, 0x118AD], [0x118CE, 0x118AE], [0x118CF, 0x118AF], [0x118D0, 0x118B0], [0x118D1, 0x118B1], [0x118D2, 0x118B2], [0x118D3, 0x118B3], [0x118D4, 0x118B4], [0x118D5, 0x118B5], [0x118D6, 0x118B6], [0x118D7, 0x118B7], [0x118D8, 0x118B8], [0x118D9, 0x118B9], [0x118DA, 0x118BA], [0x118DB, 0x118BB], [0x118DC, 0x118BC], [0x118DD, 0x118BD], [0x118DE, 0x118BE], [0x118DF, 0x118BF], [0x16E40, 0x16E60], [0x16E41, 0x16E61], [0x16E42, 0x16E62], [0x16E43, 0x16E63], [0x16E44, 0x16E64], [0x16E45, 0x16E65], [0x16E46, 0x16E66], [0x16E47, 0x16E67], [0x16E48, 0x16E68], [0x16E49, 0x16E69], [0x16E4A, 0x16E6A], [0x16E4B, 0x16E6B], [0x16E4C, 0x16E6C], [0x16E4D, 0x16E6D], [0x16E4E, 0x16E6E], [0x16E4F, 0x16E6F], [0x16E50, 0x16E70], [0x16E51, 0x16E71], [0x16E52, 0x16E72], [0x16E53, 0x16E73], [0x16E54, 0x16E74], [0x16E55, 0x16E75], [0x16E56, 0x16E76], [0x16E57, 0x16E77], [0x16E58, 0x16E78], [0x16E59, 0x16E79], [0x16E5A, 0x16E7A], [0x16E5B, 0x16E7B], [0x16E5C, 0x16E7C], [0x16E5D, 0x16E7D], [0x16E5E, 0x16E7E], [0x16E5F, 0x16E7F], [0x16E60, 0x16E40], [0x16E61, 0x16E41], [0x16E62, 0x16E42], [0x16E63, 0x16E43], [0x16E64, 0x16E44], [0x16E65, 0x16E45], [0x16E66, 0x16E46], [0x16E67, 0x16E47], [0x16E68, 0x16E48], [0x16E69, 0x16E49], [0x16E6A, 0x16E4A], [0x16E6B, 0x16E4B], [0x16E6C, 0x16E4C], [0x16E6D, 0x16E4D], [0x16E6E, 0x16E4E], [0x16E6F, 0x16E4F], [0x16E70, 0x16E50], [0x16E71, 0x16E51], [0x16E72, 0x16E52], [0x16E73, 0x16E53], [0x16E74, 0x16E54], [0x16E75, 0x16E55], [0x16E76, 0x16E56], [0x16E77, 0x16E57], [0x16E78, 0x16E58], [0x16E79, 0x16E59], [0x16E7A, 0x16E5A], [0x16E7B, 0x16E5B], [0x16E7C, 0x16E5C], [0x16E7D, 0x16E5D], [0x16E7E, 0x16E5E], [0x16E7F, 0x16E5F], [0x1E900, 0x1E922], [0x1E901, 0x1E923], [0x1E902, 0x1E924], [0x1E903, 0x1E925], [0x1E904, 0x1E926], [0x1E905, 0x1E927], [0x1E906, 0x1E928], [0x1E907, 0x1E929], [0x1E908, 0x1E92A], [0x1E909, 0x1E92B], [0x1E90A, 0x1E92C], [0x1E90B, 0x1E92D], [0x1E90C, 0x1E92E], [0x1E90D, 0x1E92F], [0x1E90E, 0x1E930], [0x1E90F, 0x1E931], [0x1E910, 0x1E932], [0x1E911, 0x1E933], [0x1E912, 0x1E934], [0x1E913, 0x1E935], [0x1E914, 0x1E936], [0x1E915, 0x1E937], [0x1E916, 0x1E938], [0x1E917, 0x1E939], [0x1E918, 0x1E93A], [0x1E919, 0x1E93B], [0x1E91A, 0x1E93C], [0x1E91B, 0x1E93D], [0x1E91C, 0x1E93E], [0x1E91D, 0x1E93F], [0x1E91E, 0x1E940], [0x1E91F, 0x1E941], [0x1E920, 0x1E942], [0x1E921, 0x1E943], [0x1E922, 0x1E900], [0x1E923, 0x1E901], [0x1E924, 0x1E902], [0x1E925, 0x1E903], [0x1E926, 0x1E904], [0x1E927, 0x1E905], [0x1E928, 0x1E906], [0x1E929, 0x1E907], [0x1E92A, 0x1E908], [0x1E92B, 0x1E909], [0x1E92C, 0x1E90A], [0x1E92D, 0x1E90B], [0x1E92E, 0x1E90C], [0x1E92F, 0x1E90D], [0x1E930, 0x1E90E], [0x1E931, 0x1E90F], [0x1E932, 0x1E910], [0x1E933, 0x1E911], [0x1E934, 0x1E912], [0x1E935, 0x1E913], [0x1E936, 0x1E914], [0x1E937, 0x1E915], [0x1E938, 0x1E916], [0x1E939, 0x1E917], [0x1E93A, 0x1E918], [0x1E93B, 0x1E919], [0x1E93C, 0x1E91A], [0x1E93D, 0x1E91B], [0x1E93E, 0x1E91C], [0x1E93F, 0x1E91D], [0x1E940, 0x1E91E], [0x1E941, 0x1E91F], [0x1E942, 0x1E920], [0x1E943, 0x1E921]]); - if (t.isExpression(node)) return self.explodeExpression(path, ignoreResult); +},{}],1066:[function(require,module,exports){ +'use strict'; - switch (node.type) { - case "Program": - return path.get("body").map(self.explodeStatement, self); +var generate = require('regjsgen').generate; - case "VariableDeclarator": - throw getDeclError(node); +var parse = require('regjsparser').parse; - // These node types should be handled by their parent nodes - // (ObjectExpression, SwitchStatement, and TryStatement, respectively). - case "Property": - case "SwitchCase": - case "CatchClause": - throw new Error(node.type + " nodes should be handled by their parents"); +var regenerate = require('regenerate'); - default: - throw new Error("unknown Node of type " + (0, _stringify2.default)(node.type)); - } -}; +var unicodeMatchProperty = require('unicode-match-property-ecmascript'); -function getDeclError(node) { - return new Error("all declarations should have been transformed into " + "assignments before the Exploder began its work: " + (0, _stringify2.default)(node)); -} +var unicodeMatchPropertyValue = require('unicode-match-property-value-ecmascript'); -Ep.explodeStatement = function (path, labelId) { - var stmt = path.node; - var self = this; - var before = void 0, - after = void 0, - head = void 0; +var iuMappings = require('./data/iu-mappings.js'); - t.assertStatement(stmt); +var ESCAPE_SETS = require('./data/character-class-escape-sets.js'); // Prepare a Regenerate set containing all code points, used for negative +// character classes (if any). - if (labelId) { - t.assertIdentifier(labelId); - } else { - labelId = null; - } - // Explode BlockStatement nodes even if they do not contain a yield, - // because we don't want or need the curly braces. - if (t.isBlockStatement(stmt)) { - path.get("body").forEach(function (path) { - self.explodeStatement(path); - }); - return; - } +var UNICODE_SET = regenerate().addRange(0x0, 0x10FFFF); // Without the `u` flag, the range stops at 0xFFFF. +// https://mths.be/es6#sec-pattern-semantics - if (!meta.containsLeap(stmt)) { - // Technically we should be able to avoid emitting the statement - // altogether if !meta.hasSideEffects(stmt), but that leads to - // confusing generated code (for instance, `while (true) {}` just - // disappears) and is probably a more appropriate job for a dedicated - // dead code elimination pass. - self.emit(stmt); - return; - } +var BMP_SET = regenerate().addRange(0x0, 0xFFFF); // Prepare a Regenerate set containing all code points that are supposed to be +// matched by `/./u`. https://mths.be/es6#sec-atom - switch (stmt.type) { - case "ExpressionStatement": - self.explodeExpression(path.get("expression"), true); - break; +var DOT_SET_UNICODE = UNICODE_SET.clone() // all Unicode code points +.remove( // minus `LineTerminator`s (https://mths.be/es6#sec-line-terminators): +0x000A, // Line Feed +0x000D, // Carriage Return +0x2028, // Line Separator +0x2029 // Paragraph Separator +); - case "LabeledStatement": - after = loc(); +var getCharacterClassEscapeSet = function getCharacterClassEscapeSet(character, unicode, ignoreCase) { + if (unicode) { + if (ignoreCase) { + return ESCAPE_SETS.UNICODE_IGNORE_CASE.get(character); + } - // Did you know you can break from any labeled block statement or - // control structure? Well, you can! Note: when a labeled loop is - // encountered, the leap.LabeledEntry created here will immediately - // enclose a leap.LoopEntry on the leap manager's stack, and both - // entries will have the same label. Though this works just fine, it - // may seem a bit redundant. In theory, we could check here to - // determine if stmt knows how to handle its own label; for example, - // stmt happens to be a WhileStatement and so we know it's going to - // establish its own LoopEntry when we explode it (below). Then this - // LabeledEntry would be unnecessary. Alternatively, we might be - // tempted not to pass stmt.label down into self.explodeStatement, - // because we've handled the label here, but that's a mistake because - // labeled loops may contain labeled continue statements, which is not - // something we can handle in this generic case. All in all, I think a - // little redundancy greatly simplifies the logic of this case, since - // it's clear that we handle all possible LabeledStatements correctly - // here, regardless of whether they interact with the leap manager - // themselves. Also remember that labels and break/continue-to-label - // statements are rare, and all of this logic happens at transform - // time, so it has no additional runtime cost. - self.leapManager.withEntry(new leap.LabeledEntry(after, stmt.label), function () { - self.explodeStatement(path.get("body"), stmt.label); - }); + return ESCAPE_SETS.UNICODE.get(character); + } - self.mark(after); + return ESCAPE_SETS.REGULAR.get(character); +}; - break; +var getUnicodeDotSet = function getUnicodeDotSet(dotAll) { + return dotAll ? UNICODE_SET : DOT_SET_UNICODE; +}; - case "WhileStatement": - before = loc(); - after = loc(); +var getUnicodePropertyValueSet = function getUnicodePropertyValueSet(property, value) { + var path = value ? "".concat(property, "/").concat(value) : "Binary_Property/".concat(property); - self.mark(before); - self.jumpIfNot(self.explodeExpression(path.get("test")), after); - self.leapManager.withEntry(new leap.LoopEntry(after, before, labelId), function () { - self.explodeStatement(path.get("body")); - }); - self.jump(before); - self.mark(after); + try { + return require("regenerate-unicode-properties/".concat(path, ".js")); + } catch (exception) { + throw new Error("Failed to recognize value `".concat(value, "` for property ") + "`".concat(property, "`.")); + } +}; - break; +var handleLoneUnicodePropertyNameOrValue = function handleLoneUnicodePropertyNameOrValue(value) { + // It could be a `General_Category` value or a binary property. + // Note: `unicodeMatchPropertyValue` throws on invalid values. + try { + var _property = 'General_Category'; + var category = unicodeMatchPropertyValue(_property, value); + return getUnicodePropertyValueSet(_property, category); + } catch (exception) {} // It’s not a `General_Category` value, so check if it’s a binary + // property. Note: `unicodeMatchProperty` throws on invalid properties. - case "DoWhileStatement": - var first = loc(); - var test = loc(); - after = loc(); - self.mark(first); - self.leapManager.withEntry(new leap.LoopEntry(after, test, labelId), function () { - self.explode(path.get("body")); - }); - self.mark(test); - self.jumpIf(self.explodeExpression(path.get("test")), first); - self.mark(after); + var property = unicodeMatchProperty(value); + return getUnicodePropertyValueSet(property); +}; - break; +var getUnicodePropertyEscapeSet = function getUnicodePropertyEscapeSet(value, isNegative) { + var parts = value.split('='); + var firstPart = parts[0]; + var set; - case "ForStatement": - head = loc(); - var update = loc(); - after = loc(); + if (parts.length == 1) { + set = handleLoneUnicodePropertyNameOrValue(firstPart); + } else { + // The pattern consists of two parts, i.e. `Property=Value`. + var property = unicodeMatchProperty(firstPart); - if (stmt.init) { - // We pass true here to indicate that if stmt.init is an expression - // then we do not care about its result. - self.explode(path.get("init"), true); - } + var _value = unicodeMatchPropertyValue(property, parts[1]); - self.mark(head); + set = getUnicodePropertyValueSet(property, _value); + } - if (stmt.test) { - self.jumpIfNot(self.explodeExpression(path.get("test")), after); - } else { - // No test means continue unconditionally. - } + if (isNegative) { + return UNICODE_SET.clone().remove(set); + } - self.leapManager.withEntry(new leap.LoopEntry(after, update, labelId), function () { - self.explodeStatement(path.get("body")); - }); + return set.clone(); +}; // Given a range of code points, add any case-folded code points in that range +// to a set. - self.mark(update); - if (stmt.update) { - // We pass true here to indicate that if stmt.update is an - // expression then we do not care about its result. - self.explode(path.get("update"), true); - } +regenerate.prototype.iuAddRange = function (min, max) { + var $this = this; - self.jump(head); + do { + var folded = caseFold(min); - self.mark(after); + if (folded) { + $this.add(folded); + } + } while (++min <= max); - break; + return $this; +}; - case "TypeCastExpression": - return self.explodeExpression(path.get("expression")); +var update = function update(item, pattern) { + var tree = parse(pattern, config.useUnicodeFlag ? 'u' : ''); - case "ForInStatement": - head = loc(); - after = loc(); + switch (tree.type) { + case 'characterClass': + case 'group': + case 'value': + // No wrapping needed. + break; - var keyIterNextFn = self.makeTempVar(); - self.emitAssign(keyIterNextFn, t.callExpression(util.runtimeProperty("keys"), [self.explodeExpression(path.get("right"))])); + default: + // Wrap the pattern in a non-capturing group. + tree = wrap(tree, pattern); + } - self.mark(head); + Object.assign(item, tree); +}; - var keyInfoTmpVar = self.makeTempVar(); - self.jumpIf(t.memberExpression(t.assignmentExpression("=", keyInfoTmpVar, t.callExpression(keyIterNextFn, [])), t.identifier("done"), false), after); +var wrap = function wrap(tree, pattern) { + // Wrap the pattern in a non-capturing group. + return { + 'type': 'group', + 'behavior': 'ignore', + 'body': [tree], + 'raw': "(?:".concat(pattern, ")") + }; +}; - self.emitAssign(stmt.left, t.memberExpression(keyInfoTmpVar, t.identifier("value"), false)); +var caseFold = function caseFold(codePoint) { + return iuMappings.get(codePoint) || false; +}; - self.leapManager.withEntry(new leap.LoopEntry(after, head, labelId), function () { - self.explodeStatement(path.get("body")); - }); +var processCharacterClass = function processCharacterClass(characterClassItem, regenerateOptions) { + var set = regenerate(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - self.jump(head); + try { + for (var _iterator = characterClassItem.body[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var item = _step.value; - self.mark(after); + switch (item.type) { + case 'value': + set.add(item.codePoint); - break; + if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) { + var folded = caseFold(item.codePoint); - case "BreakStatement": - self.emitAbruptCompletion({ - type: "break", - target: self.leapManager.getBreakLoc(stmt.label) - }); + if (folded) { + set.add(folded); + } + } - break; + break; - case "ContinueStatement": - self.emitAbruptCompletion({ - type: "continue", - target: self.leapManager.getContinueLoc(stmt.label) - }); + case 'characterClassRange': + var min = item.min.codePoint; + var max = item.max.codePoint; + set.addRange(min, max); - break; + if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) { + set.iuAddRange(min, max); + } - case "SwitchStatement": - // Always save the discriminant into a temporary variable in case the - // test expressions overwrite values like context.sent. - var disc = self.emitAssign(self.makeTempVar(), self.explodeExpression(path.get("discriminant"))); + break; - after = loc(); - var defaultLoc = loc(); - var condition = defaultLoc; - var caseLocs = []; + case 'characterClassEscape': + set.add(getCharacterClassEscapeSet(item.value, config.unicode, config.ignoreCase)); + break; - // If there are no cases, .cases might be undefined. - var cases = stmt.cases || []; + case 'unicodePropertyEscape': + set.add(getUnicodePropertyEscapeSet(item.value, item.negative)); + break; + // The `default` clause is only here as a safeguard; it should never be + // reached. Code coverage tools should ignore it. - for (var i = cases.length - 1; i >= 0; --i) { - var c = cases[i]; - t.assertSwitchCase(c); + /* istanbul ignore next */ - if (c.test) { - condition = t.conditionalExpression(t.binaryExpression("===", disc, c.test), caseLocs[i] = loc(), condition); - } else { - caseLocs[i] = defaultLoc; - } + default: + throw new Error("Unknown term type: ".concat(item.type)); } - - var discriminant = path.get("discriminant"); - util.replaceWithOrRemove(discriminant, condition); - self.jump(self.explodeExpression(discriminant)); - - self.leapManager.withEntry(new leap.SwitchEntry(after), function () { - path.get("cases").forEach(function (casePath) { - var i = casePath.key; - self.mark(caseLocs[i]); - - casePath.get("consequent").forEach(function (path) { - self.explodeStatement(path); - }); - }); - }); - - self.mark(after); - if (defaultLoc.value === -1) { - self.mark(defaultLoc); - _assert2.default.strictEqual(after.value, defaultLoc.value); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; } + } + } - break; + if (characterClassItem.negative) { + set = (config.unicode ? UNICODE_SET : BMP_SET).clone().remove(set); + } - case "IfStatement": - var elseLoc = stmt.alternate && loc(); - after = loc(); + update(characterClassItem, set.toString(regenerateOptions)); + return characterClassItem; +}; - self.jumpIfNot(self.explodeExpression(path.get("test")), elseLoc || after); +var updateNamedReference = function updateNamedReference(item, index) { + delete item.name; + item.matchIndex = index; +}; - self.explodeStatement(path.get("consequent")); +var assertNoUnmatchedReferences = function assertNoUnmatchedReferences(groups) { + var unmatchedReferencesNames = Object.keys(groups.unmatchedReferences); - if (elseLoc) { - self.jump(after); - self.mark(elseLoc); - self.explodeStatement(path.get("alternate")); - } + if (unmatchedReferencesNames.length > 0) { + throw new Error("Unknown group names: ".concat(unmatchedReferencesNames)); + } +}; - self.mark(after); +var processTerm = function processTerm(item, regenerateOptions, groups) { + switch (item.type) { + case 'dot': + if (config.unicode) { + update(item, getUnicodeDotSet(config.dotAll).toString(regenerateOptions)); + } else if (config.dotAll) { + // TODO: consider changing this at the regenerate level. + update(item, '[\\s\\S]'); + } break; - case "ReturnStatement": - self.emitAbruptCompletion({ - type: "return", - value: self.explodeExpression(path.get("argument")) - }); - + case 'characterClass': + item = processCharacterClass(item, regenerateOptions); break; - case "WithStatement": - throw new Error("WithStatement not supported in generator functions."); - - case "TryStatement": - after = loc(); - - var handler = stmt.handler; + case 'unicodePropertyEscape': + update(item, getUnicodePropertyEscapeSet(item.value, item.negative).toString(regenerateOptions)); + break; - var catchLoc = handler && loc(); - var catchEntry = catchLoc && new leap.CatchEntry(catchLoc, handler.param); + case 'characterClassEscape': + update(item, getCharacterClassEscapeSet(item.value, config.unicode, config.ignoreCase).toString(regenerateOptions)); + break; - var finallyLoc = stmt.finalizer && loc(); - var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); + case 'group': + if (item.behavior == 'normal') { + groups.lastIndex++; + } - var tryEntry = new leap.TryEntry(self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry); + if (item.name) { + var name = item.name.value; - self.tryEntries.push(tryEntry); - self.updateContextPrevLoc(tryEntry.firstLoc); + if (groups.names[name]) { + throw new Error("Multiple groups with the same name (".concat(name, ") are not allowed.")); + } - self.leapManager.withEntry(tryEntry, function () { - self.explodeStatement(path.get("block")); + var index = groups.lastIndex; + delete item.name; + groups.names[name] = index; - if (catchLoc) { - if (finallyLoc) { - // If we have both a catch block and a finally block, then - // because we emit the catch block first, we need to jump over - // it to the finally block. - self.jump(finallyLoc); - } else { - // If there is no finally block, then we need to jump over the - // catch block to the fall-through location. - self.jump(after); - } + if (groups.onNamedGroup) { + groups.onNamedGroup.call(null, name, index); + } - self.updateContextPrevLoc(self.mark(catchLoc)); + if (groups.unmatchedReferences[name]) { + groups.unmatchedReferences[name].forEach(function (reference) { + updateNamedReference(reference, index); + }); + delete groups.unmatchedReferences[name]; + } + } - var bodyPath = path.get("handler.body"); - var safeParam = self.makeTempVar(); - self.clearPendingException(tryEntry.firstLoc, safeParam); + /* falls through */ - bodyPath.traverse(catchParamVisitor, { - safeParam: safeParam, - catchParamName: handler.param.name - }); + case 'alternative': + case 'disjunction': + case 'quantifier': + item.body = item.body.map(function (term) { + return processTerm(term, regenerateOptions, groups); + }); + break; - self.leapManager.withEntry(catchEntry, function () { - self.explodeStatement(bodyPath); - }); + case 'value': + var codePoint = item.codePoint; + var set = regenerate(codePoint); + + if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) { + var folded = caseFold(codePoint); + + if (folded) { + set.add(folded); } + } - if (finallyLoc) { - self.updateContextPrevLoc(self.mark(finallyLoc)); + update(item, set.toString(regenerateOptions)); + break; - self.leapManager.withEntry(finallyEntry, function () { - self.explodeStatement(path.get("finalizer")); - }); + case 'reference': + if (item.name) { + var _name = item.name.value; + var _index = groups.names[_name]; - self.emit(t.returnStatement(t.callExpression(self.contextProperty("finish"), [finallyEntry.firstLoc]))); + if (_index) { + updateNamedReference(item, _index); + break; } - }); - self.mark(after); + if (!groups.unmatchedReferences[_name]) { + groups.unmatchedReferences[_name] = []; + } // Keep track of references used before the corresponding group. - break; - case "ThrowStatement": - self.emit(t.throwStatement(self.explodeExpression(path.get("argument")))); + groups.unmatchedReferences[_name].push(item); + } + + break; + case 'anchor': + case 'empty': + case 'group': + // Nothing to do here. break; + // The `default` clause is only here as a safeguard; it should never be + // reached. Code coverage tools should ignore it. + + /* istanbul ignore next */ default: - throw new Error("unknown Statement of type " + (0, _stringify2.default)(stmt.type)); + throw new Error("Unknown term type: ".concat(item.type)); } -}; -var catchParamVisitor = { - Identifier: function Identifier(path, state) { - if (path.node.name === state.catchParamName && util.isReference(path)) { - util.replaceWithOrRemove(path, state.safeParam); - } - }, + return item; +}; - Scope: function Scope(path, state) { - if (path.scope.hasOwnBinding(state.catchParamName)) { - // Don't descend into nested scopes that shadow the catch - // parameter with their own declarations. - path.skip(); - } - } +var config = { + 'ignoreCase': false, + 'unicode': false, + 'dotAll': false, + 'useUnicodeFlag': false }; -Ep.emitAbruptCompletion = function (record) { - if (!isValidCompletion(record)) { - _assert2.default.ok(false, "invalid completion record: " + (0, _stringify2.default)(record)); - } +var rewritePattern = function rewritePattern(pattern, flags, options) { + var regjsparserFeatures = { + 'unicodePropertyEscape': options && options.unicodePropertyEscape, + 'namedGroups': options && options.namedGroup, + 'lookbehind': options && options.lookbehind + }; + config.ignoreCase = flags && flags.includes('i'); + config.unicode = flags && flags.includes('u'); + var supportDotAllFlag = options && options.dotAllFlag; + config.dotAll = supportDotAllFlag && flags && flags.includes('s'); + config.useUnicodeFlag = options && options.useUnicodeFlag; + var regenerateOptions = { + 'hasUnicodeFlag': config.useUnicodeFlag, + 'bmpOnly': !config.unicode + }; + var groups = { + 'onNamedGroup': options && options.onNamedGroup, + 'lastIndex': 0, + 'names': Object.create(null), + // { [name]: index } + 'unmatchedReferences': Object.create(null) // { [name]: Array } - _assert2.default.notStrictEqual(record.type, "normal", "normal completions are not abrupt"); + }; + var tree = parse(pattern, flags, regjsparserFeatures); // Note: `processTerm` mutates `tree` and `groups`. - var abruptArgs = [t.stringLiteral(record.type)]; + processTerm(tree, regenerateOptions, groups); + assertNoUnmatchedReferences(groups); + return generate(tree); +}; - if (record.type === "break" || record.type === "continue") { - t.assertLiteral(record.target); - abruptArgs[1] = record.target; - } else if (record.type === "return" || record.type === "throw") { - if (record.value) { - t.assertExpression(record.value); - abruptArgs[1] = record.value; - } - } +module.exports = rewritePattern; - this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"), abruptArgs))); -}; +},{"./data/character-class-escape-sets.js":1064,"./data/iu-mappings.js":1065,"regenerate":1055,"regjsgen":1067,"regjsparser":1068,"unicode-match-property-ecmascript":1085,"unicode-match-property-value-ecmascript":1087}],1067:[function(require,module,exports){ +(function (global){ +"use strict"; -function isValidCompletion(record) { - var type = record.type; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - if (type === "normal") { - return !hasOwn.call(record, "target"); - } +/*! + * regjsgen 0.5.1 + * Copyright 2014-2019 Benjamin Tan + * Available under MIT license + */ +; +(function () { + 'use strict'; // Used to determine if values are of the language type `Object`. - if (type === "break" || type === "continue") { - return !hasOwn.call(record, "value") && t.isLiteral(record.target); - } + var objectTypes = { + 'function': true, + 'object': true + }; // Used as a reference to the global object. - if (type === "return" || type === "throw") { - return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); - } + var root = objectTypes[typeof window === "undefined" ? "undefined" : _typeof(window)] && window || this; // Detect free variable `exports`. - return false; -} + var freeExports = objectTypes[typeof exports === "undefined" ? "undefined" : _typeof(exports)] && exports && !exports.nodeType && exports; // Detect free variable `module`. -// Not all offsets into emitter.listing are potential jump targets. For -// example, execution typically falls into the beginning of a try block -// without jumping directly there. This method returns the current offset -// without marking it, so that a switch case will not necessarily be -// generated for this offset (I say "not necessarily" because the same -// location might end up being marked in the process of emitting other -// statements). There's no logical harm in marking such locations as jump -// targets, but minimizing the number of switch cases keeps the generated -// code shorter. -Ep.getUnmarkedCurrentLoc = function () { - return t.numericLiteral(this.listing.length); -}; + var hasFreeModule = objectTypes[typeof module === "undefined" ? "undefined" : _typeof(module)] && module && !module.nodeType; // Detect free variable `global` from Node.js or Browserified code and use it as `root`. -// The context.prev property takes the value of context.next whenever we -// evaluate the switch statement discriminant, which is generally good -// enough for tracking the last location we jumped to, but sometimes -// context.prev needs to be more precise, such as when we fall -// successfully out of a try block and into a finally block without -// jumping. This method exists to update context.prev to the freshest -// available location. If we were implementing a full interpreter, we -// would know the location of the current instruction with complete -// precision at all times, but we don't have that luxury here, as it would -// be costly and verbose to set context.prev before every statement. -Ep.updateContextPrevLoc = function (loc) { - if (loc) { - t.assertLiteral(loc); + var freeGlobal = freeExports && hasFreeModule && (typeof global === "undefined" ? "undefined" : _typeof(global)) == 'object' && global; - if (loc.value === -1) { - // If an uninitialized location literal was passed in, set its value - // to the current this.listing.length. - loc.value = this.listing.length; - } else { - // Otherwise assert that the location matches the current offset. - _assert2.default.strictEqual(loc.value, this.listing.length); - } - } else { - loc = this.getUnmarkedCurrentLoc(); - } + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { + root = freeGlobal; + } // Used to check objects for own properties. - // Make sure context.prev is up to date in case we fell into this try - // statement without jumping to it. TODO Consider avoiding this - // assignment when we know control must have jumped here. - this.emitAssign(this.contextProperty("prev"), loc); -}; -Ep.explodeExpression = function (path, ignoreResult) { - var expr = path.node; - if (expr) { - t.assertExpression(expr); - } else { - return expr; - } + var hasOwnProperty = Object.prototype.hasOwnProperty; + /*--------------------------------------------------------------------------*/ + // Generates a string based on the given code point. + // Based on https://mths.be/fromcodepoint by @mathias. - var self = this; - var result = void 0; // Used optionally by several cases below. - var after = void 0; + function fromCodePoint() { + var codePoint = Number(arguments[0]); - function finish(expr) { - t.assertExpression(expr); - if (ignoreResult) { - self.emit(expr); + if (!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` + codePoint < 0 || // not a valid Unicode code point + codePoint > 0x10FFFF || // not a valid Unicode code point + Math.floor(codePoint) != codePoint // not an integer + ) { + throw RangeError('Invalid code point: ' + codePoint); + } + + if (codePoint <= 0xFFFF) { + // BMP code point + return String.fromCharCode(codePoint); } else { - return expr; + // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + var highSurrogate = (codePoint >> 10) + 0xD800; + var lowSurrogate = codePoint % 0x400 + 0xDC00; + return String.fromCharCode(highSurrogate, lowSurrogate); } } + /*--------------------------------------------------------------------------*/ + // Ensures that nodes have the correct types. - // If the expression does not contain a leap, then we either emit the - // expression as a standalone statement or return it whole. - if (!meta.containsLeap(expr)) { - return finish(expr); - } - // If any child contains a leap (such as a yield or labeled continue or - // break statement), then any sibling subexpressions will almost - // certainly have to be exploded in order to maintain the order of their - // side effects relative to the leaping child(ren). - var hasLeapingChildren = meta.containsLeap.onlyChildren(expr); + var assertTypeRegexMap = {}; - // In order to save the rest of explodeExpression from a combinatorial - // trainwreck of special cases, explodeViaTempVar is responsible for - // deciding when a subexpression needs to be "exploded," which is my - // very technical term for emitting the subexpression as an assignment - // to a temporary variable and the substituting the temporary variable - // for the original subexpression. Think of exploded view diagrams, not - // Michael Bay movies. The point of exploding subexpressions is to - // control the precise order in which the generated code realizes the - // side effects of those subexpressions. - function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { - _assert2.default.ok(!ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?"); + function assertType(type, expected) { + if (expected.indexOf('|') == -1) { + if (type == expected) { + return; + } - var result = self.explodeExpression(childPath, ignoreChildResult); + throw Error('Invalid node type: ' + type + '; expected type: ' + expected); + } - if (ignoreChildResult) { - // Side effects already emitted above. + expected = hasOwnProperty.call(assertTypeRegexMap, expected) ? assertTypeRegexMap[expected] : assertTypeRegexMap[expected] = RegExp('^(?:' + expected + ')$'); - } else if (tempVar || hasLeapingChildren && !t.isLiteral(result)) { - // If tempVar was provided, then the result will always be assigned - // to it, even if the result does not otherwise need to be assigned - // to a temporary variable. When no tempVar is provided, we have - // the flexibility to decide whether a temporary variable is really - // necessary. Unfortunately, in general, a temporary variable is - // required whenever any child contains a yield expression, since it - // is difficult to prove (at all, let alone efficiently) whether - // this result would evaluate to the same value before and after the - // yield (see #206). One narrow case where we can prove it doesn't - // matter (and thus we do not need a temporary variable) is when the - // result in question is a Literal value. - result = self.emitAssign(tempVar || self.makeTempVar(), result); + if (expected.test(type)) { + return; } - return result; - } - - // If ignoreResult is true, then we must take full responsibility for - // emitting the expression with all its side effects, and we should not - // return a result. - switch (expr.type) { - case "MemberExpression": - return finish(t.memberExpression(self.explodeExpression(path.get("object")), expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property, expr.computed)); + throw Error('Invalid node type: ' + type + '; expected types: ' + expected); + } + /*--------------------------------------------------------------------------*/ + // Generates a regular expression string based on an AST. - case "CallExpression": - var calleePath = path.get("callee"); - var argsPath = path.get("arguments"); - var newCallee = void 0; - var newArgs = []; + function generate(node) { + var type = node.type; - var hasLeapingArgs = false; - argsPath.forEach(function (argPath) { - hasLeapingArgs = hasLeapingArgs || meta.containsLeap(argPath.node); - }); + if (hasOwnProperty.call(generators, type)) { + return generators[type](node); + } - if (t.isMemberExpression(calleePath.node)) { - if (hasLeapingArgs) { - // If the arguments of the CallExpression contained any yield - // expressions, then we need to be sure to evaluate the callee - // before evaluating the arguments, but if the callee was a member - // expression, then we must be careful that the object of the - // member expression still gets bound to `this` for the call. + throw Error('Invalid node type: ' + type); + } + /*--------------------------------------------------------------------------*/ - var newObject = explodeViaTempVar( - // Assign the exploded callee.object expression to a temporary - // variable so that we can use it twice without reevaluating it. - self.makeTempVar(), calleePath.get("object")); - var newProperty = calleePath.node.computed ? explodeViaTempVar(null, calleePath.get("property")) : calleePath.node.property; + function generateAlternative(node) { + assertType(node.type, 'alternative'); + var terms = node.body, + i = -1, + length = terms.length, + result = ''; - newArgs.unshift(newObject); + while (++i < length) { + result += generateTerm(terms[i]); + } - newCallee = t.memberExpression(t.memberExpression(newObject, newProperty, calleePath.node.computed), t.identifier("call"), false); - } else { - newCallee = self.explodeExpression(calleePath); - } - } else { - newCallee = explodeViaTempVar(null, calleePath); + return result; + } - if (t.isMemberExpression(newCallee)) { - // If the callee was not previously a MemberExpression, then the - // CallExpression was "unqualified," meaning its `this` object - // should be the global object. If the exploded expression has - // become a MemberExpression (e.g. a context property, probably a - // temporary variable), then we need to force it to be unqualified - // by using the (0, object.property)(...) trick; otherwise, it - // will receive the object of the MemberExpression as its `this` - // object. - newCallee = t.sequenceExpression([t.numericLiteral(0), newCallee]); - } - } + function generateAnchor(node) { + assertType(node.type, 'anchor'); - argsPath.forEach(function (argPath) { - newArgs.push(explodeViaTempVar(null, argPath)); - }); + switch (node.kind) { + case 'start': + return '^'; - return finish(t.callExpression(newCallee, newArgs)); + case 'end': + return '$'; - case "NewExpression": - return finish(t.newExpression(explodeViaTempVar(null, path.get("callee")), path.get("arguments").map(function (argPath) { - return explodeViaTempVar(null, argPath); - }))); + case 'boundary': + return '\\b'; - case "ObjectExpression": - return finish(t.objectExpression(path.get("properties").map(function (propPath) { - if (propPath.isObjectProperty()) { - return t.objectProperty(propPath.node.key, explodeViaTempVar(null, propPath.get("value")), propPath.node.computed); - } else { - return propPath.node; - } - }))); + case 'not-boundary': + return '\\B'; - case "ArrayExpression": - return finish(t.arrayExpression(path.get("elements").map(function (elemPath) { - return explodeViaTempVar(null, elemPath); - }))); + default: + throw Error('Invalid assertion'); + } + } - case "SequenceExpression": - var lastIndex = expr.expressions.length - 1; + function generateAtom(node) { + assertType(node.type, 'anchor|characterClass|characterClassEscape|dot|group|reference|value'); + return generate(node); + } - path.get("expressions").forEach(function (exprPath) { - if (exprPath.key === lastIndex) { - result = self.explodeExpression(exprPath, ignoreResult); - } else { - self.explodeExpression(exprPath, true); - } - }); + function generateCharacterClass(node) { + assertType(node.type, 'characterClass'); + var classRanges = node.body, + i = -1, + length = classRanges.length, + result = ''; - return result; + if (node.negative) { + result += '^'; + } - case "LogicalExpression": - after = loc(); + while (++i < length) { + result += generateClassAtom(classRanges[i]); + } - if (!ignoreResult) { - result = self.makeTempVar(); - } + return '[' + result + ']'; + } - var left = explodeViaTempVar(result, path.get("left")); + function generateCharacterClassEscape(node) { + assertType(node.type, 'characterClassEscape'); + return '\\' + node.value; + } - if (expr.operator === "&&") { - self.jumpIfNot(left, after); - } else { - _assert2.default.strictEqual(expr.operator, "||"); - self.jumpIf(left, after); - } + function generateUnicodePropertyEscape(node) { + assertType(node.type, 'unicodePropertyEscape'); + return '\\' + (node.negative ? 'P' : 'p') + '{' + node.value + '}'; + } - explodeViaTempVar(result, path.get("right"), ignoreResult); + function generateCharacterClassRange(node) { + assertType(node.type, 'characterClassRange'); + var min = node.min, + max = node.max; - self.mark(after); + if (min.type == 'characterClassRange' || max.type == 'characterClassRange') { + throw Error('Invalid character class range'); + } - return result; + return generateClassAtom(min) + '-' + generateClassAtom(max); + } - case "ConditionalExpression": - var elseLoc = loc(); - after = loc(); - var test = self.explodeExpression(path.get("test")); + function generateClassAtom(node) { + assertType(node.type, 'anchor|characterClassEscape|characterClassRange|dot|value'); + return generate(node); + } - self.jumpIfNot(test, elseLoc); + function generateDisjunction(node) { + assertType(node.type, 'disjunction'); + var body = node.body, + i = -1, + length = body.length, + result = ''; - if (!ignoreResult) { - result = self.makeTempVar(); + while (++i < length) { + if (i != 0) { + result += '|'; } - explodeViaTempVar(result, path.get("consequent"), ignoreResult); - self.jump(after); - - self.mark(elseLoc); - explodeViaTempVar(result, path.get("alternate"), ignoreResult); + result += generate(body[i]); + } - self.mark(after); + return result; + } - return result; + function generateDot(node) { + assertType(node.type, 'dot'); + return '.'; + } - case "UnaryExpression": - return finish(t.unaryExpression(expr.operator, - // Can't (and don't need to) break up the syntax of the argument. - // Think about delete a[b]. - self.explodeExpression(path.get("argument")), !!expr.prefix)); + function generateGroup(node) { + assertType(node.type, 'group'); + var result = ''; - case "BinaryExpression": - return finish(t.binaryExpression(expr.operator, explodeViaTempVar(null, path.get("left")), explodeViaTempVar(null, path.get("right")))); + switch (node.behavior) { + case 'normal': + if (node.name) { + result += '?<' + generateIdentifier(node.name) + '>'; + } - case "AssignmentExpression": - return finish(t.assignmentExpression(expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")))); + break; - case "UpdateExpression": - return finish(t.updateExpression(expr.operator, self.explodeExpression(path.get("argument")), expr.prefix)); + case 'ignore': + result += '?:'; + break; - case "YieldExpression": - after = loc(); - var arg = expr.argument && self.explodeExpression(path.get("argument")); + case 'lookahead': + result += '?='; + break; - if (arg && expr.delegate) { - var _result = self.makeTempVar(); + case 'negativeLookahead': + result += '?!'; + break; - self.emit(t.returnStatement(t.callExpression(self.contextProperty("delegateYield"), [arg, t.stringLiteral(_result.property.name), after]))); + case 'lookbehind': + result += '?<='; + break; - self.mark(after); + case 'negativeLookbehind': + result += '?'; + } -var hasOwn = Object.prototype.hasOwnProperty; + throw new Error('Unknown reference type'); + } -// The hoist function takes a FunctionExpression or FunctionDeclaration -// and replaces any Declaration nodes in its body with assignments, then -// returns a VariableDeclaration containing just the names of the removed -// declarations. -exports.hoist = function (funPath) { - t.assertFunction(funPath.node); + function generateTerm(node) { + assertType(node.type, 'anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|unicodePropertyEscape|value|dot'); + return generate(node); + } - var vars = {}; + function generateValue(node) { + assertType(node.type, 'value'); + var kind = node.kind, + codePoint = node.codePoint; - function varDeclToExpr(vdec, includeIdentifiers) { - t.assertVariableDeclaration(vdec); - // TODO assert.equal(vdec.kind, "var"); - var exprs = []; + if (typeof codePoint != 'number') { + throw new Error('Invalid code point: ' + codePoint); + } - vdec.declarations.forEach(function (dec) { - // Note: We duplicate 'dec.id' here to ensure that the variable declaration IDs don't - // have the same 'loc' value, since that can make sourcemaps and retainLines behave poorly. - vars[dec.id.name] = t.identifier(dec.id.name); + switch (kind) { + case 'controlLetter': + return '\\c' + fromCodePoint(codePoint + 64); - if (dec.init) { - exprs.push(t.assignmentExpression("=", dec.id, dec.init)); - } else if (includeIdentifiers) { - exprs.push(dec.id); - } - }); + case 'hexadecimalEscape': + return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2); - if (exprs.length === 0) return null; + case 'identifier': + return '\\' + fromCodePoint(codePoint); - if (exprs.length === 1) return exprs[0]; + case 'null': + return '\\' + codePoint; - return t.sequenceExpression(exprs); - } + case 'octal': + return '\\' + codePoint.toString(8); - funPath.get("body").traverse({ - VariableDeclaration: { - exit: function exit(path) { - var expr = varDeclToExpr(path.node, false); - if (expr === null) { - path.remove(); - } else { - // We don't need to traverse this expression any further because - // there can't be any new declarations inside an expression. - util.replaceWithOrRemove(path, t.expressionStatement(expr)); - } + case 'singleEscape': + switch (codePoint) { + case 0x0008: + return '\\b'; - // Since the original node has been either removed or replaced, - // avoid traversing it any further. - path.skip(); - } - }, + case 0x0009: + return '\\t'; - ForStatement: function ForStatement(path) { - var init = path.node.init; - if (t.isVariableDeclaration(init)) { - util.replaceWithOrRemove(path.get("init"), varDeclToExpr(init, false)); - } - }, + case 0x000A: + return '\\n'; - ForXStatement: function ForXStatement(path) { - var left = path.get("left"); - if (left.isVariableDeclaration()) { - util.replaceWithOrRemove(left, varDeclToExpr(left.node, true)); - } - }, + case 0x000B: + return '\\v'; - FunctionDeclaration: function FunctionDeclaration(path) { - var node = path.node; - vars[node.id.name] = node.id; + case 0x000C: + return '\\f'; - var assignment = t.expressionStatement(t.assignmentExpression("=", node.id, t.functionExpression(node.id, node.params, node.body, node.generator, node.expression))); + case 0x000D: + return '\\r'; - if (path.parentPath.isBlockStatement()) { - // Insert the assignment form before the first statement in the - // enclosing block. - path.parentPath.unshiftContainer("body", assignment); + default: + throw Error('Invalid code point: ' + codePoint); + } - // Remove the function declaration now that we've inserted the - // equivalent assignment form at the beginning of the block. - path.remove(); - } else { - // If the parent node is not a block statement, then we can just - // replace the declaration with the equivalent assignment form - // without worrying about hoisting it. - util.replaceWithOrRemove(path, assignment); - } + case 'symbol': + return fromCodePoint(codePoint); - // Don't hoist variables out of inner functions. - path.skip(); - }, + case 'unicodeEscape': + return "\\u" + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4); - FunctionExpression: function FunctionExpression(path) { - // Don't descend into nested function expressions. - path.skip(); - } - }); + case 'unicodeCodePointEscape': + return "\\u{" + codePoint.toString(16).toUpperCase() + '}'; - var paramNames = {}; - funPath.get("params").forEach(function (paramPath) { - var param = paramPath.node; - if (t.isIdentifier(param)) { - paramNames[param.name] = param; - } else { - // Variables declared by destructuring parameter patterns will be - // harmlessly re-declared. + default: + throw Error('Unsupported node kind: ' + kind); } - }); + } + /*--------------------------------------------------------------------------*/ + // Used to generate strings for each node type. + + + var generators = { + 'alternative': generateAlternative, + 'anchor': generateAnchor, + 'characterClass': generateCharacterClass, + 'characterClassEscape': generateCharacterClassEscape, + 'characterClassRange': generateCharacterClassRange, + 'unicodePropertyEscape': generateUnicodePropertyEscape, + 'disjunction': generateDisjunction, + 'dot': generateDot, + 'group': generateGroup, + 'quantifier': generateQuantifier, + 'reference': generateReference, + 'value': generateValue + }; + /*--------------------------------------------------------------------------*/ + // Export regjsgen. - var declarations = []; + var regjsgen = { + 'generate': generate + }; // Some AMD build optimizers, like r.js, check for condition patterns like the following: - (0, _keys2.default)(vars).forEach(function (name) { - if (!hasOwn.call(paramNames, name)) { - declarations.push(t.variableDeclarator(vars[name], null)); + if (typeof define == 'function' && _typeof(define.amd) == 'object' && define.amd) { + // Define as an anonymous module so it can be aliased through path mapping. + define(function () { + return regjsgen; + }); + root.regjsgen = regjsgen; + } // Check for `exports` after `define` in case a build optimizer adds an `exports` object. + else if (freeExports && hasFreeModule) { + // Export for CommonJS support. + freeExports.generate = generate; + } else { + // Export to the global object. + root.regjsgen = regjsgen; } - }); - - if (declarations.length === 0) { - return null; // Be sure to handle this case! - } +}).call(void 0); - return t.variableDeclaration("var", declarations); -}; -},{"./util":533,"babel-runtime/core-js/object/keys":102,"babel-types":151}],529:[function(require,module,exports){ +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],1068:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +// regjsparser +// +// ================================================================== +// +// See ECMA-262 Standard: 15.10.1 +// +// NOTE: The ECMA-262 standard uses the term "Assertion" for /^/. Here the +// term "Anchor" is used. +// +// Pattern :: +// Disjunction +// +// Disjunction :: +// Alternative +// Alternative | Disjunction +// +// Alternative :: +// [empty] +// Alternative Term +// +// Term :: +// Anchor +// Atom +// Atom Quantifier +// +// Anchor :: +// ^ +// $ +// \ b +// \ B +// ( ? = Disjunction ) +// ( ? ! Disjunction ) +// ( ? < = Disjunction ) +// ( ? < ! Disjunction ) +// +// Quantifier :: +// QuantifierPrefix +// QuantifierPrefix ? +// +// QuantifierPrefix :: +// * +// + +// ? +// { DecimalDigits } +// { DecimalDigits , } +// { DecimalDigits , DecimalDigits } +// +// Atom :: +// PatternCharacter +// . +// \ AtomEscape +// CharacterClass +// ( GroupSpecifier Disjunction ) +// ( ? : Disjunction ) +// +// PatternCharacter :: +// SourceCharacter but not any of: ^ $ \ . * + ? ( ) [ ] { } | +// +// AtomEscape :: +// DecimalEscape +// CharacterEscape +// CharacterClassEscape +// k GroupName +// +// CharacterEscape[U] :: +// ControlEscape +// c ControlLetter +// HexEscapeSequence +// RegExpUnicodeEscapeSequence[?U] (ES6) +// IdentityEscape[?U] +// +// ControlEscape :: +// one of f n r t v +// ControlLetter :: +// one of +// a b c d e f g h i j k l m n o p q r s t u v w x y z +// A B C D E F G H I J K L M N O P Q R S T U V W X Y Z +// +// IdentityEscape :: +// SourceCharacter but not c +// +// DecimalEscape :: +// DecimalIntegerLiteral [lookahead ∉ DecimalDigit] +// +// CharacterClassEscape :: +// one of d D s S w W +// +// CharacterClass :: +// [ [lookahead ∉ {^}] ClassRanges ] +// [ ^ ClassRanges ] +// +// ClassRanges :: +// [empty] +// NonemptyClassRanges +// +// NonemptyClassRanges :: +// ClassAtom +// ClassAtom NonemptyClassRangesNoDash +// ClassAtom - ClassAtom ClassRanges +// +// NonemptyClassRangesNoDash :: +// ClassAtom +// ClassAtomNoDash NonemptyClassRangesNoDash +// ClassAtomNoDash - ClassAtom ClassRanges +// +// ClassAtom :: +// - +// ClassAtomNoDash +// +// ClassAtomNoDash :: +// SourceCharacter but not one of \ or ] or - +// \ ClassEscape +// +// ClassEscape :: +// DecimalEscape +// b +// CharacterEscape +// CharacterClassEscape +// +// GroupSpecifier :: +// [empty] +// ? GroupName +// +// GroupName :: +// < RegExpIdentifierName > +// +// RegExpIdentifierName :: +// RegExpIdentifierStart +// RegExpIdentifierName RegExpIdentifierContinue +// +// RegExpIdentifierStart :: +// UnicodeIDStart +// $ +// _ +// \ RegExpUnicodeEscapeSequence +// +// RegExpIdentifierContinue :: +// UnicodeIDContinue +// $ +// _ +// \ RegExpUnicodeEscapeSequence +// +// +(function () { + var fromCodePoint = String.fromCodePoint || function () { + // Implementation taken from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint + var stringFromCharCode = String.fromCharCode; + var floor = Math.floor; + return function fromCodePoint() { + var MAX_SIZE = 0x4000; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; -exports.default = function (context) { - var plugin = { - visitor: require("./visit").visitor - }; + if (!length) { + return ''; + } - // Some presets manually call child presets, but fail to pass along the - // context object. Out of an abundance of caution, we verify that it - // exists first to avoid causing unnecessary breaking changes. - var version = context && context.version; + var result = ''; - // The "name" property is not allowed in older versions of Babel (6.x) - // and will cause the plugin validator to throw an exception. - if (version && parseInt(version, 10) >= 7) { - plugin.name = "regenerator-transform"; - } + while (++index < length) { + var codePoint = Number(arguments[index]); - return plugin; -}; -},{"./visit":534}],530:[function(require,module,exports){ -"use strict"; + if (!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` + codePoint < 0 || // not a valid Unicode code point + codePoint > 0x10FFFF || // not a valid Unicode code point + floor(codePoint) != codePoint // not an integer + ) { + throw RangeError('Invalid code point: ' + codePoint); + } -var _assert = require("assert"); + if (codePoint <= 0xFFFF) { + // BMP code point + codeUnits.push(codePoint); + } else { + // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + highSurrogate = (codePoint >> 10) + 0xD800; + lowSurrogate = codePoint % 0x400 + 0xDC00; + codeUnits.push(highSurrogate, lowSurrogate); + } -var _assert2 = _interopRequireDefault(_assert); + if (index + 1 == length || codeUnits.length > MAX_SIZE) { + result += stringFromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } -var _babelTypes = require("babel-types"); + return result; + }; + }(); -var t = _interopRequireWildcard(_babelTypes); + function parse(str, flags, features) { + if (!features) { + features = {}; + } -var _util = require("util"); + function addRaw(node) { + node.raw = str.substring(node.range[0], node.range[1]); + return node; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + function updateRawStart(node, start) { + node.range[0] = start; + return addRaw(node); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function createAnchor(kind, rawLength) { + return addRaw({ + type: 'anchor', + kind: kind, + range: [pos - rawLength, pos] + }); + } -function Entry() { - _assert2.default.ok(this instanceof Entry); -} /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + function createValue(kind, codePoint, from, to) { + return addRaw({ + type: 'value', + kind: kind, + codePoint: codePoint, + range: [from, to] + }); + } -function FunctionEntry(returnLoc) { - Entry.call(this); - t.assertLiteral(returnLoc); - this.returnLoc = returnLoc; -} + function createEscaped(kind, codePoint, value, fromOffset) { + fromOffset = fromOffset || 0; + return createValue(kind, codePoint, pos - (value.length + fromOffset), pos); + } -(0, _util.inherits)(FunctionEntry, Entry); -exports.FunctionEntry = FunctionEntry; + function createCharacter(matches) { + var _char = matches[0]; -function LoopEntry(breakLoc, continueLoc, label) { - Entry.call(this); + var first = _char.charCodeAt(0); - t.assertLiteral(breakLoc); - t.assertLiteral(continueLoc); + if (hasUnicodeFlag) { + var second; - if (label) { - t.assertIdentifier(label); - } else { - label = null; - } + if (_char.length === 1 && first >= 0xD800 && first <= 0xDBFF) { + second = lookahead().charCodeAt(0); - this.breakLoc = breakLoc; - this.continueLoc = continueLoc; - this.label = label; -} + if (second >= 0xDC00 && second <= 0xDFFF) { + // Unicode surrogate pair + pos++; + return createValue('symbol', (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000, pos - 2, pos); + } + } + } -(0, _util.inherits)(LoopEntry, Entry); -exports.LoopEntry = LoopEntry; + return createValue('symbol', first, pos - 1, pos); + } -function SwitchEntry(breakLoc) { - Entry.call(this); - t.assertLiteral(breakLoc); - this.breakLoc = breakLoc; -} + function createDisjunction(alternatives, from, to) { + return addRaw({ + type: 'disjunction', + body: alternatives, + range: [from, to] + }); + } -(0, _util.inherits)(SwitchEntry, Entry); -exports.SwitchEntry = SwitchEntry; + function createDot() { + return addRaw({ + type: 'dot', + range: [pos - 1, pos] + }); + } -function TryEntry(firstLoc, catchEntry, finallyEntry) { - Entry.call(this); + function createCharacterClassEscape(value) { + return addRaw({ + type: 'characterClassEscape', + value: value, + range: [pos - 2, pos] + }); + } - t.assertLiteral(firstLoc); + function createReference(matchIndex) { + return addRaw({ + type: 'reference', + matchIndex: parseInt(matchIndex, 10), + range: [pos - 1 - matchIndex.length, pos] + }); + } - if (catchEntry) { - _assert2.default.ok(catchEntry instanceof CatchEntry); - } else { - catchEntry = null; - } + function createNamedReference(name) { + return addRaw({ + type: 'reference', + name: name, + range: [name.range[0] - 3, pos] + }); + } - if (finallyEntry) { - _assert2.default.ok(finallyEntry instanceof FinallyEntry); - } else { - finallyEntry = null; - } + function createGroup(behavior, disjunction, from, to) { + return addRaw({ + type: 'group', + behavior: behavior, + body: disjunction, + range: [from, to] + }); + } - // Have to have one or the other (or both). - _assert2.default.ok(catchEntry || finallyEntry); + function createQuantifier(min, max, from, to) { + if (to == null) { + from = pos - 1; + to = pos; + } - this.firstLoc = firstLoc; - this.catchEntry = catchEntry; - this.finallyEntry = finallyEntry; -} + return addRaw({ + type: 'quantifier', + min: min, + max: max, + greedy: true, + body: null, + // set later on + range: [from, to] + }); + } -(0, _util.inherits)(TryEntry, Entry); -exports.TryEntry = TryEntry; + function createAlternative(terms, from, to) { + return addRaw({ + type: 'alternative', + body: terms, + range: [from, to] + }); + } -function CatchEntry(firstLoc, paramId) { - Entry.call(this); + function createCharacterClass(classRanges, negative, from, to) { + return addRaw({ + type: 'characterClass', + body: classRanges, + negative: negative, + range: [from, to] + }); + } - t.assertLiteral(firstLoc); - t.assertIdentifier(paramId); + function createClassRange(min, max, from, to) { + // See 15.10.2.15: + if (min.codePoint > max.codePoint) { + bail('invalid range in character class', min.raw + '-' + max.raw, from, to); + } - this.firstLoc = firstLoc; - this.paramId = paramId; -} + return addRaw({ + type: 'characterClassRange', + min: min, + max: max, + range: [from, to] + }); + } -(0, _util.inherits)(CatchEntry, Entry); -exports.CatchEntry = CatchEntry; + function flattenBody(body) { + if (body.type === 'alternative') { + return body.body; + } else { + return [body]; + } + } -function FinallyEntry(firstLoc, afterLoc) { - Entry.call(this); - t.assertLiteral(firstLoc); - t.assertLiteral(afterLoc); - this.firstLoc = firstLoc; - this.afterLoc = afterLoc; -} + function isEmpty(obj) { + return obj.type === 'empty'; + } -(0, _util.inherits)(FinallyEntry, Entry); -exports.FinallyEntry = FinallyEntry; + function incr(amount) { + amount = amount || 1; + var res = str.substring(pos, pos + amount); + pos += amount || 1; + return res; + } -function LabeledEntry(breakLoc, label) { - Entry.call(this); + function skip(value) { + if (!match(value)) { + bail('character', value); + } + } - t.assertLiteral(breakLoc); - t.assertIdentifier(label); + function match(value) { + if (str.indexOf(value, pos) === pos) { + return incr(value.length); + } + } - this.breakLoc = breakLoc; - this.label = label; -} + function lookahead() { + return str[pos]; + } -(0, _util.inherits)(LabeledEntry, Entry); -exports.LabeledEntry = LabeledEntry; + function current(value) { + return str.indexOf(value, pos) === pos; + } -function LeapManager(emitter) { - _assert2.default.ok(this instanceof LeapManager); + function next(value) { + return str[pos + 1] === value; + } - var Emitter = require("./emit").Emitter; - _assert2.default.ok(emitter instanceof Emitter); + function matchReg(regExp) { + var subStr = str.substring(pos); + var res = subStr.match(regExp); - this.emitter = emitter; - this.entryStack = [new FunctionEntry(emitter.finalLoc)]; -} + if (res) { + res.range = []; + res.range[0] = pos; + incr(res[0].length); + res.range[1] = pos; + } -var LMp = LeapManager.prototype; -exports.LeapManager = LeapManager; + return res; + } -LMp.withEntry = function (entry, callback) { - _assert2.default.ok(entry instanceof Entry); - this.entryStack.push(entry); - try { - callback.call(this.emitter); - } finally { - var popped = this.entryStack.pop(); - _assert2.default.strictEqual(popped, entry); - } -}; + function parseDisjunction() { + // Disjunction :: + // Alternative + // Alternative | Disjunction + var res = [], + from = pos; + res.push(parseAlternative()); -LMp._findLeapLocation = function (property, label) { - for (var i = this.entryStack.length - 1; i >= 0; --i) { - var entry = this.entryStack[i]; - var loc = entry[property]; - if (loc) { - if (label) { - if (entry.label && entry.label.name === label.name) { - return loc; - } - } else if (entry instanceof LabeledEntry) { - // Ignore LabeledEntry entries unless we are actually breaking to - // a label. - } else { - return loc; + while (match('|')) { + res.push(parseAlternative()); } - } - } - return null; -}; + if (res.length === 1) { + return res[0]; + } -LMp.getBreakLoc = function (label) { - return this._findLeapLocation("breakLoc", label); -}; + return createDisjunction(res, from, pos); + } -LMp.getContinueLoc = function (label) { - return this._findLeapLocation("continueLoc", label); -}; -},{"./emit":527,"assert":3,"babel-types":151,"util":560}],531:[function(require,module,exports){ -"use strict"; + function parseAlternative() { + var res = [], + from = pos; + var term; // Alternative :: + // [empty] + // Alternative Term -var _assert = require("assert"); + while (term = parseTerm()) { + res.push(term); + } -var _assert2 = _interopRequireDefault(_assert); + if (res.length === 1) { + return res[0]; + } -var _babelTypes = require("babel-types"); + return createAlternative(res, from, pos); + } -var t = _interopRequireWildcard(_babelTypes); + function parseTerm() { + // Term :: + // Anchor + // Atom + // Atom Quantifier + if (pos >= str.length || current('|') || current(')')) { + return null; + /* Means: The term is empty */ + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var anchor = parseAnchor(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (anchor) { + return anchor; + } -var m = require("private").makeAccessor(); /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + var atom = parseAtom(); -var hasOwn = Object.prototype.hasOwnProperty; + if (!atom) { + bail('Expected atom'); + } -function makePredicate(propertyName, knownTypes) { - function onlyChildren(node) { - t.assertNode(node); + var quantifier = parseQuantifier() || false; - // Assume no side effects until we find out otherwise. - var result = false; + if (quantifier) { + quantifier.body = flattenBody(atom); // The quantifier contains the atom. Therefore, the beginning of the + // quantifier range is given by the beginning of the atom. - function check(child) { - if (result) { - // Do nothing. - } else if (Array.isArray(child)) { - child.some(check); - } else if (t.isNode(child)) { - _assert2.default.strictEqual(result, false); - result = predicate(child); + updateRawStart(quantifier, atom.range[0]); + return quantifier; } - return result; + + return atom; } - var keys = t.VISITOR_KEYS[node.type]; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var child = node[key]; - check(child); + function parseGroup(matchA, typeA, matchB, typeB) { + var type = null, + from = pos; + + if (match(matchA)) { + type = typeA; + } else if (match(matchB)) { + type = typeB; + } else { + return false; } - } - - return result; - } - function predicate(node) { - t.assertNode(node); + return finishGroup(type, from); + } - var meta = m(node); - if (hasOwn.call(meta, propertyName)) return meta[propertyName]; + function finishGroup(type, from) { + var body = parseDisjunction(); - // Certain types are "opaque," which means they have no side - // effects or leaps and we don't care about their subexpressions. - if (hasOwn.call(opaqueTypes, node.type)) return meta[propertyName] = false; + if (!body) { + bail('Expected disjunction'); + } - if (hasOwn.call(knownTypes, node.type)) return meta[propertyName] = true; + skip(')'); + var group = createGroup(type, flattenBody(body), from, pos); - return meta[propertyName] = onlyChildren(node); - } + if (type == 'normal') { + // Keep track of the number of closed groups. This is required for + // parseDecimalEscape(). In case the string is parsed a second time the + // value already holds the total count and no incrementation is required. + if (firstIteration) { + closedCaptureCounter++; + } + } - predicate.onlyChildren = onlyChildren; + return group; + } - return predicate; -} + function parseAnchor() { + // Anchor :: + // ^ + // $ + // \ b + // \ B + // ( ? = Disjunction ) + // ( ? ! Disjunction ) + var res, + from = pos; -var opaqueTypes = { - FunctionExpression: true, - ArrowFunctionExpression: true -}; + if (match('^')) { + return createAnchor('start', 1 + /* rawLength */ + ); + } else if (match('$')) { + return createAnchor('end', 1 + /* rawLength */ + ); + } else if (match('\\b')) { + return createAnchor('boundary', 2 + /* rawLength */ + ); + } else if (match('\\B')) { + return createAnchor('not-boundary', 2 + /* rawLength */ + ); + } else { + return parseGroup('(?=', 'lookahead', '(?!', 'negativeLookahead'); + } + } -// These types potentially have side effects regardless of what side -// effects their subexpressions have. -var sideEffectTypes = { - CallExpression: true, // Anything could happen! - ForInStatement: true, // Modifies the key variable. - UnaryExpression: true, // Think delete. - BinaryExpression: true, // Might invoke .toString() or .valueOf(). - AssignmentExpression: true, // Side-effecting by definition. - UpdateExpression: true, // Updates are essentially assignments. - NewExpression: true // Similar to CallExpression. -}; + function parseQuantifier() { + // Quantifier :: + // QuantifierPrefix + // QuantifierPrefix ? + // + // QuantifierPrefix :: + // * + // + + // ? + // { DecimalDigits } + // { DecimalDigits , } + // { DecimalDigits , DecimalDigits } + var res, + from = pos; + var quantifier; + var min, max; -// These types are the direct cause of all leaps in control flow. -var leapTypes = { - YieldExpression: true, - BreakStatement: true, - ContinueStatement: true, - ReturnStatement: true, - ThrowStatement: true -}; + if (match('*')) { + quantifier = createQuantifier(0); + } else if (match('+')) { + quantifier = createQuantifier(1); + } else if (match('?')) { + quantifier = createQuantifier(0, 1); + } else if (res = matchReg(/^\{([0-9]+)\}/)) { + min = parseInt(res[1], 10); + quantifier = createQuantifier(min, min, res.range[0], res.range[1]); + } else if (res = matchReg(/^\{([0-9]+),\}/)) { + min = parseInt(res[1], 10); + quantifier = createQuantifier(min, undefined, res.range[0], res.range[1]); + } else if (res = matchReg(/^\{([0-9]+),([0-9]+)\}/)) { + min = parseInt(res[1], 10); + max = parseInt(res[2], 10); -// All leap types are also side effect types. -for (var type in leapTypes) { - if (hasOwn.call(leapTypes, type)) { - sideEffectTypes[type] = leapTypes[type]; - } -} + if (min > max) { + bail('numbers out of order in {} quantifier', '', from, pos); + } -exports.hasSideEffects = makePredicate("hasSideEffects", sideEffectTypes); -exports.containsLeap = makePredicate("containsLeap", leapTypes); -},{"assert":3,"babel-types":151,"private":524}],532:[function(require,module,exports){ -"use strict"; + quantifier = createQuantifier(min, max, res.range[0], res.range[1]); + } -exports.__esModule = true; -exports.default = replaceShorthandObjectMethod; + if (quantifier) { + if (match('?')) { + quantifier.greedy = false; + quantifier.range[1] += 1; + } + } -var _babelTypes = require("babel-types"); + return quantifier; + } -var t = _interopRequireWildcard(_babelTypes); + function parseAtom() { + // Atom :: + // PatternCharacter + // . + // \ AtomEscape + // CharacterClass + // ( GroupSpecifier Disjunction ) + // ( ? : Disjunction ) + var res; // jviereck: allow ']', '}' here as well to be compatible with browser's + // implementations: ']'.match(/]/); + // if (res = matchReg(/^[^^$\\.*+?()[\]{}|]/)) { -var _util = require("./util"); + if (res = matchReg(/^[^^$\\.*+?(){[|]/)) { + // PatternCharacter + return createCharacter(res); + } else if (match('.')) { + // . + return createDot(); + } else if (match('\\')) { + // \ AtomEscape + res = parseAtomEscape(); -var util = _interopRequireWildcard(_util); + if (!res) { + if (!hasUnicodeFlag && lookahead() == 'c') { + // B.1.4 ExtendedAtom + // \[lookahead = c] + return createValue('symbol', 92, pos - 1, pos); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + bail('atomEscape'); + } -// this function converts a shorthand object generator method into a normal -// (non-shorthand) object property which is a generator function expression. for -// example, this: -// -// var foo = { -// *bar(baz) { return 5; } -// } -// -// should be replaced with: -// -// var foo = { -// bar: function*(baz) { return 5; } -// } -// -// to do this, it clones the parameter array and the body of the object generator -// method into a new FunctionExpression. -// -// this method can be passed any Function AST node path, and it will return -// either: -// a) the path that was passed in (iff the path did not need to be replaced) or -// b) the path of the new FunctionExpression that was created as a replacement -// (iff the path did need to be replaced) -// -// In either case, though, the caller can count on the fact that the return value -// is a Function AST node path. -// -// If this function is called with an AST node path that is not a Function (or with an -// argument that isn't an AST node path), it will throw an error. -function replaceShorthandObjectMethod(path) { - if (!path.node || !t.isFunction(path.node)) { - throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths."); - } + return res; + } else if (res = parseCharacterClass()) { + return res; + } else if (features.lookbehind && (res = parseGroup('(?<=', 'lookbehind', '(?"); + var group = finishGroup("normal", name.range[0] - 3); + group.name = name; + return group; + } else { + // ( Disjunction ) + // ( ? : Disjunction ) + return parseGroup('(?:', 'ignore', '(', 'normal'); + } + } - // this function only replaces shorthand object methods (called ObjectMethod - // in Babel-speak). - if (!t.isObjectMethod(path.node)) { - return path; - } + function parseUnicodeSurrogatePairEscape(firstEscape) { + if (hasUnicodeFlag) { + var first, second; - // this function only replaces generators. - if (!path.node.generator) { - return path; - } + if (firstEscape.kind == 'unicodeEscape' && (first = firstEscape.codePoint) >= 0xD800 && first <= 0xDBFF && current('\\') && next('u')) { + var prevPos = pos; + pos++; + var secondEscape = parseClassEscape(); - var parameters = path.node.params.map(function (param) { - return t.cloneDeep(param); - }); + if (secondEscape.kind == 'unicodeEscape' && (second = secondEscape.codePoint) >= 0xDC00 && second <= 0xDFFF) { + // Unicode surrogate pair + firstEscape.range[1] = secondEscape.range[1]; + firstEscape.codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + firstEscape.type = 'value'; + firstEscape.kind = 'unicodeCodePointEscape'; + addRaw(firstEscape); + } else { + pos = prevPos; + } + } + } - var functionExpression = t.functionExpression(null, // id - parameters, // params - t.cloneDeep(path.node.body), // body - path.node.generator, path.node.async); + return firstEscape; + } - util.replaceWithOrRemove(path, t.objectProperty(t.cloneDeep(path.node.key), // key - functionExpression, //value - path.node.computed, // computed - false // shorthand - )); + function parseClassEscape() { + return parseAtomEscape(true); + } - // path now refers to the ObjectProperty AST node path, but we want to return a - // Function AST node path for the function expression we created. we know that - // the FunctionExpression we just created is the value of the ObjectProperty, - // so return the "value" path off of this path. - return path.get("value"); -} -},{"./util":533,"babel-types":151}],533:[function(require,module,exports){ -"use strict"; + function parseAtomEscape(insideCharacterClass) { + // AtomEscape :: + // DecimalEscape + // CharacterEscape + // CharacterClassEscape + // k GroupName + var res, + from = pos; + res = parseDecimalEscape() || parseNamedReference(); -exports.__esModule = true; -exports.runtimeProperty = runtimeProperty; -exports.isReference = isReference; -exports.replaceWithOrRemove = replaceWithOrRemove; + if (res) { + return res; + } // For ClassEscape -var _babelTypes = require("babel-types"); -var t = _interopRequireWildcard(_babelTypes); + if (insideCharacterClass) { + if (match('b')) { + // 15.10.2.19 + // The production ClassEscape :: b evaluates by returning the + // CharSet containing the one character (Unicode value 0008). + return createEscaped('singleEscape', 0x0008, '\\b'); + } else if (match('B')) { + bail('\\B not possible inside of CharacterClass', '', from); + } else if (!hasUnicodeFlag && (res = matchReg(/^c([0-9])/))) { + // B.1.4 + // c ClassControlLetter + return createEscaped('controlLetter', res[1] + 16, res[1], 2); + } + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + res = parseCharacterEscape(); + return res; + } -function runtimeProperty(name) { - return t.memberExpression(t.identifier("regeneratorRuntime"), t.identifier(name), false); -} /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + function parseDecimalEscape() { + // DecimalEscape :: + // DecimalIntegerLiteral [lookahead ∉ DecimalDigit] + // CharacterClassEscape :: one of d D s S w W + var res, match; -function isReference(path) { - return path.isReferenced() || path.parentPath.isAssignmentExpression({ left: path.node }); -} + if (res = matchReg(/^(?!0)\d+/)) { + match = res[0]; + var refIdx = parseInt(res[0], 10); -function replaceWithOrRemove(path, replacement) { - if (replacement) { - path.replaceWith(replacement); - } else { - path.remove(); - } -} -},{"babel-types":151}],534:[function(require,module,exports){ -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + if (refIdx <= closedCaptureCounter) { + // If the number is smaller than the normal-groups found so + // far, then it is a reference... + return createReference(res[0]); + } else { + // ... otherwise it needs to be interpreted as a octal (if the + // number is in an octal format). If it is NOT octal format, + // then the slash is ignored and the number is matched later + // as normal characters. + // Recall the negative decision to decide if the input must be parsed + // a second time with the total normal-groups. + backrefDenied.push(refIdx); // Reset the position again, as maybe only parts of the previous + // matched numbers are actual octal numbers. E.g. in '019' only + // the '01' should be matched. -"use strict"; + incr(-res[0].length); -var _assert = require("assert"); + if (res = matchReg(/^[0-7]{1,3}/)) { + return createEscaped('octal', parseInt(res[0], 8), res[0], 1); + } else { + // If we end up here, we have a case like /\91/. Then the + // first slash is to be ignored and the 9 & 1 to be treated + // like ordinary characters. Create a character for the + // first number only here - other number-characters + // (if available) will be matched later. + res = createCharacter(matchReg(/^[89]/)); + return updateRawStart(res, res.range[0] - 1); + } + } + } // Only allow octal numbers in the following. All matched numbers start + // with a zero (if the do not, the previous if-branch is executed). + // If the number is not octal format and starts with zero (e.g. `091`) + // then only the zeros `0` is treated here and the `91` are ordinary + // characters. + // Example: + // /\091/.exec('\091')[0].length === 3 + else if (res = matchReg(/^[0-7]{1,3}/)) { + match = res[0]; -var _assert2 = _interopRequireDefault(_assert); + if (/^0{1,3}$/.test(match)) { + // If they are all zeros, then only take the first one. + return createEscaped('null', 0x0000, '0', match.length + 1); + } else { + return createEscaped('octal', parseInt(match, 8), match, 1); + } + } else if (res = matchReg(/^[dDsSwW]/)) { + return createCharacterClassEscape(res[0]); + } -var _babelTypes = require("babel-types"); + return false; + } -var t = _interopRequireWildcard(_babelTypes); + function parseNamedReference() { + if (features.namedGroups && matchReg(/^k<(?=.*?>)/)) { + var name = parseIdentifier(); + skip('>'); + return createNamedReference(name); + } + } -var _hoist = require("./hoist"); + function parseRegExpUnicodeEscapeSequence() { + var res; -var _emit = require("./emit"); + if (res = matchReg(/^u([0-9a-fA-F]{4})/)) { + // UnicodeEscapeSequence + return parseUnicodeSurrogatePairEscape(createEscaped('unicodeEscape', parseInt(res[1], 16), res[1], 2)); + } else if (hasUnicodeFlag && (res = matchReg(/^u\{([0-9a-fA-F]+)\}/))) { + // RegExpUnicodeEscapeSequence (ES6 Unicode code point escape) + return createEscaped('unicodeCodePointEscape', parseInt(res[1], 16), res[1], 4); + } + } -var _replaceShorthandObjectMethod = require("./replaceShorthandObjectMethod"); + function parseCharacterEscape() { + // CharacterEscape :: + // ControlEscape + // c ControlLetter + // HexEscapeSequence + // UnicodeEscapeSequence + // IdentityEscape + var res; + var from = pos; -var _replaceShorthandObjectMethod2 = _interopRequireDefault(_replaceShorthandObjectMethod); + if (res = matchReg(/^[fnrtv]/)) { + // ControlEscape + var codePoint = 0; -var _util = require("./util"); + switch (res[0]) { + case 't': + codePoint = 0x009; + break; -var util = _interopRequireWildcard(_util); + case 'n': + codePoint = 0x00A; + break; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + case 'v': + codePoint = 0x00B; + break; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case 'f': + codePoint = 0x00C; + break; -exports.visitor = { - Function: { - exit: function exit(path, state) { - var node = path.node; + case 'r': + codePoint = 0x00D; + break; + } - if (node.generator) { - if (node.async) { - // Async generator - if (state.opts.asyncGenerators === false) return; - } else { - // Plain generator - if (state.opts.generators === false) return; + return createEscaped('singleEscape', codePoint, '\\' + res[0]); + } else if (res = matchReg(/^c([a-zA-Z])/)) { + // c ControlLetter + return createEscaped('controlLetter', res[1].charCodeAt(0) % 32, res[1], 2); + } else if (res = matchReg(/^x([0-9a-fA-F]{2})/)) { + // HexEscapeSequence + return createEscaped('hexadecimalEscape', parseInt(res[1], 16), res[1], 2); + } else if (res = parseRegExpUnicodeEscapeSequence()) { + if (!res || res.codePoint > 0x10FFFF) { + bail('Invalid escape sequence', null, from, pos); } - } else if (node.async) { - // Async function - if (state.opts.async === false) return; + + return res; + } else if (features.unicodePropertyEscape && hasUnicodeFlag && (res = matchReg(/^([pP])\{([^\}]+)\}/))) { + // https://github.com/jviereck/regjsparser/issues/77 + return addRaw({ + type: 'unicodePropertyEscape', + negative: res[1] === 'P', + value: res[2], + range: [res.range[0] - 1, res.range[1]], + raw: res[0] + }); } else { - // Not a generator or async function. - return; + // IdentityEscape + return parseIdentityEscape(); } + } - // if this is an ObjectMethod, we need to convert it to an ObjectProperty - path = (0, _replaceShorthandObjectMethod2.default)(path); - node = path.node; - - var contextId = path.scope.generateUidIdentifier("context"); - var argsId = path.scope.generateUidIdentifier("args"); - - path.ensureBlock(); - var bodyBlockPath = path.get("body"); - - if (node.async) { - bodyBlockPath.traverse(awaitVisitor); - } + function parseIdentifierAtom(check) { + var ch = lookahead(); + var from = pos; - bodyBlockPath.traverse(functionSentVisitor, { - context: contextId - }); + if (ch === '\\') { + incr(); + var esc = parseRegExpUnicodeEscapeSequence(); - var outerBody = []; - var innerBody = []; - - bodyBlockPath.get("body").forEach(function (childPath) { - var node = childPath.node; - if (t.isExpressionStatement(node) && t.isStringLiteral(node.expression)) { - // Babylon represents directives like "use strict" as elements - // of a bodyBlockPath.node.directives array, but they could just - // as easily be represented (by other parsers) as traditional - // string-literal-valued expression statements, so we need to - // handle that here. (#248) - outerBody.push(node); - } else if (node && node._blockHoist != null) { - outerBody.push(node); - } else { - innerBody.push(node); + if (!esc || !check(esc.codePoint)) { + bail('Invalid escape sequence', null, from, pos); } - }); - if (outerBody.length > 0) { - // Only replace the inner body if we actually hoisted any statements - // to the outer body. - bodyBlockPath.node.body = innerBody; + return fromCodePoint(esc.codePoint); } - var outerFnExpr = getOuterFnExpr(path); - // Note that getOuterFnExpr has the side-effect of ensuring that the - // function has a name (so node.id will always be an Identifier), even - // if a temporary name has to be synthesized. - t.assertIdentifier(node.id); - var innerFnId = t.identifier(node.id.name + "$"); + var code = ch.charCodeAt(0); - // Turn all declarations into vars, and replace the original - // declarations with equivalent assignment expressions. - var vars = (0, _hoist.hoist)(path); + if (code >= 0xD800 && code <= 0xDBFF) { + ch += str[pos + 1]; + var second = ch.charCodeAt(1); - var didRenameArguments = renameArguments(path, argsId); - if (didRenameArguments) { - vars = vars || t.variableDeclaration("var", []); - var argumentIdentifier = t.identifier("arguments"); - // we need to do this as otherwise arguments in arrow functions gets hoisted - argumentIdentifier._shadowedFunctionLiteral = path; - vars.declarations.push(t.variableDeclarator(argsId, argumentIdentifier)); + if (second >= 0xDC00 && second <= 0xDFFF) { + // Unicode surrogate pair + code = (code - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } } - var emitter = new _emit.Emitter(contextId); - emitter.explode(path.get("body")); + if (!check(code)) return; + incr(); + if (code > 0xFFFF) incr(); + return ch; + } + + function parseIdentifier() { + // RegExpIdentifierName :: + // RegExpIdentifierStart + // RegExpIdentifierName RegExpIdentifierContinue + // + // RegExpIdentifierStart :: + // UnicodeIDStart + // $ + // _ + // \ RegExpUnicodeEscapeSequence + // + // RegExpIdentifierContinue :: + // UnicodeIDContinue + // $ + // _ + // \ RegExpUnicodeEscapeSequence + // + // + var start = pos; + var res = parseIdentifierAtom(isIdentifierStart); - if (vars && vars.declarations.length > 0) { - outerBody.push(vars); + if (!res) { + bail('Invalid identifier'); } - var wrapArgs = [emitter.getContextFunction(innerFnId), - // Async functions that are not generators don't care about the - // outer function because they don't need it to be marked and don't - // inherit from its .prototype. - node.generator ? outerFnExpr : t.nullLiteral(), t.thisExpression()]; + var ch; - var tryLocsList = emitter.getTryLocsList(); - if (tryLocsList) { - wrapArgs.push(tryLocsList); + while (ch = parseIdentifierAtom(isIdentifierPart)) { + res += ch; } - var wrapCall = t.callExpression(util.runtimeProperty(node.async ? "async" : "wrap"), wrapArgs); + return addRaw({ + type: 'identifier', + value: res, + range: [start, pos] + }); + } - outerBody.push(t.returnStatement(wrapCall)); - node.body = t.blockStatement(outerBody); + function isIdentifierStart(ch) { + // Generated by `tools/generate-identifier-regex.js`. + var NonAsciiIdentifierStart = /[\$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7B9\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDF00-\uDF1C\uDF27\uDF30-\uDF45]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF1A]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFF1]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; + return ch === 36 || ch === 95 || // $ (dollar) and _ (underscore) + ch >= 65 && ch <= 90 || // A..Z + ch >= 97 && ch <= 122 || // a..z + ch >= 0x80 && NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } // Taken from the Esprima parser. - var oldDirectives = bodyBlockPath.node.directives; - if (oldDirectives) { - // Babylon represents directives like "use strict" as elements of - // a bodyBlockPath.node.directives array. (#248) - node.body.directives = oldDirectives; - } - var wasGeneratorFunction = node.generator; - if (wasGeneratorFunction) { - node.generator = false; - } + function isIdentifierPart(ch) { + // Generated by `tools/generate-identifier-regex.js`. + var NonAsciiIdentifierPartOnly = /[0-9_\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD801[\uDCA0-\uDCA9]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD803[\uDD24-\uDD27\uDD30-\uDD39\uDF46-\uDF50]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC66-\uDC6F\uDC7F-\uDC82\uDCB0-\uDCBA\uDCF0-\uDCF9\uDD00-\uDD02\uDD27-\uDD34\uDD36-\uDD3F\uDD45\uDD46\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDDC9-\uDDCC\uDDD0-\uDDD9\uDE2C-\uDE37\uDE3E\uDEDF-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF3B\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC35-\uDC46\uDC50-\uDC59\uDC5E\uDCB0-\uDCC3\uDCD0-\uDCD9\uDDAF-\uDDB5\uDDB8-\uDDC0\uDDDC\uDDDD\uDE30-\uDE40\uDE50-\uDE59\uDEAB-\uDEB7\uDEC0-\uDEC9\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDC2C-\uDC3A\uDCE0-\uDCE9\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE3E\uDE47\uDE51-\uDE5B\uDE8A-\uDE99]|\uD807[\uDC2F-\uDC36\uDC38-\uDC3F\uDC50-\uDC59\uDC92-\uDCA7\uDCA9-\uDCB6\uDD31-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD45\uDD47\uDD50-\uDD59\uDD8A-\uDD8E\uDD90\uDD91\uDD93-\uDD97\uDDA0-\uDDA9\uDEF3-\uDEF6]|\uD81A[\uDE60-\uDE69\uDEF0-\uDEF4\uDF30-\uDF36\uDF50-\uDF59]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDCD0-\uDCD6\uDD44-\uDD4A\uDD50-\uDD59]|\uDB40[\uDD00-\uDDEF]/; + return isIdentifierStart(ch) || ch >= 48 && ch <= 57 || // 0..9 + ch >= 0x80 && NonAsciiIdentifierPartOnly.test(fromCodePoint(ch)); + } - if (node.async) { - node.async = false; - } + function parseIdentityEscape() { + // IdentityEscape :: + // SourceCharacter but not c + var tmp; - if (wasGeneratorFunction && t.isExpression(node)) { - util.replaceWithOrRemove(path, t.callExpression(util.runtimeProperty("mark"), [node])); - path.addComment("leading", "#__PURE__"); + if (lookahead() !== 'c') { + tmp = incr(); + return createEscaped('identifier', tmp.charCodeAt(0), tmp, 1); } - // Generators are processed in 'exit' handlers so that regenerator only has to run on - // an ES5 AST, but that means traversal will not pick up newly inserted references - // to things like 'regeneratorRuntime'. To avoid this, we explicitly requeue. - path.requeue(); + return null; } - } -}; - -// Given a NodePath for a Function, return an Expression node that can be -// used to refer reliably to the function object from inside the function. -// This expression is essentially a replacement for arguments.callee, with -// the key advantage that it works in strict mode. -function getOuterFnExpr(funPath) { - var node = funPath.node; - t.assertFunction(node); - - if (!node.id) { - // Default-exported function declarations, and function expressions may not - // have a name to reference, so we explicitly add one. - node.id = funPath.scope.parent.generateUidIdentifier("callee"); - } - if (node.generator && // Non-generator functions don't need to be marked. - t.isFunctionDeclaration(node)) { - // Return the identifier returned by runtime.mark(). - return getMarkedFunctionId(funPath); - } + function parseCharacterClass() { + // CharacterClass :: + // [ [lookahead ∉ {^}] ClassRanges ] + // [ ^ ClassRanges ] + var res, + from = pos; - return node.id; -} + if (res = matchReg(/^\[\^/)) { + res = parseClassRanges(); + skip(']'); + return createCharacterClass(res, true, from, pos); + } else if (match('[')) { + res = parseClassRanges(); + skip(']'); + return createCharacterClass(res, false, from, pos); + } -var getMarkInfo = require("private").makeAccessor(); + return null; + } -function getMarkedFunctionId(funPath) { - var node = funPath.node; - t.assertIdentifier(node.id); + function parseClassRanges() { + // ClassRanges :: + // [empty] + // NonemptyClassRanges + var res; - var blockPath = funPath.findParent(function (path) { - return path.isProgram() || path.isBlockStatement(); - }); + if (current(']')) { + // Empty array means nothing insinde of the ClassRange. + return []; + } else { + res = parseNonemptyClassRanges(); - if (!blockPath) { - return node.id; - } + if (!res) { + bail('nonEmptyClassRanges'); + } - var block = blockPath.node; - _assert2.default.ok(Array.isArray(block.body)); + return res; + } + } - var info = getMarkInfo(block); - if (!info.decl) { - info.decl = t.variableDeclaration("var", []); - blockPath.unshiftContainer("body", info.decl); - info.declPath = blockPath.get("body.0"); - } + function parseHelperClassRanges(atom) { + var from, to, res; - _assert2.default.strictEqual(info.declPath.node, info.decl); + if (current('-') && !next(']')) { + // ClassAtom - ClassAtom ClassRanges + skip('-'); + res = parseClassAtom(); - // Get a new unique identifier for our marked variable. - var markedId = blockPath.scope.generateUidIdentifier("marked"); - var markCallExp = t.callExpression(util.runtimeProperty("mark"), [node.id]); + if (!res) { + bail('classAtom'); + } - var index = info.decl.declarations.push(t.variableDeclarator(markedId, markCallExp)) - 1; + to = pos; + var classRanges = parseClassRanges(); - var markCallExpPath = info.declPath.get("declarations." + index + ".init"); + if (!classRanges) { + bail('classRanges'); + } - _assert2.default.strictEqual(markCallExpPath.node, markCallExp); + from = atom.range[0]; - markCallExpPath.addComment("leading", "#__PURE__"); + if (classRanges.type === 'empty') { + return [createClassRange(atom, res, from, to)]; + } - return markedId; -} + return [createClassRange(atom, res, from, to)].concat(classRanges); + } -function renameArguments(funcPath, argsId) { - var state = { - didRenameArguments: false, - argsId: argsId - }; + res = parseNonemptyClassRangesNoDash(); - funcPath.traverse(argumentsVisitor, state); + if (!res) { + bail('nonEmptyClassRangesNoDash'); + } - // If the traversal replaced any arguments references, then we need to - // alias the outer function's arguments binding (be it the implicit - // arguments object or some other parameter or variable) to the variable - // named by argsId. - return state.didRenameArguments; -} + return [atom].concat(res); + } -var argumentsVisitor = { - "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { - path.skip(); - }, + function parseNonemptyClassRanges() { + // NonemptyClassRanges :: + // ClassAtom + // ClassAtom NonemptyClassRangesNoDash + // ClassAtom - ClassAtom ClassRanges + var atom = parseClassAtom(); - Identifier: function Identifier(path, state) { - if (path.node.name === "arguments" && util.isReference(path)) { - util.replaceWithOrRemove(path, state.argsId); - state.didRenameArguments = true; - } - } -}; + if (!atom) { + bail('classAtom'); + } -var functionSentVisitor = { - MetaProperty: function MetaProperty(path) { - var node = path.node; + if (current(']')) { + // ClassAtom + return [atom]; + } // ClassAtom NonemptyClassRangesNoDash + // ClassAtom - ClassAtom ClassRanges - if (node.meta.name === "function" && node.property.name === "sent") { - util.replaceWithOrRemove(path, t.memberExpression(this.context, t.identifier("_sent"))); + return parseHelperClassRanges(atom); } - } -}; -var awaitVisitor = { - Function: function Function(path) { - path.skip(); // Don't descend into nested function scopes. - }, + function parseNonemptyClassRangesNoDash() { + // NonemptyClassRangesNoDash :: + // ClassAtom + // ClassAtomNoDash NonemptyClassRangesNoDash + // ClassAtomNoDash - ClassAtom ClassRanges + var res = parseClassAtom(); - AwaitExpression: function AwaitExpression(path) { - // Convert await expressions to yield expressions. - var argument = path.node.argument; + if (!res) { + bail('classAtom'); + } - // Transforming `await x` to `yield regeneratorRuntime.awrap(x)` - // causes the argument to be wrapped in such a way that the runtime - // can distinguish between awaited and merely yielded values. - util.replaceWithOrRemove(path, t.yieldExpression(t.callExpression(util.runtimeProperty("awrap"), [argument]), false)); - } -}; -},{"./emit":527,"./hoist":528,"./replaceShorthandObjectMethod":532,"./util":533,"assert":3,"babel-types":151,"private":524}],535:[function(require,module,exports){ -// Generated by `/scripts/character-class-escape-sets.js`. Do not edit. -var regenerate = require('regenerate'); + if (current(']')) { + // ClassAtom + return res; + } // ClassAtomNoDash NonemptyClassRangesNoDash + // ClassAtomNoDash - ClassAtom ClassRanges -exports.REGULAR = { - 'd': regenerate() - .addRange(0x30, 0x39), - 'D': regenerate() - .addRange(0x0, 0x2F) - .addRange(0x3A, 0xFFFF), - 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) - .addRange(0x9, 0xD) - .addRange(0x2000, 0x200A) - .addRange(0x2028, 0x2029), - 'S': regenerate() - .addRange(0x0, 0x8) - .addRange(0xE, 0x1F) - .addRange(0x21, 0x9F) - .addRange(0xA1, 0x167F) - .addRange(0x1681, 0x1FFF) - .addRange(0x200B, 0x2027) - .addRange(0x202A, 0x202E) - .addRange(0x2030, 0x205E) - .addRange(0x2060, 0x2FFF) - .addRange(0x3001, 0xFEFE) - .addRange(0xFF00, 0xFFFF), - 'w': regenerate(0x5F) - .addRange(0x30, 0x39) - .addRange(0x41, 0x5A) - .addRange(0x61, 0x7A), - 'W': regenerate(0x60) - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x40) - .addRange(0x5B, 0x5E) - .addRange(0x7B, 0xFFFF) -}; - -exports.UNICODE = { - 'd': regenerate() - .addRange(0x30, 0x39), - 'D': regenerate() - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x10FFFF), - 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) - .addRange(0x9, 0xD) - .addRange(0x2000, 0x200A) - .addRange(0x2028, 0x2029), - 'S': regenerate() - .addRange(0x0, 0x8) - .addRange(0xE, 0x1F) - .addRange(0x21, 0x9F) - .addRange(0xA1, 0x167F) - .addRange(0x1681, 0x1FFF) - .addRange(0x200B, 0x2027) - .addRange(0x202A, 0x202E) - .addRange(0x2030, 0x205E) - .addRange(0x2060, 0x2FFF) - .addRange(0x3001, 0xFEFE) - .addRange(0xFF00, 0x10FFFF), - 'w': regenerate(0x5F) - .addRange(0x30, 0x39) - .addRange(0x41, 0x5A) - .addRange(0x61, 0x7A), - 'W': regenerate(0x60) - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x40) - .addRange(0x5B, 0x5E) - .addRange(0x7B, 0x10FFFF) -}; - -exports.UNICODE_IGNORE_CASE = { - 'd': regenerate() - .addRange(0x30, 0x39), - 'D': regenerate() - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x10FFFF), - 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) - .addRange(0x9, 0xD) - .addRange(0x2000, 0x200A) - .addRange(0x2028, 0x2029), - 'S': regenerate() - .addRange(0x0, 0x8) - .addRange(0xE, 0x1F) - .addRange(0x21, 0x9F) - .addRange(0xA1, 0x167F) - .addRange(0x1681, 0x1FFF) - .addRange(0x200B, 0x2027) - .addRange(0x202A, 0x202E) - .addRange(0x2030, 0x205E) - .addRange(0x2060, 0x2FFF) - .addRange(0x3001, 0xFEFE) - .addRange(0xFF00, 0x10FFFF), - 'w': regenerate(0x5F, 0x17F, 0x212A) - .addRange(0x30, 0x39) - .addRange(0x41, 0x5A) - .addRange(0x61, 0x7A), - 'W': regenerate(0x4B, 0x53, 0x60) - .addRange(0x0, 0x2F) - .addRange(0x3A, 0x40) - .addRange(0x5B, 0x5E) - .addRange(0x7B, 0x10FFFF) -}; - -},{"regenerate":526}],536:[function(require,module,exports){ -module.exports={ - "75": 8490, - "83": 383, - "107": 8490, - "115": 383, - "181": 924, - "197": 8491, - "383": 83, - "452": 453, - "453": 452, - "455": 456, - "456": 455, - "458": 459, - "459": 458, - "497": 498, - "498": 497, - "837": 8126, - "914": 976, - "917": 1013, - "920": 1012, - "921": 8126, - "922": 1008, - "924": 181, - "928": 982, - "929": 1009, - "931": 962, - "934": 981, - "937": 8486, - "962": 931, - "976": 914, - "977": 1012, - "981": 934, - "982": 928, - "1008": 922, - "1009": 929, - "1012": [ - 920, - 977 - ], - "1013": 917, - "7776": 7835, - "7835": 7776, - "8126": [ - 837, - 921 - ], - "8486": 937, - "8490": 75, - "8491": 197, - "66560": 66600, - "66561": 66601, - "66562": 66602, - "66563": 66603, - "66564": 66604, - "66565": 66605, - "66566": 66606, - "66567": 66607, - "66568": 66608, - "66569": 66609, - "66570": 66610, - "66571": 66611, - "66572": 66612, - "66573": 66613, - "66574": 66614, - "66575": 66615, - "66576": 66616, - "66577": 66617, - "66578": 66618, - "66579": 66619, - "66580": 66620, - "66581": 66621, - "66582": 66622, - "66583": 66623, - "66584": 66624, - "66585": 66625, - "66586": 66626, - "66587": 66627, - "66588": 66628, - "66589": 66629, - "66590": 66630, - "66591": 66631, - "66592": 66632, - "66593": 66633, - "66594": 66634, - "66595": 66635, - "66596": 66636, - "66597": 66637, - "66598": 66638, - "66599": 66639, - "66600": 66560, - "66601": 66561, - "66602": 66562, - "66603": 66563, - "66604": 66564, - "66605": 66565, - "66606": 66566, - "66607": 66567, - "66608": 66568, - "66609": 66569, - "66610": 66570, - "66611": 66571, - "66612": 66572, - "66613": 66573, - "66614": 66574, - "66615": 66575, - "66616": 66576, - "66617": 66577, - "66618": 66578, - "66619": 66579, - "66620": 66580, - "66621": 66581, - "66622": 66582, - "66623": 66583, - "66624": 66584, - "66625": 66585, - "66626": 66586, - "66627": 66587, - "66628": 66588, - "66629": 66589, - "66630": 66590, - "66631": 66591, - "66632": 66592, - "66633": 66593, - "66634": 66594, - "66635": 66595, - "66636": 66596, - "66637": 66597, - "66638": 66598, - "66639": 66599, - "68736": 68800, - "68737": 68801, - "68738": 68802, - "68739": 68803, - "68740": 68804, - "68741": 68805, - "68742": 68806, - "68743": 68807, - "68744": 68808, - "68745": 68809, - "68746": 68810, - "68747": 68811, - "68748": 68812, - "68749": 68813, - "68750": 68814, - "68751": 68815, - "68752": 68816, - "68753": 68817, - "68754": 68818, - "68755": 68819, - "68756": 68820, - "68757": 68821, - "68758": 68822, - "68759": 68823, - "68760": 68824, - "68761": 68825, - "68762": 68826, - "68763": 68827, - "68764": 68828, - "68765": 68829, - "68766": 68830, - "68767": 68831, - "68768": 68832, - "68769": 68833, - "68770": 68834, - "68771": 68835, - "68772": 68836, - "68773": 68837, - "68774": 68838, - "68775": 68839, - "68776": 68840, - "68777": 68841, - "68778": 68842, - "68779": 68843, - "68780": 68844, - "68781": 68845, - "68782": 68846, - "68783": 68847, - "68784": 68848, - "68785": 68849, - "68786": 68850, - "68800": 68736, - "68801": 68737, - "68802": 68738, - "68803": 68739, - "68804": 68740, - "68805": 68741, - "68806": 68742, - "68807": 68743, - "68808": 68744, - "68809": 68745, - "68810": 68746, - "68811": 68747, - "68812": 68748, - "68813": 68749, - "68814": 68750, - "68815": 68751, - "68816": 68752, - "68817": 68753, - "68818": 68754, - "68819": 68755, - "68820": 68756, - "68821": 68757, - "68822": 68758, - "68823": 68759, - "68824": 68760, - "68825": 68761, - "68826": 68762, - "68827": 68763, - "68828": 68764, - "68829": 68765, - "68830": 68766, - "68831": 68767, - "68832": 68768, - "68833": 68769, - "68834": 68770, - "68835": 68771, - "68836": 68772, - "68837": 68773, - "68838": 68774, - "68839": 68775, - "68840": 68776, - "68841": 68777, - "68842": 68778, - "68843": 68779, - "68844": 68780, - "68845": 68781, - "68846": 68782, - "68847": 68783, - "68848": 68784, - "68849": 68785, - "68850": 68786, - "71840": 71872, - "71841": 71873, - "71842": 71874, - "71843": 71875, - "71844": 71876, - "71845": 71877, - "71846": 71878, - "71847": 71879, - "71848": 71880, - "71849": 71881, - "71850": 71882, - "71851": 71883, - "71852": 71884, - "71853": 71885, - "71854": 71886, - "71855": 71887, - "71856": 71888, - "71857": 71889, - "71858": 71890, - "71859": 71891, - "71860": 71892, - "71861": 71893, - "71862": 71894, - "71863": 71895, - "71864": 71896, - "71865": 71897, - "71866": 71898, - "71867": 71899, - "71868": 71900, - "71869": 71901, - "71870": 71902, - "71871": 71903, - "71872": 71840, - "71873": 71841, - "71874": 71842, - "71875": 71843, - "71876": 71844, - "71877": 71845, - "71878": 71846, - "71879": 71847, - "71880": 71848, - "71881": 71849, - "71882": 71850, - "71883": 71851, - "71884": 71852, - "71885": 71853, - "71886": 71854, - "71887": 71855, - "71888": 71856, - "71889": 71857, - "71890": 71858, - "71891": 71859, - "71892": 71860, - "71893": 71861, - "71894": 71862, - "71895": 71863, - "71896": 71864, - "71897": 71865, - "71898": 71866, - "71899": 71867, - "71900": 71868, - "71901": 71869, - "71902": 71870, - "71903": 71871 -} - -},{}],537:[function(require,module,exports){ -var generate = require('regjsgen').generate; -var parse = require('regjsparser').parse; -var regenerate = require('regenerate'); -var iuMappings = require('./data/iu-mappings.json'); -var ESCAPE_SETS = require('./data/character-class-escape-sets.js'); - -function getCharacterClassEscapeSet(character) { - if (unicode) { - if (ignoreCase) { - return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]; - } - return ESCAPE_SETS.UNICODE[character]; - } - return ESCAPE_SETS.REGULAR[character]; -} -var object = {}; -var hasOwnProperty = object.hasOwnProperty; -function has(object, property) { - return hasOwnProperty.call(object, property); -} + return parseHelperClassRanges(res); + } -// Prepare a Regenerate set containing all code points, used for negative -// character classes (if any). -var UNICODE_SET = regenerate().addRange(0x0, 0x10FFFF); -// Without the `u` flag, the range stops at 0xFFFF. -// https://mths.be/es6#sec-pattern-semantics -var BMP_SET = regenerate().addRange(0x0, 0xFFFF); + function parseClassAtom() { + // ClassAtom :: + // - + // ClassAtomNoDash + if (match('-')) { + return createCharacter('-'); + } else { + return parseClassAtomNoDash(); + } + } -// Prepare a Regenerate set containing all code points that are supposed to be -// matched by `/./u`. https://mths.be/es6#sec-atom -var DOT_SET_UNICODE = UNICODE_SET.clone() // all Unicode code points - .remove( - // minus `LineTerminator`s (https://mths.be/es6#sec-line-terminators): - 0x000A, // Line Feed - 0x000D, // Carriage Return - 0x2028, // Line Separator - 0x2029 // Paragraph Separator - ); -// Prepare a Regenerate set containing all code points that are supposed to be -// matched by `/./` (only BMP code points). -var DOT_SET = DOT_SET_UNICODE.clone() - .intersection(BMP_SET); - -// Add a range of code points + any case-folded code points in that range to a -// set. -regenerate.prototype.iuAddRange = function(min, max) { - var $this = this; - do { - var folded = caseFold(min); - if (folded) { - $this.add(folded); - } - } while (++min <= max); - return $this; -}; - -function assign(target, source) { - for (var key in source) { - // Note: `hasOwnProperty` is not needed here. - target[key] = source[key]; - } -} + function parseClassAtomNoDash() { + // ClassAtomNoDash :: + // SourceCharacter but not one of \ or ] or - + // \ ClassEscape + var res; -function update(item, pattern) { - // TODO: Test if memoizing `pattern` here is worth the effort. - if (!pattern) { - return; - } - var tree = parse(pattern, ''); - switch (tree.type) { - case 'characterClass': - case 'group': - case 'value': - // No wrapping needed. - break; - default: - // Wrap the pattern in a non-capturing group. - tree = wrap(tree, pattern); - } - assign(item, tree); -} - -function wrap(tree, pattern) { - // Wrap the pattern in a non-capturing group. - return { - 'type': 'group', - 'behavior': 'ignore', - 'body': [tree], - 'raw': '(?:' + pattern + ')' - }; -} - -function caseFold(codePoint) { - return has(iuMappings, codePoint) ? iuMappings[codePoint] : false; -} - -var ignoreCase = false; -var unicode = false; -function processCharacterClass(characterClassItem) { - var set = regenerate(); - var body = characterClassItem.body.forEach(function(item) { - switch (item.type) { - case 'value': - set.add(item.codePoint); - if (ignoreCase && unicode) { - var folded = caseFold(item.codePoint); - if (folded) { - set.add(folded); - } - } - break; - case 'characterClassRange': - var min = item.min.codePoint; - var max = item.max.codePoint; - set.addRange(min, max); - if (ignoreCase && unicode) { - set.iuAddRange(min, max); - } - break; - case 'characterClassEscape': - set.add(getCharacterClassEscapeSet(item.value)); - break; - // The `default` clause is only here as a safeguard; it should never be - // reached. Code coverage tools should ignore it. - /* istanbul ignore next */ - default: - throw Error('Unknown term type: ' + item.type); - } - }); - if (characterClassItem.negative) { - set = (unicode ? UNICODE_SET : BMP_SET).clone().remove(set); - } - update(characterClassItem, set.toString()); - return characterClassItem; -} - -function processTerm(item) { - switch (item.type) { - case 'dot': - update( - item, - (unicode ? DOT_SET_UNICODE : DOT_SET).toString() - ); - break; - case 'characterClass': - item = processCharacterClass(item); - break; - case 'characterClassEscape': - update( - item, - getCharacterClassEscapeSet(item.value).toString() - ); - break; - case 'alternative': - case 'disjunction': - case 'group': - case 'quantifier': - item.body = item.body.map(processTerm); - break; - case 'value': - var codePoint = item.codePoint; - var set = regenerate(codePoint); - if (ignoreCase && unicode) { - var folded = caseFold(codePoint); - if (folded) { - set.add(folded); - } - } - update(item, set.toString()); - break; - case 'anchor': - case 'empty': - case 'group': - case 'reference': - // Nothing to do here. - break; - // The `default` clause is only here as a safeguard; it should never be - // reached. Code coverage tools should ignore it. - /* istanbul ignore next */ - default: - throw Error('Unknown term type: ' + item.type); - } - return item; -}; + if (res = matchReg(/^[^\\\]-]/)) { + return createCharacter(res[0]); + } else if (match('\\')) { + res = parseClassEscape(); -module.exports = function(pattern, flags) { - var tree = parse(pattern, flags); - ignoreCase = flags ? flags.indexOf('i') > -1 : false; - unicode = flags ? flags.indexOf('u') > -1 : false; - assign(tree, processTerm(tree)); - return generate(tree); -}; + if (!res) { + bail('classEscape'); + } -},{"./data/character-class-escape-sets.js":535,"./data/iu-mappings.json":536,"regenerate":526,"regjsgen":538,"regjsparser":539}],538:[function(require,module,exports){ -(function (global){ -/*! - * RegJSGen - * Copyright 2014 Benjamin Tan - * Available under MIT license - */ -;(function() { - 'use strict'; + return parseUnicodeSurrogatePairEscape(res); + } + } - /** Used to determine if values are of the language type `Object` */ - var objectTypes = { - 'function': true, - 'object': true - }; + function bail(message, details, from, to) { + from = from == null ? pos : from; + to = to == null ? from : to; + var contextStart = Math.max(0, from - 10); + var contextEnd = Math.min(to + 10, str.length); // Output a bit of context and a line pointing to where our error is. + // + // We are assuming that there are no actual newlines in the content as this is a regular expression. - /** Used as a reference to the global object */ - var root = (objectTypes[typeof window] && window) || this; + var context = ' ' + str.substring(contextStart, contextEnd); + var pointer = ' ' + new Array(from - contextStart + 1).join(' ') + '^'; + throw SyntaxError(message + ' at position ' + from + (details ? ': ' + details : '') + '\n' + context + '\n' + pointer); + } - /** Backup possible global object */ - var oldRoot = root; + var backrefDenied = []; + var closedCaptureCounter = 0; + var firstIteration = true; + var hasUnicodeFlag = (flags || "").indexOf("u") !== -1; + var pos = 0; // Convert the input to a string and treat the empty string special. - /** Detect free variable `exports` */ - var freeExports = objectTypes[typeof exports] && exports; + str = String(str); - /** Detect free variable `module` */ - var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + if (str === '') { + str = '(?:)'; + } - /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ - var freeGlobal = freeExports && freeModule && typeof global == 'object' && global; - if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { - root = freeGlobal; - } + var result = parseDisjunction(); - /*--------------------------------------------------------------------------*/ + if (result.range[1] !== str.length) { + bail('Could not parse entire input - got stuck', '', result.range[1]); + } // The spec requires to interpret the `\2` in `/\2()()/` as backreference. + // As the parser collects the number of capture groups as the string is + // parsed it is impossible to make these decisions at the point when the + // `\2` is handled. In case the local decision turns out to be wrong after + // the parsing has finished, the input string is parsed a second time with + // the total number of capture groups set. + // + // SEE: https://github.com/jviereck/regjsparser/issues/70 - /*! Based on https://mths.be/fromcodepoint v0.2.0 by @mathias */ - var stringFromCharCode = String.fromCharCode; - var floor = Math.floor; - function fromCodePoint() { - var MAX_SIZE = 0x4000; - var codeUnits = []; - var highSurrogate; - var lowSurrogate; - var index = -1; - var length = arguments.length; - if (!length) { - return ''; - } - var result = ''; - while (++index < length) { - var codePoint = Number(arguments[index]); - if ( - !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` - codePoint < 0 || // not a valid Unicode code point - codePoint > 0x10FFFF || // not a valid Unicode code point - floor(codePoint) != codePoint // not an integer - ) { - throw RangeError('Invalid code point: ' + codePoint); - } - if (codePoint <= 0xFFFF) { - // BMP code point - codeUnits.push(codePoint); - } else { - // Astral code point; split in surrogate halves - // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - codePoint -= 0x10000; - highSurrogate = (codePoint >> 10) + 0xD800; - lowSurrogate = (codePoint % 0x400) + 0xDC00; - codeUnits.push(highSurrogate, lowSurrogate); - } - if (index + 1 == length || codeUnits.length > MAX_SIZE) { - result += stringFromCharCode.apply(null, codeUnits); - codeUnits.length = 0; + for (var i = 0; i < backrefDenied.length; i++) { + if (backrefDenied[i] <= closedCaptureCounter) { + // Parse the input a second time. + pos = 0; + firstIteration = false; + return parseDisjunction(); } } + return result; } - function assertType(type, expected) { - if (expected.indexOf('|') == -1) { - if (type == expected) { - return; - } + var regjsparser = { + parse: parse + }; - throw Error('Invalid node type: ' + type); - } + if (typeof module !== 'undefined' && module.exports) { + module.exports = regjsparser; + } else { + window.regjsparser = regjsparser; + } +})(); - expected = assertType.hasOwnProperty(expected) - ? assertType[expected] - : (assertType[expected] = RegExp('^(?:' + expected + ')$')); +},{}],1069:[function(require,module,exports){ +"use strict"; - if (expected.test(type)) { - return; - } +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer'); - throw Error('Invalid node type: ' + type); +var Buffer = buffer.Buffer; // alternative to using Object.keys for old browsers + +function copyProps(src, dst) { + for (var key in src) { + dst[key] = src[key]; } +} - /*--------------------------------------------------------------------------*/ +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer; +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports); + exports.Buffer = SafeBuffer; +} - function generate(node) { - var type = node.type; +function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length); +} // Copy static methods from Buffer - if (generate.hasOwnProperty(type) && typeof generate[type] == 'function') { - return generate[type](node); - } - throw Error('Invalid node type: ' + type); +copyProps(Buffer, SafeBuffer); + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number'); } - /*--------------------------------------------------------------------------*/ + return Buffer(arg, encodingOrOffset, length); +}; - function generateAlternative(node) { - assertType(node.type, 'alternative'); +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number'); + } - var terms = node.body, - length = terms ? terms.length : 0; + var buf = Buffer(size); - if (length == 1) { - return generateTerm(terms[0]); + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding); } else { - var i = -1, - result = ''; - - while (++i < length) { - result += generateTerm(terms[i]); - } - - return result; + buf.fill(fill); } + } else { + buf.fill(0); } - function generateAnchor(node) { - assertType(node.type, 'anchor'); + return buf; +}; - switch (node.kind) { - case 'start': - return '^'; - case 'end': - return '$'; - case 'boundary': - return '\\b'; - case 'not-boundary': - return '\\B'; - default: - throw Error('Invalid assertion'); - } +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number'); } - function generateAtom(node) { - assertType(node.type, 'anchor|characterClass|characterClassEscape|dot|group|reference|value'); + return Buffer(size); +}; - return generate(node); +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number'); } - function generateCharacterClass(node) { - assertType(node.type, 'characterClass'); - - var classRanges = node.body, - length = classRanges ? classRanges.length : 0; + return buffer.SlowBuffer(size); +}; - var i = -1, - result = '['; +},{"buffer":289}],1070:[function(require,module,exports){ +(function (process){ +"use strict"; - if (node.negative) { - result += '^'; - } +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - while (++i < length) { - result += generateClassAtom(classRanges[i]); - } +exports = module.exports = SemVer; +var debug; +/* istanbul ignore next */ - result += ']'; +if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function debug() { + var args = Array.prototype.slice.call(arguments, 0); + args.unshift('SEMVER'); + console.log.apply(console, args); + }; +} else { + debug = function debug() {}; +} // Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. + + +exports.SEMVER_SPEC_VERSION = '2.0.0'; +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ +9007199254740991; // Max safe segment length for coercion. + +var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re + +var re = exports.re = []; +var src = exports.src = []; +var R = 0; // The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')'; +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')'; +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. - return result; - } +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. - function generateCharacterClassEscape(node) { - assertType(node.type, 'characterClassEscape'); +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. - return '\\' + node.value; +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?'; +src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. + +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?'; +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. + +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?'; +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?'; +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion. +// Extract anything that could conceivably be a part of a valid semver + +var COERCE = R++; +src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges. +// Meaning is "reasonably at or greater than" + +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges. +// Meaning is "at least and backwards compatible with" + +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version" + +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` + +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag + +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. + +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$'; +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all. + +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. + +for (var i = 0; i < R; i++) { + debug(i, src[i]); + + if (!re[i]) { + re[i] = new RegExp(src[i]); } +} - function generateCharacterClassRange(node) { - assertType(node.type, 'characterClassRange'); - - var min = node.min, - max = node.max; - - if (min.type == 'characterClassRange' || max.type == 'characterClassRange') { - throw Error('Invalid character class range'); - } +exports.parse = parse; - return generateClassAtom(min) + '-' + generateClassAtom(max); +function parse(version, options) { + if (!options || _typeof(options) !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; } - function generateClassAtom(node) { - assertType(node.type, 'anchor|characterClassEscape|characterClassRange|dot|value'); - - return generate(node); + if (version instanceof SemVer) { + return version; } - function generateDisjunction(node) { - assertType(node.type, 'disjunction'); + if (typeof version !== 'string') { + return null; + } - var body = node.body, - length = body ? body.length : 0; + if (version.length > MAX_LENGTH) { + return null; + } - if (length == 0) { - throw Error('No body'); - } else if (length == 1) { - return generate(body[0]); - } else { - var i = -1, - result = ''; + var r = options.loose ? re[LOOSE] : re[FULL]; - while (++i < length) { - if (i != 0) { - result += '|'; - } - result += generate(body[i]); - } + if (!r.test(version)) { + return null; + } - return result; - } + try { + return new SemVer(version, options); + } catch (er) { + return null; } +} - function generateDot(node) { - assertType(node.type, 'dot'); +exports.valid = valid; - return '.'; - } +function valid(version, options) { + var v = parse(version, options); + return v ? v.version : null; +} - function generateGroup(node) { - assertType(node.type, 'group'); +exports.clean = clean; - var result = '('; +function clean(version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null; +} - switch (node.behavior) { - case 'normal': - break; - case 'ignore': - result += '?:'; - break; - case 'lookahead': - result += '?='; - break; - case 'negativeLookahead': - result += '?!'; - break; - default: - throw Error('Invalid behaviour: ' + node.behaviour); - } +exports.SemVer = SemVer; - var body = node.body, - length = body ? body.length : 0; +function SemVer(version, options) { + if (!options || _typeof(options) !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } - if (length == 1) { - result += generate(body[0]); + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version; } else { - var i = -1; - - while (++i < length) { - result += generate(body[i]); - } + version = version.version; } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } - result += ')'; + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters'); + } - return result; + if (!(this instanceof SemVer)) { + return new SemVer(version, options); } - function generateQuantifier(node) { - assertType(node.type, 'quantifier'); + debug('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]); - var quantifier = '', - min = node.min, - max = node.max; + if (!m) { + throw new TypeError('Invalid Version: ' + version); + } - switch (max) { - case undefined: - case null: - switch (min) { - case 0: - quantifier = '*' - break; - case 1: - quantifier = '+'; - break; - default: - quantifier = '{' + min + ',}'; - break; - } - break; - default: - if (min == max) { - quantifier = '{' + min + '}'; - } - else if (min == 0 && max == 1) { - quantifier = '?'; - } else { - quantifier = '{' + min + ',' + max + '}'; - } - break; - } + this.raw = version; // these are actually numbers - if (!node.greedy) { - quantifier += '?'; - } + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; - return generateAtom(node.body[0]) + quantifier; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version'); } - function generateReference(node) { - assertType(node.type, 'reference'); - - return '\\' + node.matchIndex; + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version'); } - function generateTerm(node) { - assertType(node.type, 'anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value'); - - return generate(node); - } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version'); + } // numberify any prerelease numeric ids - function generateValue(node) { - assertType(node.type, 'value'); - var kind = node.kind, - codePoint = node.codePoint; + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; - switch (kind) { - case 'controlLetter': - return '\\c' + fromCodePoint(codePoint + 64); - case 'hexadecimalEscape': - return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2); - case 'identifier': - return '\\' + fromCodePoint(codePoint); - case 'null': - return '\\' + codePoint; - case 'octal': - return '\\' + codePoint.toString(8); - case 'singleEscape': - switch (codePoint) { - case 0x0008: - return '\\b'; - case 0x009: - return '\\t'; - case 0x00A: - return '\\n'; - case 0x00B: - return '\\v'; - case 0x00C: - return '\\f'; - case 0x00D: - return '\\r'; - default: - throw Error('Invalid codepoint: ' + codePoint); + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; } - case 'symbol': - return fromCodePoint(codePoint); - case 'unicodeEscape': - return '\\u' + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4); - case 'unicodeCodePointEscape': - return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; - default: - throw Error('Unsupported node kind: ' + kind); - } - } + } - /*--------------------------------------------------------------------------*/ + return id; + }); + } - generate.alternative = generateAlternative; - generate.anchor = generateAnchor; - generate.characterClass = generateCharacterClass; - generate.characterClassEscape = generateCharacterClassEscape; - generate.characterClassRange = generateCharacterClassRange; - generate.disjunction = generateDisjunction; - generate.dot = generateDot; - generate.group = generateGroup; - generate.quantifier = generateQuantifier; - generate.reference = generateReference; - generate.value = generateValue; + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} - /*--------------------------------------------------------------------------*/ +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch; - // export regjsgen - // some AMD build optimizers, like r.js, check for condition patterns like the following: - if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { - // define as an anonymous module so, through path mapping, it can be aliased - define(function() { - return { - 'generate': generate - }; - }); - } - // check for `exports` after `define` in case a build optimizer adds an `exports` object - else if (freeExports && freeModule) { - // in Narwhal, Node.js, Rhino -require, or RingoJS - freeExports.generate = generate; - } - // in a browser or Rhino - else { - root.regjsgen = { - 'generate': generate - }; + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.'); } -}.call(this)); -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],539:[function(require,module,exports){ -// regjsparser -// -// ================================================================== -// -// See ECMA-262 Standard: 15.10.1 -// -// NOTE: The ECMA-262 standard uses the term "Assertion" for /^/. Here the -// term "Anchor" is used. -// -// Pattern :: -// Disjunction -// -// Disjunction :: -// Alternative -// Alternative | Disjunction -// -// Alternative :: -// [empty] -// Alternative Term -// -// Term :: -// Anchor -// Atom -// Atom Quantifier -// -// Anchor :: -// ^ -// $ -// \ b -// \ B -// ( ? = Disjunction ) -// ( ? ! Disjunction ) -// -// Quantifier :: -// QuantifierPrefix -// QuantifierPrefix ? -// -// QuantifierPrefix :: -// * -// + -// ? -// { DecimalDigits } -// { DecimalDigits , } -// { DecimalDigits , DecimalDigits } -// -// Atom :: -// PatternCharacter -// . -// \ AtomEscape -// CharacterClass -// ( Disjunction ) -// ( ? : Disjunction ) -// -// PatternCharacter :: -// SourceCharacter but not any of: ^ $ \ . * + ? ( ) [ ] { } | -// -// AtomEscape :: -// DecimalEscape -// CharacterEscape -// CharacterClassEscape -// -// CharacterEscape[U] :: -// ControlEscape -// c ControlLetter -// HexEscapeSequence -// RegExpUnicodeEscapeSequence[?U] (ES6) -// IdentityEscape[?U] -// -// ControlEscape :: -// one of f n r t v -// ControlLetter :: -// one of -// a b c d e f g h i j k l m n o p q r s t u v w x y z -// A B C D E F G H I J K L M N O P Q R S T U V W X Y Z -// -// IdentityEscape :: -// SourceCharacter but not IdentifierPart -// -// -// -// DecimalEscape :: -// DecimalIntegerLiteral [lookahead ∉ DecimalDigit] -// -// CharacterClassEscape :: -// one of d D s S w W -// -// CharacterClass :: -// [ [lookahead ∉ {^}] ClassRanges ] -// [ ^ ClassRanges ] -// -// ClassRanges :: -// [empty] -// NonemptyClassRanges -// -// NonemptyClassRanges :: -// ClassAtom -// ClassAtom NonemptyClassRangesNoDash -// ClassAtom - ClassAtom ClassRanges -// -// NonemptyClassRangesNoDash :: -// ClassAtom -// ClassAtomNoDash NonemptyClassRangesNoDash -// ClassAtomNoDash - ClassAtom ClassRanges -// -// ClassAtom :: -// - -// ClassAtomNoDash -// -// ClassAtomNoDash :: -// SourceCharacter but not one of \ or ] or - -// \ ClassEscape -// -// ClassEscape :: -// DecimalEscape -// b -// CharacterEscape -// CharacterClassEscape + return this.version; +}; -(function() { +SemVer.prototype.toString = function () { + return this.version; +}; - function parse(str, flags) { - function addRaw(node) { - node.raw = str.substring(node.range[0], node.range[1]); - return node; - } +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other); - function updateRawStart(node, start) { - node.range[0] = start; - return addRaw(node); - } + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } - function createAnchor(kind, rawLength) { - return addRaw({ - type: 'anchor', - kind: kind, - range: [ - pos - rawLength, - pos - ] - }); - } + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); +}; - function createValue(kind, codePoint, from, to) { - return addRaw({ - type: 'value', - kind: kind, - codePoint: codePoint, - range: [from, to] - }); - } +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } // NOT having a prerelease is > having one - function createEscaped(kind, codePoint, value, fromOffset) { - fromOffset = fromOffset || 0; - return createValue(kind, codePoint, pos - (value.length + fromOffset), pos); - } - function createCharacter(matches) { - var _char = matches[0]; - var first = _char.charCodeAt(0); - if (hasUnicodeFlag) { - var second; - if (_char.length === 1 && first >= 0xD800 && first <= 0xDBFF) { - second = lookahead().charCodeAt(0); - if (second >= 0xDC00 && second <= 0xDFFF) { - // Unicode surrogate pair - pos++; - return createValue( - 'symbol', - (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000, - pos - 2, pos); - } - } - } - return createValue('symbol', first, pos - 1, pos); - } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } - function createDisjunction(alternatives, from, to) { - return addRaw({ - type: 'disjunction', - body: alternatives, - range: [ - from, - to - ] - }); - } + var i = 0; - function createDot() { - return addRaw({ - type: 'dot', - range: [ - pos - 1, - pos - ] - }); - } + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); - function createCharacterClassEscape(value) { - return addRaw({ - type: 'characterClassEscape', - value: value, - range: [ - pos - 2, - pos - ] - }); + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); } + } while (++i); +}; // preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. - function createReference(matchIndex) { - return addRaw({ - type: 'reference', - matchIndex: parseInt(matchIndex, 10), - range: [ - pos - 1 - matchIndex.length, - pos - ] - }); - } - function createGroup(behavior, disjunction, from, to) { - return addRaw({ - type: 'group', - behavior: behavior, - body: disjunction, - range: [ - from, - to - ] - }); - } +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; - function createQuantifier(min, max, from, to) { - if (to == null) { - from = pos - 1; - to = pos; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); } - return addRaw({ - type: 'quantifier', - min: min, - max: max, - greedy: true, - body: null, // set later on - range: [ - from, - to - ] - }); - } + this.inc('pre', identifier); + break; - function createAlternative(terms, from, to) { - return addRaw({ - type: 'alternative', - body: terms, - range: [ - from, - to - ] - }); - } + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } - function createCharacterClass(classRanges, negative, from, to) { - return addRaw({ - type: 'characterClass', - body: classRanges, - negative: negative, - range: [ - from, - to - ] - }); - } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; - function createClassRange(min, max, from, to) { - // See 15.10.2.15: - if (min.codePoint > max.codePoint) { - bail('invalid range in character class', min.raw + '-' + max.raw, from, to); + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; } - return addRaw({ - type: 'characterClassRange', - min: min, - max: max, - range: [ - from, - to - ] - }); - } + this.patch = 0; + this.prerelease = []; + break; - function flattenBody(body) { - if (body.type === 'alternative') { - return body.body; - } else { - return [body]; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; } - } - function isEmpty(obj) { - return obj.type === 'empty'; - } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - function incr(amount) { - amount = (amount || 1); - var res = str.substring(pos, pos + amount); - pos += (amount || 1); - return res; - } + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + var i = this.prerelease.length; - function skip(value) { - if (!match(value)) { - bail('character', value); + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } } - } - function match(value) { - if (str.indexOf(value, pos) === pos) { - return incr(value.length); + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } } - } - function lookahead() { - return str[pos]; - } + break; - function current(value) { - return str.indexOf(value, pos) === pos; - } + default: + throw new Error('invalid increment argument: ' + release); + } - function next(value) { - return str[pos + 1] === value; + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; + +function inc(version, release, loose, identifier) { + if (typeof loose === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; + +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + var prefix = ''; + + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre'; + var defaultResult = 'prerelease'; } - function matchReg(regExp) { - var subStr = str.substring(pos); - var res = subStr.match(regExp); - if (res) { - res.range = []; - res.range[0] = pos; - incr(res[0].length); - res.range[1] = pos; + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key; + } } - return res; } - function parseDisjunction() { - // Disjunction :: - // Alternative - // Alternative | Disjunction - var res = [], from = pos; - res.push(parseAlternative()); + return defaultResult; // may be undefined + } +} - while (match('|')) { - res.push(parseAlternative()); - } +exports.compareIdentifiers = compareIdentifiers; +var numeric = /^[0-9]+$/; - if (res.length === 1) { - return res[0]; - } +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); - return createDisjunction(res, from, pos); - } + if (anum && bnum) { + a = +a; + b = +b; + } - function parseAlternative() { - var res = [], from = pos; - var term; + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; +} - // Alternative :: - // [empty] - // Alternative Term - while (term = parseTerm()) { - res.push(term); - } +exports.rcompareIdentifiers = rcompareIdentifiers; - if (res.length === 1) { - return res[0]; - } +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} - return createAlternative(res, from, pos); - } +exports.major = major; - function parseTerm() { - // Term :: - // Anchor - // Atom - // Atom Quantifier +function major(a, loose) { + return new SemVer(a, loose).major; +} - if (pos >= str.length || current('|') || current(')')) { - return null; /* Means: The term is empty */ - } +exports.minor = minor; - var anchor = parseAnchor(); +function minor(a, loose) { + return new SemVer(a, loose).minor; +} - if (anchor) { - return anchor; - } +exports.patch = patch; - var atom = parseAtom(); - if (!atom) { - bail('Expected atom'); - } - var quantifier = parseQuantifier() || false; - if (quantifier) { - quantifier.body = flattenBody(atom); - // The quantifier contains the atom. Therefore, the beginning of the - // quantifier range is given by the beginning of the atom. - updateRawStart(quantifier, atom.range[0]); - return quantifier; - } - return atom; - } +function patch(a, loose) { + return new SemVer(a, loose).patch; +} - function parseGroup(matchA, typeA, matchB, typeB) { - var type = null, from = pos; +exports.compare = compare; - if (match(matchA)) { - type = typeA; - } else if (match(matchB)) { - type = typeB; - } else { - return false; - } +function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); +} - var body = parseDisjunction(); - if (!body) { - bail('Expected disjunction'); - } - skip(')'); - var group = createGroup(type, flattenBody(body), from, pos); +exports.compareLoose = compareLoose; - if (type == 'normal') { - // Keep track of the number of closed groups. This is required for - // parseDecimalEscape(). In case the string is parsed a second time the - // value already holds the total count and no incrementation is required. - if (firstIteration) { - closedCaptureCounter++; - } - } - return group; - } +function compareLoose(a, b) { + return compare(a, b, true); +} - function parseAnchor() { - // Anchor :: - // ^ - // $ - // \ b - // \ B - // ( ? = Disjunction ) - // ( ? ! Disjunction ) - var res, from = pos; +exports.rcompare = rcompare; - if (match('^')) { - return createAnchor('start', 1 /* rawLength */); - } else if (match('$')) { - return createAnchor('end', 1 /* rawLength */); - } else if (match('\\b')) { - return createAnchor('boundary', 2 /* rawLength */); - } else if (match('\\B')) { - return createAnchor('not-boundary', 2 /* rawLength */); - } else { - return parseGroup('(?=', 'lookahead', '(?!', 'negativeLookahead'); - } - } +function rcompare(a, b, loose) { + return compare(b, a, loose); +} - function parseQuantifier() { - // Quantifier :: - // QuantifierPrefix - // QuantifierPrefix ? - // - // QuantifierPrefix :: - // * - // + - // ? - // { DecimalDigits } - // { DecimalDigits , } - // { DecimalDigits , DecimalDigits } +exports.sort = sort; - var res, from = pos; - var quantifier; - var min, max; +function sort(list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose); + }); +} - if (match('*')) { - quantifier = createQuantifier(0); - } - else if (match('+')) { - quantifier = createQuantifier(1); - } - else if (match('?')) { - quantifier = createQuantifier(0, 1); - } - else if (res = matchReg(/^\{([0-9]+)\}/)) { - min = parseInt(res[1], 10); - quantifier = createQuantifier(min, min, res.range[0], res.range[1]); - } - else if (res = matchReg(/^\{([0-9]+),\}/)) { - min = parseInt(res[1], 10); - quantifier = createQuantifier(min, undefined, res.range[0], res.range[1]); - } - else if (res = matchReg(/^\{([0-9]+),([0-9]+)\}/)) { - min = parseInt(res[1], 10); - max = parseInt(res[2], 10); - if (min > max) { - bail('numbers out of order in {} quantifier', '', from, pos); - } - quantifier = createQuantifier(min, max, res.range[0], res.range[1]); - } +exports.rsort = rsort; - if (quantifier) { - if (match('?')) { - quantifier.greedy = false; - quantifier.range[1] += 1; - } - } +function rsort(list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose); + }); +} - return quantifier; - } +exports.gt = gt; - function parseAtom() { - // Atom :: - // PatternCharacter - // . - // \ AtomEscape - // CharacterClass - // ( Disjunction ) - // ( ? : Disjunction ) +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} - var res; +exports.lt = lt; - // jviereck: allow ']', '}' here as well to be compatible with browser's - // implementations: ']'.match(/]/); - // if (res = matchReg(/^[^^$\\.*+?()[\]{}|]/)) { - if (res = matchReg(/^[^^$\\.*+?(){[|]/)) { - // PatternCharacter - return createCharacter(res); - } - else if (match('.')) { - // . - return createDot(); - } - else if (match('\\')) { - // \ AtomEscape - res = parseAtomEscape(); - if (!res) { - bail('atomEscape'); - } - return res; - } - else if (res = parseCharacterClass()) { - return res; - } - else { - // ( Disjunction ) - // ( ? : Disjunction ) - return parseGroup('(?:', 'ignore', '(', 'normal'); - } - } +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} - function parseUnicodeSurrogatePairEscape(firstEscape) { - if (hasUnicodeFlag) { - var first, second; - if (firstEscape.kind == 'unicodeEscape' && - (first = firstEscape.codePoint) >= 0xD800 && first <= 0xDBFF && - current('\\') && next('u') ) { - var prevPos = pos; - pos++; - var secondEscape = parseClassEscape(); - if (secondEscape.kind == 'unicodeEscape' && - (second = secondEscape.codePoint) >= 0xDC00 && second <= 0xDFFF) { - // Unicode surrogate pair - firstEscape.range[1] = secondEscape.range[1]; - firstEscape.codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - firstEscape.type = 'value'; - firstEscape.kind = 'unicodeCodePointEscape'; - addRaw(firstEscape); - } - else { - pos = prevPos; - } - } - } - return firstEscape; +exports.eq = eq; + +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; + +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; + +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; + +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; + +function cmp(a, op, b, loose) { + switch (op) { + case '===': + if (_typeof(a) === 'object') a = a.version; + if (_typeof(b) === 'object') b = b.version; + return a === b; + + case '!==': + if (_typeof(a) === 'object') a = a.version; + if (_typeof(b) === 'object') b = b.version; + return a !== b; + + case '': + case '=': + case '==': + return eq(a, b, loose); + + case '!=': + return neq(a, b, loose); + + case '>': + return gt(a, b, loose); + + case '>=': + return gte(a, b, loose); + + case '<': + return lt(a, b, loose); + + case '<=': + return lte(a, b, loose); + + default: + throw new TypeError('Invalid operator: ' + op); + } +} + +exports.Comparator = Comparator; + +function Comparator(comp, options) { + if (!options || _typeof(options) !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; } + } - function parseClassEscape() { - return parseAtomEscape(true); + if (!(this instanceof Comparator)) { + return new Comparator(comp, options); + } + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } + + debug('comp', this); +} + +var ANY = {}; + +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp); + } + + this.operator = m[1]; + + if (this.operator === '=') { + this.operator = ''; + } // if it literally is just '>' or '' then allow anything. + + + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } +}; + +Comparator.prototype.toString = function () { + return this.value; +}; + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY) { + return true; + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options); + } + + return cmp(version, this.operator, this.semver, this.options); +}; + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + if (!options || _typeof(options) !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + var rangeTmp; + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options); + return satisfies(this.value, rangeTmp, options); + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options); + return satisfies(comp.semver, rangeTmp, options); + } + + var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>'); + var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<'); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); + var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); + var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); + return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; +}; + +exports.Range = Range; + +function Range(range, options) { + if (!options || _typeof(options) !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new Range(range.raw, options); } + } - function parseAtomEscape(insideCharacterClass) { - // AtomEscape :: - // DecimalEscape - // CharacterEscape - // CharacterClassEscape + if (range instanceof Comparator) { + return new Range(range.value, options); + } - var res, from = pos; + if (!(this instanceof Range)) { + return new Range(range, options); + } - res = parseDecimalEscape(); - if (res) { - return res; + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or || + + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()); + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function () { + return this.range; +}; + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose; + range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` + + range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3` + + range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces + + range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options); + }, this).join(' ').split(/\s+/); + + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe); + }); + } + + set = set.map(function (comp) { + return new Comparator(comp, this.options); + }, this); + return set; +}; + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); +}; // Mostly just for testing and legacy API reasons + + +exports.toComparators = toComparators; + +function toComparators(range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} // comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. + + +function parseComparator(comp, options) { + debug('comp', comp, options); + comp = replaceCarets(comp, options); + debug('caret', comp); + comp = replaceTildes(comp, options); + debug('tildes', comp); + comp = replaceXRanges(comp, options); + debug('xrange', comp); + comp = replaceStars(comp, options); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} // ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 + + +function replaceTildes(comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options); + }).join(' '); +} + +function replaceTilde(comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } else if (pr) { + debug('replaceTilde pr', pr); + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0'; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; + } + + debug('tilde return', ret); + return ret; + }); +} // ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 + + +function replaceCarets(comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options); + }).join(' '); +} + +function replaceCaret(comp, options) { + debug('caret', comp, options); + var r = options.loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; } + } else if (pr) { + debug('replaceCaret pr', pr); - // For ClassEscape - if (insideCharacterClass) { - if (match('b')) { - // 15.10.2.19 - // The production ClassEscape :: b evaluates by returning the - // CharSet containing the one character (Unicode value 0008). - return createEscaped('singleEscape', 0x0008, '\\b'); - } else if (match('B')) { - bail('\\B not possible inside of CharacterClass', '', from); + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1); + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0'; + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0'; + } + } else { + debug('no pr'); + + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1); + } else { + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; } + } else { + ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0'; } + } - res = parseCharacterEscape(); + debug('caret return', ret); + return ret; + }); +} - return res; - } +function replaceXRanges(comp, options) { + debug('replaceXRanges', comp, options); + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options); + }).join(' '); +} +function replaceXRange(comp, options) { + comp = comp.trim(); + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; - function parseDecimalEscape() { - // DecimalEscape :: - // DecimalIntegerLiteral [lookahead ∉ DecimalDigit] - // CharacterClassEscape :: one of d D s S w W + if (gtlt === '=' && anyX) { + gtlt = ''; + } - var res, match; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } - if (res = matchReg(/^(?!0)\d+/)) { - match = res[0]; - var refIdx = parseInt(res[0], 10); - if (refIdx <= closedCaptureCounter) { - // If the number is smaller than the normal-groups found so - // far, then it is a reference... - return createReference(res[0]); - } else { - // ... otherwise it needs to be interpreted as a octal (if the - // number is in an octal format). If it is NOT octal format, - // then the slash is ignored and the number is matched later - // as normal characters. + p = 0; - // Recall the negative decision to decide if the input must be parsed - // a second time with the total normal-groups. - backrefDenied.push(refIdx); + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; - // Reset the position again, as maybe only parts of the previous - // matched numbers are actual octal numbers. E.g. in '019' only - // the '01' should be matched. - incr(-res[0].length); - if (res = matchReg(/^[0-7]{1,3}/)) { - return createEscaped('octal', parseInt(res[0], 8), res[0], 1); - } else { - // If we end up here, we have a case like /\91/. Then the - // first slash is to be ignored and the 9 & 1 to be treated - // like ordinary characters. Create a character for the - // first number only here - other number-characters - // (if available) will be matched later. - res = createCharacter(matchReg(/^[89]/)); - return updateRawStart(res, res.range[0] - 1); - } + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; } - } - // Only allow octal numbers in the following. All matched numbers start - // with a zero (if the do not, the previous if-branch is executed). - // If the number is not octal format and starts with zero (e.g. `091`) - // then only the zeros `0` is treated here and the `91` are ordinary - // characters. - // Example: - // /\091/.exec('\091')[0].length === 3 - else if (res = matchReg(/^[0-7]{1,3}/)) { - match = res[0]; - if (/^0{1,3}$/.test(match)) { - // If they are all zeros, then only take the first one. - return createEscaped('null', 0x0000, '0', match.length + 1); + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + + if (xm) { + M = +M + 1; } else { - return createEscaped('octal', parseInt(match, 8), match, 1); + m = +m + 1; } - } else if (res = matchReg(/^[dDsSwW]/)) { - return createCharacterClassEscape(res[0]); } - return false; + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; } - function parseCharacterEscape() { - // CharacterEscape :: - // ControlEscape - // c ControlLetter - // HexEscapeSequence - // UnicodeEscapeSequence - // IdentityEscape + debug('xRange return', ret); + return ret; + }); +} // Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. - var res; - if (res = matchReg(/^[fnrtv]/)) { - // ControlEscape - var codePoint = 0; - switch (res[0]) { - case 't': codePoint = 0x009; break; - case 'n': codePoint = 0x00A; break; - case 'v': codePoint = 0x00B; break; - case 'f': codePoint = 0x00C; break; - case 'r': codePoint = 0x00D; break; - } - return createEscaped('singleEscape', codePoint, '\\' + res[0]); - } else if (res = matchReg(/^c([a-zA-Z])/)) { - // c ControlLetter - return createEscaped('controlLetter', res[1].charCodeAt(0) % 32, res[1], 2); - } else if (res = matchReg(/^x([0-9a-fA-F]{2})/)) { - // HexEscapeSequence - return createEscaped('hexadecimalEscape', parseInt(res[1], 16), res[1], 2); - } else if (res = matchReg(/^u([0-9a-fA-F]{4})/)) { - // UnicodeEscapeSequence - return parseUnicodeSurrogatePairEscape( - createEscaped('unicodeEscape', parseInt(res[1], 16), res[1], 2) - ); - } else if (hasUnicodeFlag && (res = matchReg(/^u\{([0-9a-fA-F]+)\}/))) { - // RegExpUnicodeEscapeSequence (ES6 Unicode code point escape) - return createEscaped('unicodeCodePointEscape', parseInt(res[1], 16), res[1], 4); - } else { - // IdentityEscape - return parseIdentityEscape(); - } - } - // Taken from the Esprima parser. - function isIdentifierPart(ch) { - // Generated by `tools/generate-identifier-regex.js`. - var NonAsciiIdentifierPart = new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'); +function replaceStars(comp, options) { + debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets! - return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) - (ch >= 65 && ch <= 90) || // A..Z - (ch >= 97 && ch <= 122) || // a..z - (ch >= 48 && ch <= 57) || // 0..9 - (ch === 92) || // \ (backslash) - ((ch >= 0x80) && NonAsciiIdentifierPart.test(String.fromCharCode(ch))); - } + return comp.trim().replace(re[STAR], ''); +} // This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 - function parseIdentityEscape() { - // IdentityEscape :: - // SourceCharacter but not IdentifierPart - // - // - var ZWJ = '\u200C'; - var ZWNJ = '\u200D'; +function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = '>=' + fM + '.0.0'; + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0'; + } else { + from = '>=' + from; + } - var tmp; + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0'; + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0'; + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + } else { + to = '<=' + to; + } - if (!isIdentifierPart(lookahead())) { - tmp = incr(); - return createEscaped('identifier', tmp.charCodeAt(0), tmp, 1); - } + return (from + ' ' + to).trim(); +} // if ANY of the sets match ALL of its comparators, then pass - if (match(ZWJ)) { - // - return createEscaped('identifier', 0x200C, ZWJ); - } else if (match(ZWNJ)) { - // - return createEscaped('identifier', 0x200D, ZWNJ); - } - return null; - } +Range.prototype.test = function (version) { + if (!version) { + return false; + } - function parseCharacterClass() { - // CharacterClass :: - // [ [lookahead ∉ {^}] ClassRanges ] - // [ ^ ClassRanges ] + if (typeof version === 'string') { + version = new SemVer(version, this.options); + } - var res, from = pos; - if (res = matchReg(/^\[\^/)) { - res = parseClassRanges(); - skip(']'); - return createCharacterClass(res, true, from, pos); - } else if (match('[')) { - res = parseClassRanges(); - skip(']'); - return createCharacterClass(res, false, from, pos); - } + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true; + } + } - return null; + return false; +}; + +function testSet(set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false; } + } - function parseClassRanges() { - // ClassRanges :: - // [empty] - // NonemptyClassRanges + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver); - var res; - if (current(']')) { - // Empty array means nothing insinde of the ClassRange. - return []; - } else { - res = parseNonemptyClassRanges(); - if (!res) { - bail('nonEmptyClassRanges'); - } - return res; + if (set[i].semver === ANY) { + continue; } - } - function parseHelperClassRanges(atom) { - var from, to, res; - if (current('-') && !next(']')) { - // ClassAtom - ClassAtom ClassRanges - skip('-'); + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; - res = parseClassAtom(); - if (!res) { - bail('classAtom'); - } - to = pos; - var classRanges = parseClassRanges(); - if (!classRanges) { - bail('classRanges'); - } - from = atom.range[0]; - if (classRanges.type === 'empty') { - return [createClassRange(atom, res, from, to)]; + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; } - return [createClassRange(atom, res, from, to)].concat(classRanges); } + } // Version has a -pre, but it's not one of the ones we like. - res = parseNonemptyClassRangesNoDash(); - if (!res) { - bail('nonEmptyClassRangesNoDash'); - } - return [atom].concat(res); - } + return false; + } - function parseNonemptyClassRanges() { - // NonemptyClassRanges :: - // ClassAtom - // ClassAtom NonemptyClassRangesNoDash - // ClassAtom - ClassAtom ClassRanges + return true; +} - var atom = parseClassAtom(); - if (!atom) { - bail('classAtom'); - } +exports.satisfies = satisfies; - if (current(']')) { - // ClassAtom - return [atom]; - } +function satisfies(version, range, options) { + try { + range = new Range(range, options); + } catch (er) { + return false; + } - // ClassAtom NonemptyClassRangesNoDash - // ClassAtom - ClassAtom ClassRanges - return parseHelperClassRanges(atom); - } + return range.test(version); +} - function parseNonemptyClassRangesNoDash() { - // NonemptyClassRangesNoDash :: - // ClassAtom - // ClassAtomNoDash NonemptyClassRangesNoDash - // ClassAtomNoDash - ClassAtom ClassRanges +exports.maxSatisfying = maxSatisfying; - var res = parseClassAtom(); - if (!res) { - bail('classAtom'); - } - if (current(']')) { - // ClassAtom - return res; - } +function maxSatisfying(versions, range, options) { + var max = null; + var maxSV = null; - // ClassAtomNoDash NonemptyClassRangesNoDash - // ClassAtomNoDash - ClassAtom ClassRanges - return parseHelperClassRanges(res); - } + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null; + } - function parseClassAtom() { - // ClassAtom :: - // - - // ClassAtomNoDash - if (match('-')) { - return createCharacter('-'); - } else { - return parseClassAtomNoDash(); + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer(max, options); } } + }); + return max; +} - function parseClassAtomNoDash() { - // ClassAtomNoDash :: - // SourceCharacter but not one of \ or ] or - - // \ ClassEscape +exports.minSatisfying = minSatisfying; - var res; - if (res = matchReg(/^[^\\\]-]/)) { - return createCharacter(res[0]); - } else if (match('\\')) { - res = parseClassEscape(); - if (!res) { - bail('classEscape'); - } +function minSatisfying(versions, range, options) { + var min = null; + var minSV = null; - return parseUnicodeSurrogatePairEscape(res); + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null; + } + + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer(min, options); } } + }); + return min; +} - function bail(message, details, from, to) { - from = from == null ? pos : from; - to = to == null ? from : to; +exports.minVersion = minVersion; - var contextStart = Math.max(0, from - 10); - var contextEnd = Math.min(to + 10, str.length); +function minVersion(range, loose) { + range = new Range(range, loose); + var minver = new SemVer('0.0.0'); - // Output a bit of context and a line pointing to where our error is. - // - // We are assuming that there are no actual newlines in the content as this is a regular expression. - var context = ' ' + str.substring(contextStart, contextEnd); - var pointer = ' ' + new Array(from - contextStart + 1).join(' ') + '^'; + if (range.test(minver)) { + return minver; + } - throw SyntaxError(message + ' at position ' + from + (details ? ': ' + details : '') + '\n' + context + '\n' + pointer); - } + minver = new SemVer('0.0.0-0'); - var backrefDenied = []; - var closedCaptureCounter = 0; - var firstIteration = true; - var hasUnicodeFlag = (flags || "").indexOf("u") !== -1; - var pos = 0; + if (range.test(minver)) { + return minver; + } - // Convert the input to a string and treat the empty string special. - str = String(str); - if (str === '') { - str = '(?:)'; - } + minver = null; - var result = parseDisjunction(); + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version); - if (result.range[1] !== str.length) { - bail('Could not parse entire input - got stuck', '', result.range[1]); - } + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } - // The spec requires to interpret the `\2` in `/\2()()/` as backreference. - // As the parser collects the number of capture groups as the string is - // parsed it is impossible to make these decisions at the point when the - // `\2` is handled. In case the local decision turns out to be wrong after - // the parsing has finished, the input string is parsed a second time with - // the total number of capture groups set. - // - // SEE: https://github.com/jviereck/regjsparser/issues/70 - for (var i = 0; i < backrefDenied.length; i++) { - if (backrefDenied[i] <= closedCaptureCounter) { - // Parse the input a second time. - pos = 0; - firstIteration = false; - return parseDisjunction(); + compver.raw = compver.format(); + + /* fallthrough */ + + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver; + } + + break; + + case '<': + case '<=': + /* Ignore maximum versions */ + break; + + /* istanbul ignore next */ + + default: + throw new Error('Unexpected operation: ' + comparator.operator); } - } + }); + } - return result; + if (minver && range.test(minver)) { + return minver; } - var regjsparser = { - parse: parse - }; + return null; +} - if (typeof module !== 'undefined' && module.exports) { - module.exports = regjsparser; - } else { - window.regjsparser = regjsparser; +exports.validRange = validRange; + +function validRange(range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*'; + } catch (er) { + return null; } +} // Determine if version is less than all the versions possible in the range -}()); -},{}],540:[function(require,module,exports){ -'use strict'; -var isFinite = require('is-finite'); +exports.ltr = ltr; -module.exports = function (str, n) { - if (typeof str !== 'string') { - throw new TypeError('Expected `input` to be a string'); - } +function ltr(version, range, options) { + return outside(version, range, '<', options); +} // Determine if version is greater than all the versions possible in the range. - if (n < 0 || !isFinite(n)) { - throw new TypeError('Expected `count` to be a positive finite number'); - } - var ret = ''; +exports.gtr = gtr; - do { - if (n & 1) { - ret += str; - } +function gtr(version, range, options) { + return outside(version, range, '>', options); +} - str += str; - } while ((n >>= 1)); +exports.outside = outside; - return ret; -}; +function outside(version, range, hilo, options) { + version = new SemVer(version, options); + range = new Range(range, options); + var gtfn, ltefn, ltfn, comp, ecomp; -},{"is-finite":293}],541:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - var isExtendedLengthPath = /^\\\\\?\\/.test(str); - var hasNonAscii = /[^\x00-\x80]+/.test(str); + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; - if (isExtendedLengthPath || hasNonAscii) { - return str; - } + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; - return str.replace(/\\/g, '/'); -}; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } // If it satisifes the range it is not outside + + + if (satisfies(version, range, options)) { + return false; + } // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + var high = null; + var low = null; + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0'); + } + + high = high || comparator; + low = low || comparator; + + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); // If the edge version comparator has a operator then our version + // isn't outside it + + if (high.operator === comp || high.operator === ecomp) { + return false; + } // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + + + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + + return true; +} + +exports.prerelease = prerelease; + +function prerelease(version, options) { + var parsed = parse(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; +} + +exports.intersects = intersects; + +function intersects(r1, r2, options) { + r1 = new Range(r1, options); + r2 = new Range(r2, options); + return r1.intersects(r2); +} + +exports.coerce = coerce; + +function coerce(version) { + if (version instanceof SemVer) { + return version; + } + + if (typeof version !== 'string') { + return null; + } + + var match = version.match(re[COERCE]); + + if (match == null) { + return null; + } + + return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0')); +} + +}).call(this,require('_process')) +},{"_process":1054}],1071:[function(require,module,exports){ +"use strict"; -},{}],542:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ - var util = require('./util'); + var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; - /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ + function ArraySet() { this._array = []; this._set = hasNativeMap ? new Map() : Object.create(null); } - /** * Static method for creating ArraySet instances from an existing array. */ + + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } + return set; }; - /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ + + ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; - /** * Add the given string to this set. * * @param String aStr */ + + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } + if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); @@ -52121,12 +118317,13 @@ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { } } }; - /** * Is the given string a member of this set? * * @param String aStr */ + + ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); @@ -52135,20 +118332,23 @@ ArraySet.prototype.has = function ArraySet_has(aStr) { return has.call(this._set, sStr); } }; - /** * What is the index of the given string in the array? * * @param String aStr */ + + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); + if (idx >= 0) { - return idx; + return idx; } } else { var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { return this._set[sStr]; } @@ -52156,32 +118356,38 @@ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { throw new Error('"' + aStr + '" is not in the set.'); }; - /** * What is the element at the given index? * * @param Number aIdx */ + + ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } + throw new Error('No element indexed by ' + aIdx); }; - /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ + + ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; -},{"./util":551}],543:[function(require,module,exports){ +},{"./util":1080}],1072:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: @@ -52217,10 +118423,7 @@ exports.ArraySet = ArraySet; * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - -var base64 = require('./base64'); - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable +var base64 = require('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more @@ -52232,70 +118435,68 @@ var base64 = require('./base64'); // V V // 101011 -var VLQ_BASE_SHIFT = 5; -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; +var VLQ_BASE_SHIFT = 5; // binary: 100000 -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; +var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ + function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; + return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; } - /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ + + function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; + return isNegative ? -shifted : shifted; } - /** * Returns the base 64 VLQ encoded value. */ + + exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; - var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } + encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; - /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ + + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; @@ -52308,6 +118509,7 @@ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { } digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } @@ -52322,86 +118524,94 @@ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { aOutParam.rest = aIndex; }; -},{"./base64":544}],544:[function(require,module,exports){ +},{"./base64":1073}],1073:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ - var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ + exports.encode = function (number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } + throw new TypeError("Must be between 0 and 63: " + number); }; - /** * Decode a single base 64 character code digit to an integer. Returns -1 on * failure. */ + + exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' + var bigA = 65; // 'A' + + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' - var littleA = 97; // 'a' var littleZ = 122; // 'z' - var zero = 48; // '0' - var nine = 57; // '9' + var zero = 48; // '0' + + var nine = 57; // '9' + + var plus = 43; // '+' - var plus = 43; // '+' - var slash = 47; // '/' + var slash = 47; // '/' var littleOffset = 26; - var numberOffset = 52; + var numberOffset = 52; // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } + return charCode - bigA; + } // 26 - 51: abcdefghijklmnopqrstuvwxyz + - // 26 - 51: abcdefghijklmnopqrstuvwxyz if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } + return charCode - littleA + littleOffset; + } // 52 - 61: 0123456789 + - // 52 - 61: 0123456789 if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } + return charCode - zero + numberOffset; + } // 62: + + - // 62: + if (charCode == plus) { return 62; - } + } // 63: / + - // 63: / if (charCode == slash) { return 63; - } + } // Invalid base64 digit. + - // Invalid base64 digit. return -1; }; -},{}],545:[function(require,module,exports){ +},{}],1074:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ - exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; - /** * Recursive implementation of binary search. * @@ -52415,6 +118625,7 @@ exports.LEAST_UPPER_BOUND = 2; * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // @@ -52427,33 +118638,32 @@ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { // Found the element we are looking for. return mid; - } - else if (cmp > 0) { + } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if + } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. + + if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } - } - else { + } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } + } // we are in termination case (3) or (2) and return the appropriate thing. + - // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { @@ -52461,7 +118671,6 @@ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { } } } - /** * This is an implementation of binary search which will always try and return * the index of the closest element if there is no exact hit. This is because @@ -52480,92 +118689,103 @@ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { * searching for, respectively, if the exact element cannot be found. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ + + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { return -1; - } - - // We have found either the exact element, or the next-closest element than + } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. + + while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } + --index; } return index; }; -},{}],546:[function(require,module,exports){ +},{}],1075:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ - var util = require('./util'); - /** * Determine whether mappingB is after mappingA with respect to generated * position. */ + + function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } - /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ + + function MappingList() { this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; -} + this._sorted = true; // Serves as infimum + this._last = { + generatedLine: -1, + generatedColumn: 0 + }; +} /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ -MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; + +MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); +}; /** * Add the given source mapping. * * @param Object aMapping */ + + MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; + this._array.push(aMapping); } else { this._sorted = false; + this._array.push(aMapping); } }; - /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. @@ -52575,24 +118795,30 @@ MappingList.prototype.add = function MappingList_add(aMapping) { * an immutable borrow. If you want to take ownership, you must make your own * copy. */ + + MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; } + return this._array; }; exports.MappingList = MappingList; -},{"./util":551}],547:[function(require,module,exports){ +},{"./util":1080}],1076:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ - // It turns out that some (most?) JavaScript engines don't self-host // `Array.prototype.sort`. This makes sense because C++ will likely remain // faster than JS when doing raw CPU-intensive sorting. However, when using a @@ -52618,7 +118844,6 @@ function swap(ary, x, y) { ary[x] = ary[y]; ary[y] = temp; } - /** * Returns a random integer within the range `low .. high` inclusive. * @@ -52627,10 +118852,11 @@ function swap(ary, x, y) { * @param {Number} high * The upper bound on the range. */ + + function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); + return Math.round(low + Math.random() * (high - low)); } - /** * The Quick Sort algorithm. * @@ -52643,11 +118869,12 @@ function randomIntInRange(low, high) { * @param {Number} r * End index of the array */ + + function doQuickSort(ary, comparator, p, r) { // If our lower bound is less than our upper bound, we (1) partition the // array into two pieces and (2) recurse on each half. If it is not, this is // the empty array and our base case. - if (p < r) { // (1) Partitioning. // @@ -52657,21 +118884,18 @@ function doQuickSort(ary, comparator, p, r) { // once partition is done, the pivot is in the exact place it will be when // the array is put in sorted order, and it will not need to be moved // again. This runs in O(n) time. - // Always choose a random pivot so that an input array which is reverse // sorted does not cause O(n^2) running time. var pivotIndex = randomIntInRange(p, r); var i = p - 1; - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold + var pivot = ary[r]; // Immediately after `j` is incremented in this loop, the following hold // true: // // * Every element in `ary[p .. i]` is less than or equal to the pivot. // // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; @@ -52680,15 +118904,12 @@ function doQuickSort(ary, comparator, p, r) { } swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. + var q = i + 1; // (2) Recurse on each half. doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } - /** * Sort the given array in-place with the given comparator function. * @@ -52697,45 +118918,51 @@ function doQuickSort(ary, comparator, p, r) { * @param {function} comparator * Function to use to compare two items. */ + + exports.quickSort = function (ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; -},{}],548:[function(require,module,exports){ +},{}],1077:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ - var util = require('./util'); + var binarySearch = require('./binary-search'); + var ArraySet = require('./array-set').ArraySet; + var base64VLQ = require('./base64-vlq'); + var quickSort = require('./quick-sort').quickSort; function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap) - : new BasicSourceMapConsumer(sourceMap); + return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap); } -SourceMapConsumer.fromSourceMap = function(aSourceMap) { +SourceMapConsumer.fromSourceMap = function (aSourceMap) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap); -} - +}; /** * The version of the source mapping spec that we are consuming. */ -SourceMapConsumer.prototype._version = 3; -// `__generatedMappings` and `__originalMappings` are arrays that hold the + +SourceMapConsumer.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings @@ -52767,7 +118994,7 @@ SourceMapConsumer.prototype._version = 3; SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { + get: function get() { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } @@ -52775,10 +119002,9 @@ Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { return this.__generatedMappings; } }); - SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { + get: function get() { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } @@ -52787,28 +119013,25 @@ Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { } }); -SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - +SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; +}; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ -SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; + + +SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); +}; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; - SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; - /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. @@ -52825,40 +119048,43 @@ SourceMapConsumer.LEAST_UPPER_BOUND = 2; * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ -SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - var mappings; - switch (order) { +SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + var mappings; + + switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; + case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; + default: throw new Error("Unknown order of iteration."); - } + } - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - if (source != null && sourceRoot != null) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); +}; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings @@ -52878,81 +119104,71 @@ SourceMapConsumer.prototype.eachMapping = * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ -SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - if (this.sourceRoot != null) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - if (!this._sources.has(needle.source)) { - return []; - } - needle.source = this._sources.indexOf(needle.source); - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); +SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. - mapping = this._originalMappings[++index]; - } + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + + if (!this._sources.has(needle.source)) { + return []; + } + + needle.source = this._sources.indexOf(needle.source); + var mappings = []; + + var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + + while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + mapping = this._originalMappings[++index]; } } + } - return mappings; - }; + return mappings; +}; exports.SourceMapConsumer = SourceMapConsumer; - /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file @@ -52983,51 +119199,45 @@ exports.SourceMapConsumer = SourceMapConsumer; * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ + function BasicSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a + var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. + if (version != this._version) { throw new Error('Unsupported version: ' + version); } - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps + sources = sources.map(String) // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; + }); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); - this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; @@ -53036,7 +119246,6 @@ function BasicSourceMapConsumer(aSourceMap) { BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * @@ -53044,71 +119253,68 @@ BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; * The source map that will be consumed. * @returns BasicSourceMapConsumer */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. +BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); + smc.file = aSourceMap._file; // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; + var generatedMappings = aSourceMap._mappings.toArray().slice(); - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping(); + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; - destOriginalMappings.push(destMapping); + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); } - destGeneratedMappings.push(destMapping); + destOriginalMappings.push(destMapping); } - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - - return smc; - }; + destGeneratedMappings.push(destMapping); + } + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + return smc; +}; /** * The version of the source mapping spec that we are consuming. */ -BasicSourceMapConsumer.prototype._version = 3; + +BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { + get: function get() { return this._sources.toArray().map(function (s) { return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; }, this); } }); - /** * Provide the JIT with a nice shape / hidden class. */ + function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; @@ -53117,167 +119323,159 @@ function Mapping() { this.originalColumn = null; this.name = null; } - /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } + +BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } else if (aStr.charAt(index) === ',') { + index++; + } else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; } - str = aStr.slice(index, end); + } - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } + str = aStr.slice(index, end); + segment = cachedSegments[str]; - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } + if (segment) { + index += str.length; + } else { + segment = []; - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } - cachedSegments[str] = segment; + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); } - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; + cachedSegments[str] = segment; + } // Generated column. - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; // Original line. - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; // Lines are stored 0-based - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); + mapping.originalLine += 1; // Original column. + + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; } } - } - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; + generatedMappings.push(mapping); - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; +}; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; +BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); + } + + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); + } + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); +}; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } +BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; } + } // The last mapping for each line spans the entire line. - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; + mapping.lastGeneratedColumn = Infinity; + } +}; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object @@ -53298,117 +119496,115 @@ BasicSourceMapConsumer.prototype.computeColumnSpans = * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - if (index >= 0) { - var mapping = this._generatedMappings[index]; +BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)); - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - if (this.sourceRoot != null) { - source = util.join(this.sourceRoot, source); - } - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + + if (source !== null) { + source = this._sources.at(source); + + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; } + + var name = util.getArg(mapping, 'name', null); + + if (name !== null) { + name = this._names.at(name); + } + + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; } + } - return { - source: null, - line: null, - column: null, - name: null - }; + return { + source: null, + line: null, + column: null, + name: null }; - +}; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; + +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + + return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) { + return sc == null; + }); +}; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - if (this.sourceRoot != null) { - aSource = util.relative(this.sourceRoot, aSource); - } - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } +BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } - } + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; + var url; + + if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + + if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); + + if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } - }; + } // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + + if (nullOnMissing) { + return null; + } else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } +}; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with @@ -53428,57 +119624,52 @@ BasicSourceMapConsumer.prototype.sourceContentFor = * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - if (this.sourceRoot != null) { - source = util.relative(this.sourceRoot, source); - } - if (!this._sources.has(source)) { - return { - line: null, - column: null, - lastColumn: null - }; - } - source = this._sources.indexOf(source); - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - if (index >= 0) { - var mapping = this._originalMappings[index]; +BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { return { line: null, column: null, lastColumn: null }; + } + + source = this._sources.indexOf(source); + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') }; -exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; +}; +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in @@ -53524,8 +119715,10 @@ exports.BasicSourceMapConsumer = BasicSourceMapConsumer; * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ + function IndexedSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } @@ -53539,7 +119732,6 @@ function IndexedSourceMapConsumer(aSourceMap) { this._sources = new ArraySet(); this._names = new ArraySet(); - var lastOffset = { line: -1, column: 0 @@ -53550,16 +119742,16 @@ function IndexedSourceMapConsumer(aSourceMap) { // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } + var offset = util.getArg(s, 'offset'); var offsetLine = util.getArg(offset, 'line'); var offsetColumn = util.getArg(offset, 'column'); - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) { throw new Error('Section offsets must be ordered and non-overlapping.'); } - lastOffset = offset; + lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when @@ -53568,33 +119760,34 @@ function IndexedSourceMapConsumer(aSourceMap) { generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, 'map')) - } + }; }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - /** * The version of the source mapping spec that we are consuming. */ -IndexedSourceMapConsumer.prototype._version = 3; +IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { + get: function get() { var sources = []; + for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } } + return sources; } }); - /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object @@ -53610,81 +119803,74 @@ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } +IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; // Find the section containing the generated position we're trying to map + // to an original position. - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; + var sectionIndex = binarySearch.search(needle, this._sections, function (needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; + if (cmp) { + return cmp; } - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; + return needle.generatedColumn - section.generatedOffset.generatedColumn; + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + return section.consumer.originalPositionFor({ + line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), + bias: aArgs.bias + }); +}; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; + +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); +}; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); + +IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var content = section.consumer.sourceContentFor(aSource, true); + + if (content) { + return content; } - }; + } + if (nullOnMissing) { + return null; + } else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } +}; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with @@ -53699,105 +119885,110 @@ IndexedSourceMapConsumer.prototype.sourceContentFor = * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } + +IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; // Only consider this section if the requested source is in the list of + // sources of the consumer. + + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; } - return { - line: null, - column: null - }; - }; + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + + if (generatedPosition) { + var ret = { + line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) + }; + return ret; + } + } + return { + line: null, + column: null + }; +}; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - if (section.consumer.sourceRoot !== null) { - source = util.join(section.consumer.sourceRoot, source); - } - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } + +IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + + this._sources.add(source); + + source = this._sources.indexOf(source); + + var name = section.consumer._names.at(mapping.name); + + this._names.add(name); + + name = this._names.indexOf(name); // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); } } + } - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); +}; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; -},{"./array-set":542,"./base64-vlq":543,"./binary-search":545,"./quick-sort":547,"./util":551}],549:[function(require,module,exports){ +},{"./array-set":1071,"./base64-vlq":1072,"./binary-search":1074,"./quick-sort":1076,"./util":1080}],1078:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ - var base64VLQ = require('./base64-vlq'); + var util = require('./util'); + var ArraySet = require('./array-set').ArraySet; -var MappingList = require('./mapping-list').MappingList; +var MappingList = require('./mapping-list').MappingList; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following @@ -53806,10 +119997,13 @@ var MappingList = require('./mapping-list').MappingList; * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ + + function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } + this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util.getArg(aArgs, 'skipValidation', false); @@ -53820,54 +120014,54 @@ function SourceMapGenerator(aArgs) { } SourceMapGenerator.prototype._version = 3; - /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ -SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } +SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; + if (mapping.source != null) { + newMapping.source = mapping.source; - if (mapping.name != null) { - newMapping.name = mapping.name; - } + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); } - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; } - }); - return generator; - }; + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; +}; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping @@ -53878,68 +120072,73 @@ SourceMapGenerator.fromSourceMap = * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ -SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } +SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + + if (!this._sources.has(source)) { + this._sources.add(source); } + } - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); +}; /** * Set the source content for a source file. */ -SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } + +SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); } - }; + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } +}; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is @@ -53956,83 +120155,91 @@ SourceMapGenerator.prototype.setSourceContent = * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ -SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } +SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap - }, this); - this._sources = newSources; - this._names = newNames; + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.'); + } + + sourceFile = aSourceMapConsumer.file; + } + + var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. + + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } // Applying the SourceMap can add and remove items from the sources and + // the names array. + + + var newSources = new ArraySet(); + var newNames = new ArraySet(); // Find mappings for the "sourceFile" + + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + + if (original.source != null) { + // Copy mapping + mapping.source = original.source; - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); + mapping.source = util.join(aSourceMapPath, mapping.source); } + if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); + mapping.source = util.relative(sourceRoot, mapping.source); + } + + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + + if (original.name != null) { + mapping.name = original.name; } - this.setSourceContent(sourceFile, content); } - }, this); - }; + } + + var source = mapping.source; + + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + }, this); + + this._sources = newSources; + this._names = newNames; // Copy sourcesContents of applied map. + + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + + this.setSourceContent(sourceFile, content); + } + }, this); +}; /** * A mapping can have one of the three levels of data: * @@ -54044,188 +120251,175 @@ SourceMapGenerator.prototype.applySourceMap = * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ -SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; +SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error('original.line and original.column are not numbers -- you probably meant to omit ' + 'the original mapping entirely and only map the generated position. If so, pass ' + 'null for the original mapping instead of an object with empty or null values.'); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { + // Cases 2 and 3. + return; + } else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } +}; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ -SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } +SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = ''; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; + } else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; } - } - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; + next += ','; + } + } - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; + next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; + next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; } - - result += next; } - return result; - }; + result += next; + } -SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; + return result; +}; + +SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; + }, this); +}; /** * Externalize the source map. */ -SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - return map; + +SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() }; + if (this._file != null) { + map.file = this._file; + } + + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; +}; /** * Render the source map being generated to a string. */ -SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; + + +SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); +}; exports.SourceMapGenerator = SourceMapGenerator; -},{"./array-set":542,"./base64-vlq":543,"./mapping-list":546,"./util":551}],550:[function(require,module,exports){ +},{"./array-set":1071,"./base64-vlq":1072,"./mapping-list":1075,"./util":1080}],1079:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ - var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; -var util = require('./util'); -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +var util = require('./util'); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; -// Private symbol for identifying `SourceNode`s when multiple versions of +var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons + +var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! -var isSourceNode = "$$$isSourceNode$$$"; +var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and @@ -54238,6 +120432,7 @@ var isSourceNode = "$$$isSourceNode$$$"; * generated JS, or other SourceNodes. * @param aName The original identifier. */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; @@ -54248,7 +120443,6 @@ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } - /** * Creates a SourceNode from generated code and a SourceMapConsumer. * @@ -54257,166 +120451,156 @@ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ -SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); + +SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + + var shiftNextLine = function shiftNextLine() { + var lineContents = getNextLine(); // The last line of a file might not have a newline. + + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : undefined; + } + }; // We need to remember the position of "remainingLines" + + + var lastGeneratedLine = 1, + lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + + var lastMapping = null; + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { + lastGeneratedColumn = 0; // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[remainingLinesIndex]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); // No more remaining code, continue + + lastMapping = mapping; + return; } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); + } // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + + + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; } - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } - return node; + lastMapping = mapping; + }, this); // We have processed all mappings. - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } // and add the remaining lines without any mapping + + + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } // Copy sourcesContent into SourceNode + + + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); } + + node.setSourceContent(sourceFile, content); } - }; + }); + return node; + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; + node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); + } + } +}; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ + + SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { + } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } + } else { + throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk); } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } + return this; }; - /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ + + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { + for (var i = aChunk.length - 1; i >= 0; i--) { this.prepend(aChunk[i]); } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { + } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); + } else { + throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk); } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } + return this; }; - /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that @@ -54424,46 +120608,55 @@ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { * * @param aFn The traversal function. */ + + SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; + if (chunk[isSourceNode]) { chunk.walk(aFn); - } - else { + } else { if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); + aFn(chunk, { + source: this.source, + line: this.line, + column: this.column, + name: this.name + }); } } } }; - /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ + + SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; + if (len > 0) { newChildren = []; - for (i = 0; i < len-1; i++) { + + for (i = 0; i < len - 1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } + newChildren.push(this.children[i]); this.children = newChildren; } + return this; }; - /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. @@ -54471,20 +120664,21 @@ SourceNode.prototype.join = function SourceNode_join(aSep) { * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ + + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { + } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { + } else { this.children.push(''.replace(aPattern, aReplacement)); } + return this; }; - /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. @@ -54492,35 +120686,38 @@ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, a * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ -SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; + +SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; +}; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ -SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + +SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); } - }; + } + var sources = Object.keys(this.sourceContents); + + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } +}; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ + + SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { @@ -54528,11 +120725,12 @@ SourceNode.prototype.toString = function SourceNode_toString() { }); return str; }; - /** * Returns the string representation of this source node along with a source * map. */ + + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", @@ -54547,13 +120745,9 @@ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSou var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { + + if (original.source !== null && original.line !== null && original.column !== null) { + if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { @@ -54567,6 +120761,7 @@ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSou name: original.name }); } + lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; @@ -54582,11 +120777,12 @@ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSou lastOriginalSource = null; sourceMappingActive = false; } + for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; - generated.column = 0; - // Mappings end at eol + generated.column = 0; // Mappings end at eol + if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; @@ -54612,14 +120808,19 @@ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSou this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); - - return { code: generated.code, map: map }; + return { + code: generated.code, + map: map + }; }; exports.SourceNode = SourceNode; -},{"./source-map-generator":549,"./util":551}],551:[function(require,module,exports){ +},{"./source-map-generator":1078,"./util":1080}],1080:[function(require,module,exports){ +"use strict"; + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: @@ -54645,16 +120846,18 @@ function getArg(aArgs, aName, aDefaultValue) { throw new Error('"' + aName + '" is a required argument.'); } } -exports.getArg = getArg; +exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); + if (!match) { return null; } + return { scheme: match[1], auth: match[2], @@ -54663,30 +120866,38 @@ function urlParse(aUrl) { path: match[5] }; } + exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; + if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } + url += '//'; + if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } + if (aParsedUrl.host) { url += aParsedUrl.host; } + if (aParsedUrl.port) { - url += ":" + aParsedUrl.port + url += ":" + aParsedUrl.port; } + if (aParsedUrl.path) { url += aParsedUrl.path; } + return url; } -exports.urlGenerate = urlGenerate; +exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * @@ -54698,20 +120909,25 @@ exports.urlGenerate = urlGenerate; * * @param aPath The path or url to normalize. */ + function normalize(aPath) { var path = aPath; var url = urlParse(aPath); + if (url) { if (!url.path) { return aPath; } + path = url.path; } - var isAbsolute = exports.isAbsolute(path); + var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; + if (part === '.') { parts.splice(i, 1); } else if (part === '..') { @@ -54729,6 +120945,7 @@ function normalize(aPath) { } } } + path = parts.join('/'); if (path === '') { @@ -54739,10 +120956,11 @@ function normalize(aPath) { url.path = path; return urlGenerate(url); } + return path; } -exports.normalize = normalize; +exports.normalize = normalize; /** * Joins two paths/URLs. * @@ -54759,1041 +120977,482 @@ exports.normalize = normalize; * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ + function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } + if (aPath === "") { aPath = "."; } + var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); + if (aRootUrl) { aRoot = aRootUrl.path || '/'; - } + } // `join(foo, '//www.example.org')` + - // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } + return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; - } + } // `join('http://', 'www.example.com')` + - // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } + return joined; } + exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; - /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ + + function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply + aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); -} -exports.relative = relative; - -var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); -}()); - -function identity (s) { - return s; -} - -/** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ -function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; -} -exports.toSetString = supportsNullProto ? identity : toSetString; - -function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; -} -exports.fromSetString = supportsNullProto ? identity : fromSetString; - -function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; -} - -/** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ -function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; -} -exports.compareByOriginalPositions = compareByOriginalPositions; - -/** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ -function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; -} -exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - -function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; -} - -/** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ -function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - -},{}],552:[function(require,module,exports){ -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; -exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; -exports.SourceNode = require('./lib/source-node').SourceNode; - -},{"./lib/source-map-consumer":548,"./lib/source-map-generator":549,"./lib/source-node":550}],553:[function(require,module,exports){ -'use strict'; -var ansiRegex = require('ansi-regex')(); - -module.exports = function (str) { - return typeof str === 'string' ? str.replace(ansiRegex, '') : str; -}; - -},{"ansi-regex":1}],554:[function(require,module,exports){ -(function (process){ -'use strict'; -var argv = process.argv; - -var terminator = argv.indexOf('--'); -var hasFlag = function (flag) { - flag = '--' + flag; - var pos = argv.indexOf(flag); - return pos !== -1 && (terminator !== -1 ? pos < terminator : true); -}; - -module.exports = (function () { - if ('FORCE_COLOR' in process.env) { - return true; - } - - if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - return false; - } - - if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - return true; - } - - if (process.stdout && !process.stdout.isTTY) { - return false; - } - - if (process.platform === 'win32') { - return true; - } - - if ('COLORTERM' in process.env) { - return true; - } - - if (process.env.TERM === 'dumb') { - return false; - } - - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; - } - - return false; -})(); - -}).call(this,require('_process')) -},{"_process":525}],555:[function(require,module,exports){ -'use strict'; -module.exports = function toFastproperties(o) { - function Sub() {} - Sub.prototype = o; - var receiver = new Sub(); // create an instance - function ic() { return typeof receiver.foo; } // perform access - ic(); - ic(); - return o; - eval("o" + o); // ensure no dead code elimination -} - -},{}],556:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - var tail = str.length; - - while (/[\s\uFEFF\u00A0]/.test(str[tail - 1])) { - tail--; - } - - return str.slice(0, tail); -}; - -},{}],557:[function(require,module,exports){ -exports.isatty = function () { return false; }; - -function ReadStream() { - throw new Error('tty.ReadStream is not implemented'); -} -exports.ReadStream = ReadStream; - -function WriteStream() { - throw new Error('tty.ReadStream is not implemented'); -} -exports.WriteStream = WriteStream; - -},{}],558:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],559:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],560:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; + var level = 0; -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); - if (process.noDeprecation === true) { - return fn; - } + if (index < 0) { + return aPath; + } // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; + + aRoot = aRoot.slice(0, index); + + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; } - return fn.apply(this, arguments); - } - return deprecated; -}; + ++level; + } // Make sure we add a "../" for each component we removed from the root. -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} + +exports.relative = relative; +var supportsNullProto = function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}(); +function identity(s) { + return s; +} /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + return aStr; +} -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; +exports.toSetString = supportsNullProto ? identity : toSetString; - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); } + + return aStr; } +exports.fromSetString = supportsNullProto ? identity : fromSetString; -function stylizeNoColor(str, styleType) { - return str; -} +function isProtoString(s) { + if (!s) { + return false; + } + var length = s.length; -function arrayToHash(array) { - var hash = {}; + if (length < 9 + /* "__proto__".length */ + ) { + return false; + } - array.forEach(function(val, idx) { - hash[val] = true; - }); + if (s.charCodeAt(length - 1) !== 95 + /* '_' */ + || s.charCodeAt(length - 2) !== 95 + /* '_' */ + || s.charCodeAt(length - 3) !== 111 + /* 'o' */ + || s.charCodeAt(length - 4) !== 116 + /* 't' */ + || s.charCodeAt(length - 5) !== 111 + /* 'o' */ + || s.charCodeAt(length - 6) !== 114 + /* 'r' */ + || s.charCodeAt(length - 7) !== 112 + /* 'p' */ + || s.charCodeAt(length - 8) !== 95 + /* '_' */ + || s.charCodeAt(length - 9) !== 95 + /* '_' */ + ) { + return false; + } - return hash; + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 + /* '$' */ + ) { + return false; + } + } + + return true; } +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; + if (cmp !== 0) { + return cmp; } - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + cmp = mappingA.originalLine - mappingB.originalLine; - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); + if (cmp !== 0) { + return cmp; } - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } + cmp = mappingA.originalColumn - mappingB.originalColumn; - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; } - var base = '', array = false, braces = ['{', '}']; + cmp = mappingA.generatedColumn - mappingB.generatedColumn; - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; + if (cmp !== 0) { + return cmp; } - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + cmp = mappingA.generatedLine - mappingB.generatedLine; - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); + if (cmp !== 0) { + return cmp; } - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + return mappingA.name - mappingB.name; +} - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); +exports.compareByOriginalPositions = compareByOriginalPositions; +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + + if (cmp !== 0) { + return cmp; } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; } - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } + cmp = mappingA.source - mappingB.source; + + if (cmp !== 0) { + return cmp; } - ctx.seen.push(value); + cmp = mappingA.originalLine - mappingB.originalLine; - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); + if (cmp !== 0) { + return cmp; } - ctx.seen.pop(); + cmp = mappingA.originalColumn - mappingB.originalColumn; - return reduceToSingleString(output, base, braces); + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; } +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} + if (aStr1 > aStr2) { + return 1; + } -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; + return -1; } +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + + if (cmp !== 0) { + return cmp; } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} + cmp = mappingA.generatedColumn - mappingB.generatedColumn; -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } + if (cmp !== 0) { + return cmp; } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } + + cmp = strcmp(mappingA.source, mappingB.source); + + if (cmp !== 0) { + return cmp; } - return name + ': ' + str; -} + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); + cmp = mappingA.originalColumn - mappingB.originalColumn; - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; + if (cmp !== 0) { + return cmp; } - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + return strcmp(mappingA.name, mappingB.name); } +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; +},{}],1081:[function(require,module,exports){ +"use strict"; -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; +},{"./lib/source-map-consumer":1077,"./lib/source-map-generator":1078,"./lib/source-node":1079}],1082:[function(require,module,exports){ +'use strict'; -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; +module.exports = { + stdout: false, + stderr: false +}; -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; +},{}],1083:[function(require,module,exports){ +'use strict'; -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; +var fastProto = null; // Creates an object with permanently fast properties in V8. See Toon Verwaest's +// post https://medium.com/@tverwaes/setting-up-prototypes-in-v8-ec9c9491dfe2#5f62 +// for more details. Use %HasFastProperties(object) and the Node.js flag +// --allow-natives-syntax to check whether an object has fast properties. -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +function FastObject(o) { + // A prototype object will have "fast properties" enabled once it is checked + // against the inline property cache of a function, e.g. fastProto.property: + // https://github.com/v8/v8/blob/6.0.122/test/mjsunit/fast-prototype.js#L48-L63 + if (fastProto !== null && _typeof(fastProto.property)) { + var result = fastProto; + fastProto = FastObject.prototype = null; + return result; + } -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + fastProto = FastObject.prototype = o == null ? Object.create(null) : o; + return new FastObject(); +} // Initialize the inline property cache of FastObject -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; +FastObject(); -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; +module.exports = function toFastproperties(o) { + return FastObject(o); +}; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; +},{}],1084:[function(require,module,exports){ +"use strict"; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; +module.exports = new Set([// Non-binary properties: +'General_Category', 'Script', 'Script_Extensions', // Binary properties: +'Alphabetic', 'Any', 'ASCII', 'ASCII_Hex_Digit', 'Assigned', 'Bidi_Control', 'Bidi_Mirrored', 'Case_Ignorable', 'Cased', 'Changes_When_Casefolded', 'Changes_When_Casemapped', 'Changes_When_Lowercased', 'Changes_When_NFKC_Casefolded', 'Changes_When_Titlecased', 'Changes_When_Uppercased', 'Dash', 'Default_Ignorable_Code_Point', 'Deprecated', 'Diacritic', 'Emoji', 'Emoji_Component', 'Emoji_Modifier', 'Emoji_Modifier_Base', 'Emoji_Presentation', 'Extended_Pictographic', 'Extender', 'Grapheme_Base', 'Grapheme_Extend', 'Hex_Digit', 'ID_Continue', 'ID_Start', 'Ideographic', 'IDS_Binary_Operator', 'IDS_Trinary_Operator', 'Join_Control', 'Logical_Order_Exception', 'Lowercase', 'Math', 'Noncharacter_Code_Point', 'Pattern_Syntax', 'Pattern_White_Space', 'Quotation_Mark', 'Radical', 'Regional_Indicator', 'Sentence_Terminal', 'Soft_Dotted', 'Terminal_Punctuation', 'Unified_Ideograph', 'Uppercase', 'Variation_Selector', 'White_Space', 'XID_Continue', 'XID_Start']); -exports.isBuffer = require('./support/isBuffer'); +},{}],1085:[function(require,module,exports){ +'use strict'; -function objectToString(o) { - return Object.prototype.toString.call(o); -} +var canonicalProperties = require('unicode-canonical-property-names-ecmascript'); +var propertyAliases = require('unicode-property-aliases-ecmascript'); -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} +var matchProperty = function matchProperty(property) { + if (canonicalProperties.has(property)) { + return property; + } + if (propertyAliases.has(property)) { + return propertyAliases.get(property); + } -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + throw new Error("Unknown property: ".concat(property)); +}; -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} +module.exports = matchProperty; +},{"unicode-canonical-property-names-ecmascript":1084,"unicode-property-aliases-ecmascript":1088}],1086:[function(require,module,exports){ +"use strict"; -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; +module.exports = new Map([['General_Category', new Map([['C', 'Other'], ['Cc', 'Control'], ['cntrl', 'Control'], ['Cf', 'Format'], ['Cn', 'Unassigned'], ['Co', 'Private_Use'], ['Cs', 'Surrogate'], ['L', 'Letter'], ['LC', 'Cased_Letter'], ['Ll', 'Lowercase_Letter'], ['Lm', 'Modifier_Letter'], ['Lo', 'Other_Letter'], ['Lt', 'Titlecase_Letter'], ['Lu', 'Uppercase_Letter'], ['M', 'Mark'], ['Combining_Mark', 'Mark'], ['Mc', 'Spacing_Mark'], ['Me', 'Enclosing_Mark'], ['Mn', 'Nonspacing_Mark'], ['N', 'Number'], ['Nd', 'Decimal_Number'], ['digit', 'Decimal_Number'], ['Nl', 'Letter_Number'], ['No', 'Other_Number'], ['P', 'Punctuation'], ['punct', 'Punctuation'], ['Pc', 'Connector_Punctuation'], ['Pd', 'Dash_Punctuation'], ['Pe', 'Close_Punctuation'], ['Pf', 'Final_Punctuation'], ['Pi', 'Initial_Punctuation'], ['Po', 'Other_Punctuation'], ['Ps', 'Open_Punctuation'], ['S', 'Symbol'], ['Sc', 'Currency_Symbol'], ['Sk', 'Modifier_Symbol'], ['Sm', 'Math_Symbol'], ['So', 'Other_Symbol'], ['Z', 'Separator'], ['Zl', 'Line_Separator'], ['Zp', 'Paragraph_Separator'], ['Zs', 'Space_Separator'], ['Other', 'Other'], ['Control', 'Control'], ['Format', 'Format'], ['Unassigned', 'Unassigned'], ['Private_Use', 'Private_Use'], ['Surrogate', 'Surrogate'], ['Letter', 'Letter'], ['Cased_Letter', 'Cased_Letter'], ['Lowercase_Letter', 'Lowercase_Letter'], ['Modifier_Letter', 'Modifier_Letter'], ['Other_Letter', 'Other_Letter'], ['Titlecase_Letter', 'Titlecase_Letter'], ['Uppercase_Letter', 'Uppercase_Letter'], ['Mark', 'Mark'], ['Spacing_Mark', 'Spacing_Mark'], ['Enclosing_Mark', 'Enclosing_Mark'], ['Nonspacing_Mark', 'Nonspacing_Mark'], ['Number', 'Number'], ['Decimal_Number', 'Decimal_Number'], ['Letter_Number', 'Letter_Number'], ['Other_Number', 'Other_Number'], ['Punctuation', 'Punctuation'], ['Connector_Punctuation', 'Connector_Punctuation'], ['Dash_Punctuation', 'Dash_Punctuation'], ['Close_Punctuation', 'Close_Punctuation'], ['Final_Punctuation', 'Final_Punctuation'], ['Initial_Punctuation', 'Initial_Punctuation'], ['Other_Punctuation', 'Other_Punctuation'], ['Open_Punctuation', 'Open_Punctuation'], ['Symbol', 'Symbol'], ['Currency_Symbol', 'Currency_Symbol'], ['Modifier_Symbol', 'Modifier_Symbol'], ['Math_Symbol', 'Math_Symbol'], ['Other_Symbol', 'Other_Symbol'], ['Separator', 'Separator'], ['Line_Separator', 'Line_Separator'], ['Paragraph_Separator', 'Paragraph_Separator'], ['Space_Separator', 'Space_Separator']])], ['Script', new Map([['Adlm', 'Adlam'], ['Aghb', 'Caucasian_Albanian'], ['Ahom', 'Ahom'], ['Arab', 'Arabic'], ['Armi', 'Imperial_Aramaic'], ['Armn', 'Armenian'], ['Avst', 'Avestan'], ['Bali', 'Balinese'], ['Bamu', 'Bamum'], ['Bass', 'Bassa_Vah'], ['Batk', 'Batak'], ['Beng', 'Bengali'], ['Bhks', 'Bhaiksuki'], ['Bopo', 'Bopomofo'], ['Brah', 'Brahmi'], ['Brai', 'Braille'], ['Bugi', 'Buginese'], ['Buhd', 'Buhid'], ['Cakm', 'Chakma'], ['Cans', 'Canadian_Aboriginal'], ['Cari', 'Carian'], ['Cham', 'Cham'], ['Cher', 'Cherokee'], ['Copt', 'Coptic'], ['Qaac', 'Coptic'], ['Cprt', 'Cypriot'], ['Cyrl', 'Cyrillic'], ['Deva', 'Devanagari'], ['Dogr', 'Dogra'], ['Dsrt', 'Deseret'], ['Dupl', 'Duployan'], ['Egyp', 'Egyptian_Hieroglyphs'], ['Elba', 'Elbasan'], ['Elym', 'Elymaic'], ['Ethi', 'Ethiopic'], ['Geor', 'Georgian'], ['Glag', 'Glagolitic'], ['Gong', 'Gunjala_Gondi'], ['Gonm', 'Masaram_Gondi'], ['Goth', 'Gothic'], ['Gran', 'Grantha'], ['Grek', 'Greek'], ['Gujr', 'Gujarati'], ['Guru', 'Gurmukhi'], ['Hang', 'Hangul'], ['Hani', 'Han'], ['Hano', 'Hanunoo'], ['Hatr', 'Hatran'], ['Hebr', 'Hebrew'], ['Hira', 'Hiragana'], ['Hluw', 'Anatolian_Hieroglyphs'], ['Hmng', 'Pahawh_Hmong'], ['Hmnp', 'Nyiakeng_Puachue_Hmong'], ['Hrkt', 'Katakana_Or_Hiragana'], ['Hung', 'Old_Hungarian'], ['Ital', 'Old_Italic'], ['Java', 'Javanese'], ['Kali', 'Kayah_Li'], ['Kana', 'Katakana'], ['Khar', 'Kharoshthi'], ['Khmr', 'Khmer'], ['Khoj', 'Khojki'], ['Knda', 'Kannada'], ['Kthi', 'Kaithi'], ['Lana', 'Tai_Tham'], ['Laoo', 'Lao'], ['Latn', 'Latin'], ['Lepc', 'Lepcha'], ['Limb', 'Limbu'], ['Lina', 'Linear_A'], ['Linb', 'Linear_B'], ['Lisu', 'Lisu'], ['Lyci', 'Lycian'], ['Lydi', 'Lydian'], ['Mahj', 'Mahajani'], ['Maka', 'Makasar'], ['Mand', 'Mandaic'], ['Mani', 'Manichaean'], ['Marc', 'Marchen'], ['Medf', 'Medefaidrin'], ['Mend', 'Mende_Kikakui'], ['Merc', 'Meroitic_Cursive'], ['Mero', 'Meroitic_Hieroglyphs'], ['Mlym', 'Malayalam'], ['Modi', 'Modi'], ['Mong', 'Mongolian'], ['Mroo', 'Mro'], ['Mtei', 'Meetei_Mayek'], ['Mult', 'Multani'], ['Mymr', 'Myanmar'], ['Nand', 'Nandinagari'], ['Narb', 'Old_North_Arabian'], ['Nbat', 'Nabataean'], ['Newa', 'Newa'], ['Nkoo', 'Nko'], ['Nshu', 'Nushu'], ['Ogam', 'Ogham'], ['Olck', 'Ol_Chiki'], ['Orkh', 'Old_Turkic'], ['Orya', 'Oriya'], ['Osge', 'Osage'], ['Osma', 'Osmanya'], ['Palm', 'Palmyrene'], ['Pauc', 'Pau_Cin_Hau'], ['Perm', 'Old_Permic'], ['Phag', 'Phags_Pa'], ['Phli', 'Inscriptional_Pahlavi'], ['Phlp', 'Psalter_Pahlavi'], ['Phnx', 'Phoenician'], ['Plrd', 'Miao'], ['Prti', 'Inscriptional_Parthian'], ['Rjng', 'Rejang'], ['Rohg', 'Hanifi_Rohingya'], ['Runr', 'Runic'], ['Samr', 'Samaritan'], ['Sarb', 'Old_South_Arabian'], ['Saur', 'Saurashtra'], ['Sgnw', 'SignWriting'], ['Shaw', 'Shavian'], ['Shrd', 'Sharada'], ['Sidd', 'Siddham'], ['Sind', 'Khudawadi'], ['Sinh', 'Sinhala'], ['Sogd', 'Sogdian'], ['Sogo', 'Old_Sogdian'], ['Sora', 'Sora_Sompeng'], ['Soyo', 'Soyombo'], ['Sund', 'Sundanese'], ['Sylo', 'Syloti_Nagri'], ['Syrc', 'Syriac'], ['Tagb', 'Tagbanwa'], ['Takr', 'Takri'], ['Tale', 'Tai_Le'], ['Talu', 'New_Tai_Lue'], ['Taml', 'Tamil'], ['Tang', 'Tangut'], ['Tavt', 'Tai_Viet'], ['Telu', 'Telugu'], ['Tfng', 'Tifinagh'], ['Tglg', 'Tagalog'], ['Thaa', 'Thaana'], ['Thai', 'Thai'], ['Tibt', 'Tibetan'], ['Tirh', 'Tirhuta'], ['Ugar', 'Ugaritic'], ['Vaii', 'Vai'], ['Wara', 'Warang_Citi'], ['Wcho', 'Wancho'], ['Xpeo', 'Old_Persian'], ['Xsux', 'Cuneiform'], ['Yiii', 'Yi'], ['Zanb', 'Zanabazar_Square'], ['Zinh', 'Inherited'], ['Qaai', 'Inherited'], ['Zyyy', 'Common'], ['Zzzz', 'Unknown'], ['Adlam', 'Adlam'], ['Caucasian_Albanian', 'Caucasian_Albanian'], ['Arabic', 'Arabic'], ['Imperial_Aramaic', 'Imperial_Aramaic'], ['Armenian', 'Armenian'], ['Avestan', 'Avestan'], ['Balinese', 'Balinese'], ['Bamum', 'Bamum'], ['Bassa_Vah', 'Bassa_Vah'], ['Batak', 'Batak'], ['Bengali', 'Bengali'], ['Bhaiksuki', 'Bhaiksuki'], ['Bopomofo', 'Bopomofo'], ['Brahmi', 'Brahmi'], ['Braille', 'Braille'], ['Buginese', 'Buginese'], ['Buhid', 'Buhid'], ['Chakma', 'Chakma'], ['Canadian_Aboriginal', 'Canadian_Aboriginal'], ['Carian', 'Carian'], ['Cherokee', 'Cherokee'], ['Coptic', 'Coptic'], ['Cypriot', 'Cypriot'], ['Cyrillic', 'Cyrillic'], ['Devanagari', 'Devanagari'], ['Dogra', 'Dogra'], ['Deseret', 'Deseret'], ['Duployan', 'Duployan'], ['Egyptian_Hieroglyphs', 'Egyptian_Hieroglyphs'], ['Elbasan', 'Elbasan'], ['Elymaic', 'Elymaic'], ['Ethiopic', 'Ethiopic'], ['Georgian', 'Georgian'], ['Glagolitic', 'Glagolitic'], ['Gunjala_Gondi', 'Gunjala_Gondi'], ['Masaram_Gondi', 'Masaram_Gondi'], ['Gothic', 'Gothic'], ['Grantha', 'Grantha'], ['Greek', 'Greek'], ['Gujarati', 'Gujarati'], ['Gurmukhi', 'Gurmukhi'], ['Hangul', 'Hangul'], ['Han', 'Han'], ['Hanunoo', 'Hanunoo'], ['Hatran', 'Hatran'], ['Hebrew', 'Hebrew'], ['Hiragana', 'Hiragana'], ['Anatolian_Hieroglyphs', 'Anatolian_Hieroglyphs'], ['Pahawh_Hmong', 'Pahawh_Hmong'], ['Nyiakeng_Puachue_Hmong', 'Nyiakeng_Puachue_Hmong'], ['Katakana_Or_Hiragana', 'Katakana_Or_Hiragana'], ['Old_Hungarian', 'Old_Hungarian'], ['Old_Italic', 'Old_Italic'], ['Javanese', 'Javanese'], ['Kayah_Li', 'Kayah_Li'], ['Katakana', 'Katakana'], ['Kharoshthi', 'Kharoshthi'], ['Khmer', 'Khmer'], ['Khojki', 'Khojki'], ['Kannada', 'Kannada'], ['Kaithi', 'Kaithi'], ['Tai_Tham', 'Tai_Tham'], ['Lao', 'Lao'], ['Latin', 'Latin'], ['Lepcha', 'Lepcha'], ['Limbu', 'Limbu'], ['Linear_A', 'Linear_A'], ['Linear_B', 'Linear_B'], ['Lycian', 'Lycian'], ['Lydian', 'Lydian'], ['Mahajani', 'Mahajani'], ['Makasar', 'Makasar'], ['Mandaic', 'Mandaic'], ['Manichaean', 'Manichaean'], ['Marchen', 'Marchen'], ['Medefaidrin', 'Medefaidrin'], ['Mende_Kikakui', 'Mende_Kikakui'], ['Meroitic_Cursive', 'Meroitic_Cursive'], ['Meroitic_Hieroglyphs', 'Meroitic_Hieroglyphs'], ['Malayalam', 'Malayalam'], ['Mongolian', 'Mongolian'], ['Mro', 'Mro'], ['Meetei_Mayek', 'Meetei_Mayek'], ['Multani', 'Multani'], ['Myanmar', 'Myanmar'], ['Nandinagari', 'Nandinagari'], ['Old_North_Arabian', 'Old_North_Arabian'], ['Nabataean', 'Nabataean'], ['Nko', 'Nko'], ['Nushu', 'Nushu'], ['Ogham', 'Ogham'], ['Ol_Chiki', 'Ol_Chiki'], ['Old_Turkic', 'Old_Turkic'], ['Oriya', 'Oriya'], ['Osage', 'Osage'], ['Osmanya', 'Osmanya'], ['Palmyrene', 'Palmyrene'], ['Pau_Cin_Hau', 'Pau_Cin_Hau'], ['Old_Permic', 'Old_Permic'], ['Phags_Pa', 'Phags_Pa'], ['Inscriptional_Pahlavi', 'Inscriptional_Pahlavi'], ['Psalter_Pahlavi', 'Psalter_Pahlavi'], ['Phoenician', 'Phoenician'], ['Miao', 'Miao'], ['Inscriptional_Parthian', 'Inscriptional_Parthian'], ['Rejang', 'Rejang'], ['Hanifi_Rohingya', 'Hanifi_Rohingya'], ['Runic', 'Runic'], ['Samaritan', 'Samaritan'], ['Old_South_Arabian', 'Old_South_Arabian'], ['Saurashtra', 'Saurashtra'], ['SignWriting', 'SignWriting'], ['Shavian', 'Shavian'], ['Sharada', 'Sharada'], ['Siddham', 'Siddham'], ['Khudawadi', 'Khudawadi'], ['Sinhala', 'Sinhala'], ['Sogdian', 'Sogdian'], ['Old_Sogdian', 'Old_Sogdian'], ['Sora_Sompeng', 'Sora_Sompeng'], ['Soyombo', 'Soyombo'], ['Sundanese', 'Sundanese'], ['Syloti_Nagri', 'Syloti_Nagri'], ['Syriac', 'Syriac'], ['Tagbanwa', 'Tagbanwa'], ['Takri', 'Takri'], ['Tai_Le', 'Tai_Le'], ['New_Tai_Lue', 'New_Tai_Lue'], ['Tamil', 'Tamil'], ['Tangut', 'Tangut'], ['Tai_Viet', 'Tai_Viet'], ['Telugu', 'Telugu'], ['Tifinagh', 'Tifinagh'], ['Tagalog', 'Tagalog'], ['Thaana', 'Thaana'], ['Tibetan', 'Tibetan'], ['Tirhuta', 'Tirhuta'], ['Ugaritic', 'Ugaritic'], ['Vai', 'Vai'], ['Warang_Citi', 'Warang_Citi'], ['Wancho', 'Wancho'], ['Old_Persian', 'Old_Persian'], ['Cuneiform', 'Cuneiform'], ['Yi', 'Yi'], ['Zanabazar_Square', 'Zanabazar_Square'], ['Inherited', 'Inherited'], ['Common', 'Common'], ['Unknown', 'Unknown']])], ['Script_Extensions', new Map([['Adlm', 'Adlam'], ['Aghb', 'Caucasian_Albanian'], ['Ahom', 'Ahom'], ['Arab', 'Arabic'], ['Armi', 'Imperial_Aramaic'], ['Armn', 'Armenian'], ['Avst', 'Avestan'], ['Bali', 'Balinese'], ['Bamu', 'Bamum'], ['Bass', 'Bassa_Vah'], ['Batk', 'Batak'], ['Beng', 'Bengali'], ['Bhks', 'Bhaiksuki'], ['Bopo', 'Bopomofo'], ['Brah', 'Brahmi'], ['Brai', 'Braille'], ['Bugi', 'Buginese'], ['Buhd', 'Buhid'], ['Cakm', 'Chakma'], ['Cans', 'Canadian_Aboriginal'], ['Cari', 'Carian'], ['Cham', 'Cham'], ['Cher', 'Cherokee'], ['Copt', 'Coptic'], ['Qaac', 'Coptic'], ['Cprt', 'Cypriot'], ['Cyrl', 'Cyrillic'], ['Deva', 'Devanagari'], ['Dogr', 'Dogra'], ['Dsrt', 'Deseret'], ['Dupl', 'Duployan'], ['Egyp', 'Egyptian_Hieroglyphs'], ['Elba', 'Elbasan'], ['Elym', 'Elymaic'], ['Ethi', 'Ethiopic'], ['Geor', 'Georgian'], ['Glag', 'Glagolitic'], ['Gong', 'Gunjala_Gondi'], ['Gonm', 'Masaram_Gondi'], ['Goth', 'Gothic'], ['Gran', 'Grantha'], ['Grek', 'Greek'], ['Gujr', 'Gujarati'], ['Guru', 'Gurmukhi'], ['Hang', 'Hangul'], ['Hani', 'Han'], ['Hano', 'Hanunoo'], ['Hatr', 'Hatran'], ['Hebr', 'Hebrew'], ['Hira', 'Hiragana'], ['Hluw', 'Anatolian_Hieroglyphs'], ['Hmng', 'Pahawh_Hmong'], ['Hmnp', 'Nyiakeng_Puachue_Hmong'], ['Hrkt', 'Katakana_Or_Hiragana'], ['Hung', 'Old_Hungarian'], ['Ital', 'Old_Italic'], ['Java', 'Javanese'], ['Kali', 'Kayah_Li'], ['Kana', 'Katakana'], ['Khar', 'Kharoshthi'], ['Khmr', 'Khmer'], ['Khoj', 'Khojki'], ['Knda', 'Kannada'], ['Kthi', 'Kaithi'], ['Lana', 'Tai_Tham'], ['Laoo', 'Lao'], ['Latn', 'Latin'], ['Lepc', 'Lepcha'], ['Limb', 'Limbu'], ['Lina', 'Linear_A'], ['Linb', 'Linear_B'], ['Lisu', 'Lisu'], ['Lyci', 'Lycian'], ['Lydi', 'Lydian'], ['Mahj', 'Mahajani'], ['Maka', 'Makasar'], ['Mand', 'Mandaic'], ['Mani', 'Manichaean'], ['Marc', 'Marchen'], ['Medf', 'Medefaidrin'], ['Mend', 'Mende_Kikakui'], ['Merc', 'Meroitic_Cursive'], ['Mero', 'Meroitic_Hieroglyphs'], ['Mlym', 'Malayalam'], ['Modi', 'Modi'], ['Mong', 'Mongolian'], ['Mroo', 'Mro'], ['Mtei', 'Meetei_Mayek'], ['Mult', 'Multani'], ['Mymr', 'Myanmar'], ['Nand', 'Nandinagari'], ['Narb', 'Old_North_Arabian'], ['Nbat', 'Nabataean'], ['Newa', 'Newa'], ['Nkoo', 'Nko'], ['Nshu', 'Nushu'], ['Ogam', 'Ogham'], ['Olck', 'Ol_Chiki'], ['Orkh', 'Old_Turkic'], ['Orya', 'Oriya'], ['Osge', 'Osage'], ['Osma', 'Osmanya'], ['Palm', 'Palmyrene'], ['Pauc', 'Pau_Cin_Hau'], ['Perm', 'Old_Permic'], ['Phag', 'Phags_Pa'], ['Phli', 'Inscriptional_Pahlavi'], ['Phlp', 'Psalter_Pahlavi'], ['Phnx', 'Phoenician'], ['Plrd', 'Miao'], ['Prti', 'Inscriptional_Parthian'], ['Rjng', 'Rejang'], ['Rohg', 'Hanifi_Rohingya'], ['Runr', 'Runic'], ['Samr', 'Samaritan'], ['Sarb', 'Old_South_Arabian'], ['Saur', 'Saurashtra'], ['Sgnw', 'SignWriting'], ['Shaw', 'Shavian'], ['Shrd', 'Sharada'], ['Sidd', 'Siddham'], ['Sind', 'Khudawadi'], ['Sinh', 'Sinhala'], ['Sogd', 'Sogdian'], ['Sogo', 'Old_Sogdian'], ['Sora', 'Sora_Sompeng'], ['Soyo', 'Soyombo'], ['Sund', 'Sundanese'], ['Sylo', 'Syloti_Nagri'], ['Syrc', 'Syriac'], ['Tagb', 'Tagbanwa'], ['Takr', 'Takri'], ['Tale', 'Tai_Le'], ['Talu', 'New_Tai_Lue'], ['Taml', 'Tamil'], ['Tang', 'Tangut'], ['Tavt', 'Tai_Viet'], ['Telu', 'Telugu'], ['Tfng', 'Tifinagh'], ['Tglg', 'Tagalog'], ['Thaa', 'Thaana'], ['Thai', 'Thai'], ['Tibt', 'Tibetan'], ['Tirh', 'Tirhuta'], ['Ugar', 'Ugaritic'], ['Vaii', 'Vai'], ['Wara', 'Warang_Citi'], ['Wcho', 'Wancho'], ['Xpeo', 'Old_Persian'], ['Xsux', 'Cuneiform'], ['Yiii', 'Yi'], ['Zanb', 'Zanabazar_Square'], ['Zinh', 'Inherited'], ['Qaai', 'Inherited'], ['Zyyy', 'Common'], ['Zzzz', 'Unknown'], ['Adlam', 'Adlam'], ['Caucasian_Albanian', 'Caucasian_Albanian'], ['Arabic', 'Arabic'], ['Imperial_Aramaic', 'Imperial_Aramaic'], ['Armenian', 'Armenian'], ['Avestan', 'Avestan'], ['Balinese', 'Balinese'], ['Bamum', 'Bamum'], ['Bassa_Vah', 'Bassa_Vah'], ['Batak', 'Batak'], ['Bengali', 'Bengali'], ['Bhaiksuki', 'Bhaiksuki'], ['Bopomofo', 'Bopomofo'], ['Brahmi', 'Brahmi'], ['Braille', 'Braille'], ['Buginese', 'Buginese'], ['Buhid', 'Buhid'], ['Chakma', 'Chakma'], ['Canadian_Aboriginal', 'Canadian_Aboriginal'], ['Carian', 'Carian'], ['Cherokee', 'Cherokee'], ['Coptic', 'Coptic'], ['Cypriot', 'Cypriot'], ['Cyrillic', 'Cyrillic'], ['Devanagari', 'Devanagari'], ['Dogra', 'Dogra'], ['Deseret', 'Deseret'], ['Duployan', 'Duployan'], ['Egyptian_Hieroglyphs', 'Egyptian_Hieroglyphs'], ['Elbasan', 'Elbasan'], ['Elymaic', 'Elymaic'], ['Ethiopic', 'Ethiopic'], ['Georgian', 'Georgian'], ['Glagolitic', 'Glagolitic'], ['Gunjala_Gondi', 'Gunjala_Gondi'], ['Masaram_Gondi', 'Masaram_Gondi'], ['Gothic', 'Gothic'], ['Grantha', 'Grantha'], ['Greek', 'Greek'], ['Gujarati', 'Gujarati'], ['Gurmukhi', 'Gurmukhi'], ['Hangul', 'Hangul'], ['Han', 'Han'], ['Hanunoo', 'Hanunoo'], ['Hatran', 'Hatran'], ['Hebrew', 'Hebrew'], ['Hiragana', 'Hiragana'], ['Anatolian_Hieroglyphs', 'Anatolian_Hieroglyphs'], ['Pahawh_Hmong', 'Pahawh_Hmong'], ['Nyiakeng_Puachue_Hmong', 'Nyiakeng_Puachue_Hmong'], ['Katakana_Or_Hiragana', 'Katakana_Or_Hiragana'], ['Old_Hungarian', 'Old_Hungarian'], ['Old_Italic', 'Old_Italic'], ['Javanese', 'Javanese'], ['Kayah_Li', 'Kayah_Li'], ['Katakana', 'Katakana'], ['Kharoshthi', 'Kharoshthi'], ['Khmer', 'Khmer'], ['Khojki', 'Khojki'], ['Kannada', 'Kannada'], ['Kaithi', 'Kaithi'], ['Tai_Tham', 'Tai_Tham'], ['Lao', 'Lao'], ['Latin', 'Latin'], ['Lepcha', 'Lepcha'], ['Limbu', 'Limbu'], ['Linear_A', 'Linear_A'], ['Linear_B', 'Linear_B'], ['Lycian', 'Lycian'], ['Lydian', 'Lydian'], ['Mahajani', 'Mahajani'], ['Makasar', 'Makasar'], ['Mandaic', 'Mandaic'], ['Manichaean', 'Manichaean'], ['Marchen', 'Marchen'], ['Medefaidrin', 'Medefaidrin'], ['Mende_Kikakui', 'Mende_Kikakui'], ['Meroitic_Cursive', 'Meroitic_Cursive'], ['Meroitic_Hieroglyphs', 'Meroitic_Hieroglyphs'], ['Malayalam', 'Malayalam'], ['Mongolian', 'Mongolian'], ['Mro', 'Mro'], ['Meetei_Mayek', 'Meetei_Mayek'], ['Multani', 'Multani'], ['Myanmar', 'Myanmar'], ['Nandinagari', 'Nandinagari'], ['Old_North_Arabian', 'Old_North_Arabian'], ['Nabataean', 'Nabataean'], ['Nko', 'Nko'], ['Nushu', 'Nushu'], ['Ogham', 'Ogham'], ['Ol_Chiki', 'Ol_Chiki'], ['Old_Turkic', 'Old_Turkic'], ['Oriya', 'Oriya'], ['Osage', 'Osage'], ['Osmanya', 'Osmanya'], ['Palmyrene', 'Palmyrene'], ['Pau_Cin_Hau', 'Pau_Cin_Hau'], ['Old_Permic', 'Old_Permic'], ['Phags_Pa', 'Phags_Pa'], ['Inscriptional_Pahlavi', 'Inscriptional_Pahlavi'], ['Psalter_Pahlavi', 'Psalter_Pahlavi'], ['Phoenician', 'Phoenician'], ['Miao', 'Miao'], ['Inscriptional_Parthian', 'Inscriptional_Parthian'], ['Rejang', 'Rejang'], ['Hanifi_Rohingya', 'Hanifi_Rohingya'], ['Runic', 'Runic'], ['Samaritan', 'Samaritan'], ['Old_South_Arabian', 'Old_South_Arabian'], ['Saurashtra', 'Saurashtra'], ['SignWriting', 'SignWriting'], ['Shavian', 'Shavian'], ['Sharada', 'Sharada'], ['Siddham', 'Siddham'], ['Khudawadi', 'Khudawadi'], ['Sinhala', 'Sinhala'], ['Sogdian', 'Sogdian'], ['Old_Sogdian', 'Old_Sogdian'], ['Sora_Sompeng', 'Sora_Sompeng'], ['Soyombo', 'Soyombo'], ['Sundanese', 'Sundanese'], ['Syloti_Nagri', 'Syloti_Nagri'], ['Syriac', 'Syriac'], ['Tagbanwa', 'Tagbanwa'], ['Takri', 'Takri'], ['Tai_Le', 'Tai_Le'], ['New_Tai_Lue', 'New_Tai_Lue'], ['Tamil', 'Tamil'], ['Tangut', 'Tangut'], ['Tai_Viet', 'Tai_Viet'], ['Telugu', 'Telugu'], ['Tifinagh', 'Tifinagh'], ['Tagalog', 'Tagalog'], ['Thaana', 'Thaana'], ['Tibetan', 'Tibetan'], ['Tirhuta', 'Tirhuta'], ['Ugaritic', 'Ugaritic'], ['Vai', 'Vai'], ['Warang_Citi', 'Warang_Citi'], ['Wancho', 'Wancho'], ['Old_Persian', 'Old_Persian'], ['Cuneiform', 'Cuneiform'], ['Yi', 'Yi'], ['Zanabazar_Square', 'Zanabazar_Square'], ['Inherited', 'Inherited'], ['Common', 'Common'], ['Unknown', 'Unknown']])]]); +},{}],1087:[function(require,module,exports){ +'use strict'; -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); +var propertyToValueAliases = require('./data/mappings.js'); -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; +var matchPropertyValue = function matchPropertyValue(property, value) { + var aliasToValue = propertyToValueAliases.get(property); - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; + if (!aliasToValue) { + throw new Error("Unknown property `".concat(property, "`.")); } - return origin; + + var canonicalValue = aliasToValue.get(value); + + if (canonicalValue) { + return canonicalValue; + } + + throw new Error("Unknown value `".concat(value, "` for property `").concat(property, "`.")); }; -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} +module.exports = matchPropertyValue; -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":559,"_process":525,"inherits":558}],561:[function(require,module,exports){ -/*import { transform as babelTransform } from 'babel-core'; -import babelTransformDynamicImport from 'babel-plugin-syntax-dynamic-import'; -import babelTransformES2015ModulesSystemJS from 'babel-plugin-transform-es2015-modules-systemjs';*/ +},{"./data/mappings.js":1086}],1088:[function(require,module,exports){ +"use strict"; -// sadly, due to how rollup works, we can't use es6 imports here -var babelTransform = require('babel-core').transform; -var babelTransformDynamicImport = require('babel-plugin-syntax-dynamic-import'); -var babelTransformES2015ModulesSystemJS = require('babel-plugin-transform-es2015-modules-systemjs'); -var babelPresetES2015 = require('babel-preset-es2015'); +// Generated using `npm run build`. Do not edit! +module.exports = new Map([['scx', 'Script_Extensions'], ['sc', 'Script'], ['gc', 'General_Category'], ['AHex', 'ASCII_Hex_Digit'], ['Alpha', 'Alphabetic'], ['Bidi_C', 'Bidi_Control'], ['Bidi_M', 'Bidi_Mirrored'], ['Cased', 'Cased'], ['CI', 'Case_Ignorable'], ['CWCF', 'Changes_When_Casefolded'], ['CWCM', 'Changes_When_Casemapped'], ['CWKCF', 'Changes_When_NFKC_Casefolded'], ['CWL', 'Changes_When_Lowercased'], ['CWT', 'Changes_When_Titlecased'], ['CWU', 'Changes_When_Uppercased'], ['Dash', 'Dash'], ['Dep', 'Deprecated'], ['DI', 'Default_Ignorable_Code_Point'], ['Dia', 'Diacritic'], ['Ext', 'Extender'], ['Gr_Base', 'Grapheme_Base'], ['Gr_Ext', 'Grapheme_Extend'], ['Hex', 'Hex_Digit'], ['IDC', 'ID_Continue'], ['Ideo', 'Ideographic'], ['IDS', 'ID_Start'], ['IDSB', 'IDS_Binary_Operator'], ['IDST', 'IDS_Trinary_Operator'], ['Join_C', 'Join_Control'], ['LOE', 'Logical_Order_Exception'], ['Lower', 'Lowercase'], ['Math', 'Math'], ['NChar', 'Noncharacter_Code_Point'], ['Pat_Syn', 'Pattern_Syntax'], ['Pat_WS', 'Pattern_White_Space'], ['QMark', 'Quotation_Mark'], ['Radical', 'Radical'], ['RI', 'Regional_Indicator'], ['SD', 'Soft_Dotted'], ['STerm', 'Sentence_Terminal'], ['Term', 'Terminal_Punctuation'], ['UIdeo', 'Unified_Ideograph'], ['Upper', 'Uppercase'], ['VS', 'Variation_Selector'], ['WSpace', 'White_Space'], ['space', 'White_Space'], ['XIDC', 'XID_Continue'], ['XIDS', 'XID_Start']]); -self.onmessage = function (evt) { - // transform source with Babel - var output = babelTransform(evt.data.source, { - compact: false, - filename: evt.data.key + '!transpiled', - sourceFileName: evt.data.key, - moduleIds: false, - sourceMaps: 'inline', - babelrc: false, - plugins: [babelTransformDynamicImport, babelTransformES2015ModulesSystemJS], - presets: [babelPresetES2015], - }); +},{}],1089:[function(require,module,exports){ +arguments[4][279][0].apply(exports,arguments) +},{"dup":279}],1090:[function(require,module,exports){ +arguments[4][280][0].apply(exports,arguments) +},{"dup":280}],1091:[function(require,module,exports){ +arguments[4][281][0].apply(exports,arguments) +},{"./support/isBuffer":1090,"_process":1054,"dup":281,"inherits":1089}],1092:[function(require,module,exports){ +"use strict"; - self.postMessage({key: evt.data.key, code: output.code, source: evt.data.source}); +// Polyfills needed for Babel to function +require("core-js"); + +var babelTransform = require('@babel/core').transform; + +var babelTransformDynamicImport = require('@babel/plugin-syntax-dynamic-import'); + +var babelTransformModulesSystemJS = require('@babel/plugin-transform-modules-systemjs'); + +var babelPresetEnv = require('@babel/preset-env'); + +self.onmessage = function (evt) { + // transform source with Babel + var output = babelTransform(evt.data.source, { + compact: false, + filename: evt.data.key + '!transpiled', + sourceFileName: evt.data.key, + moduleIds: false, + sourceMaps: 'inline', + babelrc: false, + plugins: [babelTransformDynamicImport, babelTransformModulesSystemJS], + presets: [[babelPresetEnv, { + targets: 'ie >= 11' + }]] + }); + self.postMessage({ + key: evt.data.key, + code: output.code, + source: evt.data.source + }); }; -},{"babel-core":5,"babel-plugin-syntax-dynamic-import":63,"babel-plugin-transform-es2015-modules-systemjs":79,"babel-preset-es2015":94}]},{},[561]); +},{"@babel/core":19,"@babel/plugin-syntax-dynamic-import":99,"@babel/plugin-transform-modules-systemjs":122,"@babel/preset-env":149,"core-js":309}]},{},[1092]); diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/dist/browser-es-module-loader.js b/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/dist/browser-es-module-loader.js index c36665aa..17f1ef15 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/dist/browser-es-module-loader.js +++ b/jupyter_desktop/share/web/noVNC-1.2.0/vendor/browser-es-module-loader/dist/browser-es-module-loader.js @@ -1,1486 +1,1481 @@ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.BrowserESModuleLoader = factory()); + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.BrowserESModuleLoader = factory()); }(this, (function () { 'use strict'; -/* - * Environment - */ -var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'; -var isNode = typeof process !== 'undefined' && process.versions && process.versions.node; -var isWindows = typeof process !== 'undefined' && typeof process.platform === 'string' && process.platform.match(/^win/); + /* + * Environment + */ + var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'; + var isNode = typeof process !== 'undefined' && process.versions && process.versions.node; + var isWindows = typeof process !== 'undefined' && typeof process.platform === 'string' && process.platform.match(/^win/); + + var envGlobal = typeof self !== 'undefined' ? self : global; + + /* + * Simple Symbol() shim + */ + var hasSymbol = typeof Symbol !== 'undefined'; + function createSymbol (name) { + return hasSymbol ? Symbol() : '@@' + name; + } -var envGlobal = typeof self !== 'undefined' ? self : global; -/* - * Simple Symbol() shim - */ -var hasSymbol = typeof Symbol !== 'undefined'; -function createSymbol (name) { - return hasSymbol ? Symbol() : '@@' + name; -} + var toStringTag = hasSymbol && Symbol.toStringTag; -var toStringTag = hasSymbol && Symbol.toStringTag; + /* + * Environment baseURI + */ + var baseURI; + // environent baseURI detection + if (typeof document != 'undefined' && document.getElementsByTagName) { + baseURI = document.baseURI; + if (!baseURI) { + var bases = document.getElementsByTagName('base'); + baseURI = bases[0] && bases[0].href || window.location.href; + } + } + else if (typeof location != 'undefined') { + baseURI = location.href; + } + // sanitize out the hash and querystring + if (baseURI) { + baseURI = baseURI.split('#')[0].split('?')[0]; + var slashIndex = baseURI.lastIndexOf('/'); + if (slashIndex !== -1) + baseURI = baseURI.substr(0, slashIndex + 1); + } + else if (typeof process !== 'undefined' && process.cwd) { + baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd(); + if (isWindows) + baseURI = baseURI.replace(/\\/g, '/'); + } + else { + throw new TypeError('No environment baseURI'); + } + // ensure baseURI has trailing "/" + if (baseURI[baseURI.length - 1] !== '/') + baseURI += '/'; -/* - * Environment baseURI - */ -var baseURI; + /* + * LoaderError with chaining for loader stacks + */ + var errArgs = new Error(0, '_').fileName == '_'; + function LoaderError__Check_error_message_for_loader_stack (childErr, newMessage) { + // Convert file:/// URLs to paths in Node + if (!isBrowser) + newMessage = newMessage.replace(isWindows ? /file:\/\/\//g : /file:\/\//g, ''); -// environent baseURI detection -if (typeof document != 'undefined' && document.getElementsByTagName) { - baseURI = document.baseURI; + var message = (childErr.message || childErr) + '\n ' + newMessage; - if (!baseURI) { - var bases = document.getElementsByTagName('base'); - baseURI = bases[0] && bases[0].href || window.location.href; - } -} -else if (typeof location != 'undefined') { - baseURI = location.href; -} - -// sanitize out the hash and querystring -if (baseURI) { - baseURI = baseURI.split('#')[0].split('?')[0]; - var slashIndex = baseURI.lastIndexOf('/'); - if (slashIndex !== -1) - baseURI = baseURI.substr(0, slashIndex + 1); -} -else if (typeof process !== 'undefined' && process.cwd) { - baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd(); - if (isWindows) - baseURI = baseURI.replace(/\\/g, '/'); -} -else { - throw new TypeError('No environment baseURI'); -} - -// ensure baseURI has trailing "/" -if (baseURI[baseURI.length - 1] !== '/') - baseURI += '/'; - -/* - * LoaderError with chaining for loader stacks - */ -var errArgs = new Error(0, '_').fileName == '_'; -function LoaderError__Check_error_message_for_loader_stack (childErr, newMessage) { - // Convert file:/// URLs to paths in Node - if (!isBrowser) - newMessage = newMessage.replace(isWindows ? /file:\/\/\//g : /file:\/\//g, ''); - - var message = (childErr.message || childErr) + '\n ' + newMessage; - - var err; - if (errArgs && childErr.fileName) - err = new Error(message, childErr.fileName, childErr.lineNumber); - else - err = new Error(message); - - - var stack = childErr.originalErr ? childErr.originalErr.stack : childErr.stack; - - if (isNode) - // node doesn't show the message otherwise - err.stack = message + '\n ' + stack; - else - err.stack = stack; - - err.originalErr = childErr.originalErr || childErr; - - return err; -} + var err; + if (errArgs && childErr.fileName) + err = new Error(message, childErr.fileName, childErr.lineNumber); + else + err = new Error(message); + + + var stack = childErr.originalErr ? childErr.originalErr.stack : childErr.stack; + + if (isNode) + // node doesn't show the message otherwise + err.stack = message + '\n ' + stack; + else + err.stack = stack; + + err.originalErr = childErr.originalErr || childErr; + + return err; + } -var resolvedPromise$1 = Promise.resolve(); - -/* - * Simple Array values shim - */ -function arrayValues (arr) { - if (arr.values) - return arr.values(); - - if (typeof Symbol === 'undefined' || !Symbol.iterator) - throw new Error('Symbol.iterator not supported in this browser'); - - var iterable = {}; - iterable[Symbol.iterator] = function () { - var keys = Object.keys(arr); - var keyIndex = 0; - return { - next: function () { - if (keyIndex < keys.length) - return { - value: arr[keys[keyIndex++]], - done: false - }; - else - return { - value: undefined, - done: true - }; - } + var resolvedPromise = Promise.resolve(); + + /* + * Simple Array values shim + */ + function arrayValues (arr) { + if (arr.values) + return arr.values(); + + if (typeof Symbol === 'undefined' || !Symbol.iterator) + throw new Error('Symbol.iterator not supported in this browser'); + + var iterable = {}; + iterable[Symbol.iterator] = function () { + var keys = Object.keys(arr); + var keyIndex = 0; + return { + next: function () { + if (keyIndex < keys.length) + return { + value: arr[keys[keyIndex++]], + done: false + }; + else + return { + value: undefined, + done: true + }; + } + }; }; + return iterable; + } + + /* + * 3. Reflect.Loader + * + * We skip the entire native internal pipeline, just providing the bare API + */ + // 3.1.1 + function Loader () { + this.registry = new Registry(); + } + // 3.3.1 + Loader.prototype.constructor = Loader; + + function ensureInstantiated (module) { + if (module === undefined) + return; + if (module instanceof ModuleNamespace === false && module[toStringTag] !== 'module') + throw new TypeError('Module instantiation did not return a valid namespace object.'); + return module; + } + + // 3.3.2 + Loader.prototype.import = function (key, parent) { + if (typeof key !== 'string') + throw new TypeError('Loader import method must be passed a module key string'); + // custom resolveInstantiate combined hook for better perf + var loader = this; + return resolvedPromise + .then(function () { + return loader[RESOLVE_INSTANTIATE](key, parent); + }) + .then(ensureInstantiated) + //.then(Module.evaluate) + .catch(function (err) { + throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + key + (parent ? ' from ' + parent : '')); + }); }; - return iterable; -} - -/* - * 3. Reflect.Loader - * - * We skip the entire native internal pipeline, just providing the bare API - */ -// 3.1.1 -function Loader () { - this.registry = new Registry(); -} -// 3.3.1 -Loader.prototype.constructor = Loader; - -function ensureInstantiated (module) { - if (module === undefined) - return; - if (module instanceof ModuleNamespace === false && module[toStringTag] !== 'module') - throw new TypeError('Module instantiation did not return a valid namespace object.'); - return module; -} - -// 3.3.2 -Loader.prototype.import = function (key, parent) { - if (typeof key !== 'string') - throw new TypeError('Loader import method must be passed a module key string'); - // custom resolveInstantiate combined hook for better perf - var loader = this; - return resolvedPromise$1 - .then(function () { - return loader[RESOLVE_INSTANTIATE](key, parent); - }) - .then(ensureInstantiated) - //.then(Module.evaluate) - .catch(function (err) { - throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + key + (parent ? ' from ' + parent : '')); - }); -}; -// 3.3.3 -var RESOLVE = Loader.resolve = createSymbol('resolve'); - -/* - * Combined resolve / instantiate hook - * - * Not in current reduced spec, but necessary to separate RESOLVE from RESOLVE + INSTANTIATE as described - * in the spec notes of this repo to ensure that loader.resolve doesn't instantiate when not wanted. - * - * We implement RESOLVE_INSTANTIATE as a single hook instead of a separate INSTANTIATE in order to avoid - * the need for double registry lookups as a performance optimization. - */ -var RESOLVE_INSTANTIATE = Loader.resolveInstantiate = createSymbol('resolveInstantiate'); - -// default resolveInstantiate is just to call resolve and then get from the registry -// this provides compatibility for the resolveInstantiate optimization -Loader.prototype[RESOLVE_INSTANTIATE] = function (key, parent) { - var loader = this; - return loader.resolve(key, parent) - .then(function (resolved) { - return loader.registry.get(resolved); - }); -}; - -function ensureResolution (resolvedKey) { - if (resolvedKey === undefined) - throw new RangeError('No resolution found.'); - return resolvedKey; -} - -Loader.prototype.resolve = function (key, parent) { - var loader = this; - return resolvedPromise$1 - .then(function() { - return loader[RESOLVE](key, parent); - }) - .then(ensureResolution) - .catch(function (err) { - throw LoaderError__Check_error_message_for_loader_stack(err, 'Resolving ' + key + (parent ? ' to ' + parent : '')); - }); -}; - -// 3.3.4 (import without evaluate) -// this is not documented because the use of deferred evaluation as in Module.evaluate is not -// documented, as it is not considered a stable feature to be encouraged -// Loader.prototype.load may well be deprecated if this stays disabled -/* Loader.prototype.load = function (key, parent) { - return Promise.resolve(this[RESOLVE_INSTANTIATE](key, parent || this.key)) - .catch(function (err) { - throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : '')); - }); -}; */ - -/* - * 4. Registry - * - * Instead of structuring through a Map, just use a dictionary object - * We throw for construction attempts so this doesn't affect the public API - * - * Registry has been adjusted to use Namespace objects over ModuleStatus objects - * as part of simplifying loader API implementation - */ -var iteratorSupport = typeof Symbol !== 'undefined' && Symbol.iterator; -var REGISTRY = createSymbol('registry'); -function Registry() { - this[REGISTRY] = {}; -} -// 4.4.1 -if (iteratorSupport) { - // 4.4.2 - Registry.prototype[Symbol.iterator] = function () { - return this.entries()[Symbol.iterator](); + // 3.3.3 + var RESOLVE = Loader.resolve = createSymbol('resolve'); + + /* + * Combined resolve / instantiate hook + * + * Not in current reduced spec, but necessary to separate RESOLVE from RESOLVE + INSTANTIATE as described + * in the spec notes of this repo to ensure that loader.resolve doesn't instantiate when not wanted. + * + * We implement RESOLVE_INSTANTIATE as a single hook instead of a separate INSTANTIATE in order to avoid + * the need for double registry lookups as a performance optimization. + */ + var RESOLVE_INSTANTIATE = Loader.resolveInstantiate = createSymbol('resolveInstantiate'); + + // default resolveInstantiate is just to call resolve and then get from the registry + // this provides compatibility for the resolveInstantiate optimization + Loader.prototype[RESOLVE_INSTANTIATE] = function (key, parent) { + var loader = this; + return loader.resolve(key, parent) + .then(function (resolved) { + return loader.registry.get(resolved); + }); }; - // 4.4.3 - Registry.prototype.entries = function () { + function ensureResolution (resolvedKey) { + if (resolvedKey === undefined) + throw new RangeError('No resolution found.'); + return resolvedKey; + } + + Loader.prototype.resolve = function (key, parent) { + var loader = this; + return resolvedPromise + .then(function() { + return loader[RESOLVE](key, parent); + }) + .then(ensureResolution) + .catch(function (err) { + throw LoaderError__Check_error_message_for_loader_stack(err, 'Resolving ' + key + (parent ? ' to ' + parent : '')); + }); + }; + + // 3.3.4 (import without evaluate) + // this is not documented because the use of deferred evaluation as in Module.evaluate is not + // documented, as it is not considered a stable feature to be encouraged + // Loader.prototype.load may well be deprecated if this stays disabled + /* Loader.prototype.load = function (key, parent) { + return Promise.resolve(this[RESOLVE_INSTANTIATE](key, parent || this.key)) + .catch(function (err) { + throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : '')); + }); + }; */ + + /* + * 4. Registry + * + * Instead of structuring through a Map, just use a dictionary object + * We throw for construction attempts so this doesn't affect the public API + * + * Registry has been adjusted to use Namespace objects over ModuleStatus objects + * as part of simplifying loader API implementation + */ + var iteratorSupport = typeof Symbol !== 'undefined' && Symbol.iterator; + var REGISTRY = createSymbol('registry'); + function Registry() { + this[REGISTRY] = {}; + } + // 4.4.1 + if (iteratorSupport) { + // 4.4.2 + Registry.prototype[Symbol.iterator] = function () { + return this.entries()[Symbol.iterator](); + }; + + // 4.4.3 + Registry.prototype.entries = function () { + var registry = this[REGISTRY]; + return arrayValues(Object.keys(registry).map(function (key) { + return [key, registry[key]]; + })); + }; + } + + // 4.4.4 + Registry.prototype.keys = function () { + return arrayValues(Object.keys(this[REGISTRY])); + }; + // 4.4.5 + Registry.prototype.values = function () { var registry = this[REGISTRY]; return arrayValues(Object.keys(registry).map(function (key) { - return [key, registry[key]]; + return registry[key]; })); }; -} - -// 4.4.4 -Registry.prototype.keys = function () { - return arrayValues(Object.keys(this[REGISTRY])); -}; -// 4.4.5 -Registry.prototype.values = function () { - var registry = this[REGISTRY]; - return arrayValues(Object.keys(registry).map(function (key) { - return registry[key]; - })); -}; -// 4.4.6 -Registry.prototype.get = function (key) { - return this[REGISTRY][key]; -}; -// 4.4.7 -Registry.prototype.set = function (key, namespace) { - if (!(namespace instanceof ModuleNamespace || namespace[toStringTag] === 'module')) - throw new Error('Registry must be set with an instance of Module Namespace'); - this[REGISTRY][key] = namespace; - return this; -}; -// 4.4.8 -Registry.prototype.has = function (key) { - return Object.hasOwnProperty.call(this[REGISTRY], key); -}; -// 4.4.9 -Registry.prototype.delete = function (key) { - if (Object.hasOwnProperty.call(this[REGISTRY], key)) { - delete this[REGISTRY][key]; - return true; - } - return false; -}; - -/* - * Simple ModuleNamespace Exotic object based on a baseObject - * We export this for allowing a fast-path for module namespace creation over Module descriptors - */ -// var EVALUATE = createSymbol('evaluate'); -var BASE_OBJECT = createSymbol('baseObject'); - -// 8.3.1 Reflect.Module -/* - * Best-effort simplified non-spec implementation based on - * a baseObject referenced via getters. - * - * Allows: - * - * loader.registry.set('x', new Module({ default: 'x' })); - * - * Optional evaluation function provides experimental Module.evaluate - * support for non-executed modules in registry. - */ -function ModuleNamespace (baseObject/*, evaluate*/) { - Object.defineProperty(this, BASE_OBJECT, { - value: baseObject - }); - - // evaluate defers namespace population - /* if (evaluate) { - Object.defineProperty(this, EVALUATE, { - value: evaluate, - configurable: true, - writable: true + // 4.4.6 + Registry.prototype.get = function (key) { + return this[REGISTRY][key]; + }; + // 4.4.7 + Registry.prototype.set = function (key, namespace) { + if (!(namespace instanceof ModuleNamespace || namespace[toStringTag] === 'module')) + throw new Error('Registry must be set with an instance of Module Namespace'); + this[REGISTRY][key] = namespace; + return this; + }; + // 4.4.8 + Registry.prototype.has = function (key) { + return Object.hasOwnProperty.call(this[REGISTRY], key); + }; + // 4.4.9 + Registry.prototype.delete = function (key) { + if (Object.hasOwnProperty.call(this[REGISTRY], key)) { + delete this[REGISTRY][key]; + return true; + } + return false; + }; + + /* + * Simple ModuleNamespace Exotic object based on a baseObject + * We export this for allowing a fast-path for module namespace creation over Module descriptors + */ + // var EVALUATE = createSymbol('evaluate'); + var BASE_OBJECT = createSymbol('baseObject'); + + // 8.3.1 Reflect.Module + /* + * Best-effort simplified non-spec implementation based on + * a baseObject referenced via getters. + * + * Allows: + * + * loader.registry.set('x', new Module({ default: 'x' })); + * + * Optional evaluation function provides experimental Module.evaluate + * support for non-executed modules in registry. + */ + function ModuleNamespace (baseObject/*, evaluate*/) { + Object.defineProperty(this, BASE_OBJECT, { + value: baseObject }); - } - else { */ - Object.keys(baseObject).forEach(extendNamespace, this); - //} -} -// 8.4.2 -ModuleNamespace.prototype = Object.create(null); - -if (toStringTag) - Object.defineProperty(ModuleNamespace.prototype, toStringTag, { - value: 'Module' - }); - -function extendNamespace (key) { - Object.defineProperty(this, key, { - enumerable: true, - get: function () { - return this[BASE_OBJECT][key]; + + // evaluate defers namespace population + /* if (evaluate) { + Object.defineProperty(this, EVALUATE, { + value: evaluate, + configurable: true, + writable: true + }); } - }); -} + else { */ + Object.keys(baseObject).forEach(extendNamespace, this); + //} + }// 8.4.2 + ModuleNamespace.prototype = Object.create(null); + + if (toStringTag) + Object.defineProperty(ModuleNamespace.prototype, toStringTag, { + value: 'Module' + }); -/* function doEvaluate (evaluate, context) { - try { - evaluate.call(context); + function extendNamespace (key) { + Object.defineProperty(this, key, { + enumerable: true, + get: function () { + return this[BASE_OBJECT][key]; + } + }); } - catch (e) { - return e; + + /* function doEvaluate (evaluate, context) { + try { + evaluate.call(context); + } + catch (e) { + return e; + } } -} - -// 8.4.1 Module.evaluate... not documented or used because this is potentially unstable -Module.evaluate = function (ns) { - var evaluate = ns[EVALUATE]; - if (evaluate) { - ns[EVALUATE] = undefined; - var err = doEvaluate(evaluate); - if (err) { - // cache the error - ns[EVALUATE] = function () { + + // 8.4.1 Module.evaluate... not documented or used because this is potentially unstable + Module.evaluate = function (ns) { + var evaluate = ns[EVALUATE]; + if (evaluate) { + ns[EVALUATE] = undefined; + var err = doEvaluate(evaluate); + if (err) { + // cache the error + ns[EVALUATE] = function () { + throw err; + }; throw err; - }; - throw err; + } + Object.keys(ns[BASE_OBJECT]).forEach(extendNamespace, ns); } - Object.keys(ns[BASE_OBJECT]).forEach(extendNamespace, ns); - } - // make chainable - return ns; -}; */ + // make chainable + return ns; + }; */ -/* - * Optimized URL normalization assuming a syntax-valid URL parent - */ -function throwResolveError (relUrl, parentUrl) { - throw new RangeError('Unable to resolve "' + relUrl + '" to ' + parentUrl); -} -var backslashRegEx = /\\/g; -function resolveIfNotPlain (relUrl, parentUrl) { - if (relUrl[0] === ' ' || relUrl[relUrl.length - 1] === ' ') - relUrl = relUrl.trim(); - var parentProtocol = parentUrl && parentUrl.substr(0, parentUrl.indexOf(':') + 1); - - var firstChar = relUrl[0]; - var secondChar = relUrl[1]; - - // protocol-relative - if (firstChar === '/' && secondChar === '/') { - if (!parentProtocol) - throwResolveError(relUrl, parentUrl); - if (relUrl.indexOf('\\') !== -1) - relUrl = relUrl.replace(backslashRegEx, '/'); - return parentProtocol + relUrl; + /* + * Optimized URL normalization assuming a syntax-valid URL parent + */ + function throwResolveError (relUrl, parentUrl) { + throw new RangeError('Unable to resolve "' + relUrl + '" to ' + parentUrl); } - // relative-url - else if (firstChar === '.' && (secondChar === '/' || secondChar === '.' && (relUrl[2] === '/' || relUrl.length === 2 && (relUrl += '/')) || - relUrl.length === 1 && (relUrl += '/')) || - firstChar === '/') { - if (relUrl.indexOf('\\') !== -1) - relUrl = relUrl.replace(backslashRegEx, '/'); - var parentIsPlain = !parentProtocol || parentUrl[parentProtocol.length] !== '/'; - - // read pathname from parent if a URL - // pathname taken to be part after leading "/" - var pathname; - if (parentIsPlain) { - // resolving to a plain parent -> skip standard URL prefix, and treat entire parent as pathname - if (parentUrl === undefined) + var backslashRegEx = /\\/g; + function resolveIfNotPlain (relUrl, parentUrl) { + if (relUrl[0] === ' ' || relUrl[relUrl.length - 1] === ' ') + relUrl = relUrl.trim(); + var parentProtocol = parentUrl && parentUrl.substr(0, parentUrl.indexOf(':') + 1); + + var firstChar = relUrl[0]; + var secondChar = relUrl[1]; + + // protocol-relative + if (firstChar === '/' && secondChar === '/') { + if (!parentProtocol) throwResolveError(relUrl, parentUrl); - pathname = parentUrl; + if (relUrl.indexOf('\\') !== -1) + relUrl = relUrl.replace(backslashRegEx, '/'); + return parentProtocol + relUrl; } - else if (parentUrl[parentProtocol.length + 1] === '/') { - // resolving to a :// so we need to read out the auth and host - if (parentProtocol !== 'file:') { - pathname = parentUrl.substr(parentProtocol.length + 2); - pathname = pathname.substr(pathname.indexOf('/') + 1); + // relative-url + else if (firstChar === '.' && (secondChar === '/' || secondChar === '.' && (relUrl[2] === '/' || relUrl.length === 2 && (relUrl += '/')) || + relUrl.length === 1 && (relUrl += '/')) || + firstChar === '/') { + if (relUrl.indexOf('\\') !== -1) + relUrl = relUrl.replace(backslashRegEx, '/'); + var parentIsPlain = !parentProtocol || parentUrl[parentProtocol.length] !== '/'; + + // read pathname from parent if a URL + // pathname taken to be part after leading "/" + var pathname; + if (parentIsPlain) { + // resolving to a plain parent -> skip standard URL prefix, and treat entire parent as pathname + if (parentUrl === undefined) + throwResolveError(relUrl, parentUrl); + pathname = parentUrl; + } + else if (parentUrl[parentProtocol.length + 1] === '/') { + // resolving to a :// so we need to read out the auth and host + if (parentProtocol !== 'file:') { + pathname = parentUrl.substr(parentProtocol.length + 2); + pathname = pathname.substr(pathname.indexOf('/') + 1); + } + else { + pathname = parentUrl.substr(8); + } } else { - pathname = parentUrl.substr(8); + // resolving to :/ so pathname is the /... part + pathname = parentUrl.substr(parentProtocol.length + 1); } - } - else { - // resolving to :/ so pathname is the /... part - pathname = parentUrl.substr(parentProtocol.length + 1); - } - if (firstChar === '/') { - if (parentIsPlain) - throwResolveError(relUrl, parentUrl); - else - return parentUrl.substr(0, parentUrl.length - pathname.length - 1) + relUrl; - } + if (firstChar === '/') { + if (parentIsPlain) + throwResolveError(relUrl, parentUrl); + else + return parentUrl.substr(0, parentUrl.length - pathname.length - 1) + relUrl; + } - // join together and split for removal of .. and . segments - // looping the string instead of anything fancy for perf reasons - // '../../../../../z' resolved to 'x/y' is just 'z' regardless of parentIsPlain - var segmented = pathname.substr(0, pathname.lastIndexOf('/') + 1) + relUrl; + // join together and split for removal of .. and . segments + // looping the string instead of anything fancy for perf reasons + // '../../../../../z' resolved to 'x/y' is just 'z' regardless of parentIsPlain + var segmented = pathname.substr(0, pathname.lastIndexOf('/') + 1) + relUrl; - var output = []; - var segmentIndex = -1; + var output = []; + var segmentIndex = -1; - for (var i = 0; i < segmented.length; i++) { - // busy reading a segment - only terminate on '/' - if (segmentIndex !== -1) { - if (segmented[i] === '/') { - output.push(segmented.substring(segmentIndex, i + 1)); - segmentIndex = -1; + for (var i = 0; i < segmented.length; i++) { + // busy reading a segment - only terminate on '/' + if (segmentIndex !== -1) { + if (segmented[i] === '/') { + output.push(segmented.substring(segmentIndex, i + 1)); + segmentIndex = -1; + } + continue; } - continue; - } - // new segment - check if it is relative - if (segmented[i] === '.') { - // ../ segment - if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) { - output.pop(); - i += 2; - } - // ./ segment - else if (segmented[i + 1] === '/' || i + 1 === segmented.length) { - i += 1; - } - else { - // the start of a new segment as below - segmentIndex = i; + // new segment - check if it is relative + if (segmented[i] === '.') { + // ../ segment + if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) { + output.pop(); + i += 2; + } + // ./ segment + else if (segmented[i + 1] === '/' || i + 1 === segmented.length) { + i += 1; + } + else { + // the start of a new segment as below + segmentIndex = i; + continue; + } + + // this is the plain URI backtracking error (../, package:x -> error) + if (parentIsPlain && output.length === 0) + throwResolveError(relUrl, parentUrl); + continue; } - // this is the plain URI backtracking error (../, package:x -> error) - if (parentIsPlain && output.length === 0) - throwResolveError(relUrl, parentUrl); - - continue; + // it is the start of a new segment + segmentIndex = i; } + // finish reading out the last segment + if (segmentIndex !== -1) + output.push(segmented.substr(segmentIndex)); - // it is the start of a new segment - segmentIndex = i; + return parentUrl.substr(0, parentUrl.length - pathname.length) + output.join(''); } - // finish reading out the last segment - if (segmentIndex !== -1) - output.push(segmented.substr(segmentIndex)); - return parentUrl.substr(0, parentUrl.length - pathname.length) + output.join(''); - } - - // sanitizes and verifies (by returning undefined if not a valid URL-like form) - // Windows filepath compatibility is an added convenience here - var protocolIndex = relUrl.indexOf(':'); - if (protocolIndex !== -1) { - if (isNode) { - // C:\x becomes file:///c:/x (we don't support C|\x) - if (relUrl[1] === ':' && relUrl[2] === '\\' && relUrl[0].match(/[a-z]/i)) - return 'file:///' + relUrl.replace(backslashRegEx, '/'); + // sanitizes and verifies (by returning undefined if not a valid URL-like form) + // Windows filepath compatibility is an added convenience here + var protocolIndex = relUrl.indexOf(':'); + if (protocolIndex !== -1) { + if (isNode) { + // C:\x becomes file:///c:/x (we don't support C|\x) + if (relUrl[1] === ':' && relUrl[2] === '\\' && relUrl[0].match(/[a-z]/i)) + return 'file:///' + relUrl.replace(backslashRegEx, '/'); + } + return relUrl; } - return relUrl; - } -} + } -var resolvedPromise = Promise.resolve(); -/* - * Register Loader - * - * Builds directly on top of loader polyfill to provide: - * - loader.register support - * - hookable higher-level resolve - * - instantiate hook returning a ModuleNamespace or undefined for es module loading - * - loader error behaviour as in HTML and loader specs, caching load and eval errors separately - * - build tracing support by providing a .trace=true and .loads object format - */ - -var REGISTER_INTERNAL = createSymbol('register-internal'); - -function RegisterLoader$1 () { - Loader.call(this); - - var registryDelete = this.registry.delete; - this.registry.delete = function (key) { - var deleted = registryDelete.call(this, key); - - // also delete from register registry if linked - if (records.hasOwnProperty(key) && !records[key].linkRecord) { - delete records[key]; - deleted = true; - } - - return deleted; - }; - - var records = {}; - - this[REGISTER_INTERNAL] = { - // last anonymous System.register call - lastRegister: undefined, - // in-flight es module load records - records: records - }; + var resolvedPromise$1 = Promise.resolve(); + + /* + * Register Loader + * + * Builds directly on top of loader polyfill to provide: + * - loader.register support + * - hookable higher-level resolve + * - instantiate hook returning a ModuleNamespace or undefined for es module loading + * - loader error behaviour as in HTML and loader specs, caching load and eval errors separately + * - build tracing support by providing a .trace=true and .loads object format + */ + + var REGISTER_INTERNAL = createSymbol('register-internal'); + + function RegisterLoader () { + Loader.call(this); + + var registryDelete = this.registry.delete; + this.registry.delete = function (key) { + var deleted = registryDelete.call(this, key); + + // also delete from register registry if linked + if (records.hasOwnProperty(key) && !records[key].linkRecord) { + delete records[key]; + deleted = true; + } - // tracing - this.trace = false; -} + return deleted; + }; -RegisterLoader$1.prototype = Object.create(Loader.prototype); -RegisterLoader$1.prototype.constructor = RegisterLoader$1; + var records = {}; -var INSTANTIATE = RegisterLoader$1.instantiate = createSymbol('instantiate'); + this[REGISTER_INTERNAL] = { + // last anonymous System.register call + lastRegister: undefined, + // in-flight es module load records + records: records + }; -// default normalize is the WhatWG style normalizer -RegisterLoader$1.prototype[RegisterLoader$1.resolve = Loader.resolve] = function (key, parentKey) { - return resolveIfNotPlain(key, parentKey || baseURI); -}; + // tracing + this.trace = false; + } -RegisterLoader$1.prototype[INSTANTIATE] = function (key, processAnonRegister) {}; + RegisterLoader.prototype = Object.create(Loader.prototype); + RegisterLoader.prototype.constructor = RegisterLoader; -// once evaluated, the linkRecord is set to undefined leaving just the other load record properties -// this allows tracking new binding listeners for es modules through importerSetters -// for dynamic modules, the load record is removed entirely. -function createLoadRecord (state, key, registration) { - return state.records[key] = { - key: key, + var INSTANTIATE = RegisterLoader.instantiate = createSymbol('instantiate'); - // defined System.register cache - registration: registration, + // default normalize is the WhatWG style normalizer + RegisterLoader.prototype[RegisterLoader.resolve = Loader.resolve] = function (key, parentKey) { + return resolveIfNotPlain(key, parentKey || baseURI); + }; - // module namespace object - module: undefined, + RegisterLoader.prototype[INSTANTIATE] = function (key, processAnonRegister) {}; + + // once evaluated, the linkRecord is set to undefined leaving just the other load record properties + // this allows tracking new binding listeners for es modules through importerSetters + // for dynamic modules, the load record is removed entirely. + function createLoadRecord (state, key, registration) { + return state.records[key] = { + key: key, + + // defined System.register cache + registration: registration, + + // module namespace object + module: undefined, + + // es-only + // this sticks around so new module loads can listen to binding changes + // for already-loaded modules by adding themselves to their importerSetters + importerSetters: undefined, + + loadError: undefined, + evalError: undefined, + + // in-flight linking record + linkRecord: { + // promise for instantiated + instantiatePromise: undefined, + dependencies: undefined, + execute: undefined, + executingRequire: false, + + // underlying module object bindings + moduleObj: undefined, + + // es only, also indicates if es or not + setters: undefined, + + // promise for instantiated dependencies (dependencyInstantiations populated) + depsInstantiatePromise: undefined, + // will be the array of dependency load record or a module namespace + dependencyInstantiations: undefined, + + // top-level await! + evaluatePromise: undefined, + + // NB optimization and way of ensuring module objects in setters + // indicates setters which should run pre-execution of that dependency + // setters is then just for completely executed module objects + // alternatively we just pass the partially filled module objects as + // arguments into the execute function + // hoisted: undefined + } + }; + } - // es-only - // this sticks around so new module loads can listen to binding changes - // for already-loaded modules by adding themselves to their importerSetters - importerSetters: undefined, + RegisterLoader.prototype[Loader.resolveInstantiate] = function (key, parentKey) { + var loader = this; + var state = this[REGISTER_INTERNAL]; + var registry = this.registry[REGISTRY]; - loadError: undefined, - evalError: undefined, + return resolveInstantiate(loader, key, parentKey, registry, state) + .then(function (instantiated) { + if (instantiated instanceof ModuleNamespace || instantiated[toStringTag] === 'module') + return instantiated; - // in-flight linking record - linkRecord: { - // promise for instantiated - instantiatePromise: undefined, - dependencies: undefined, - execute: undefined, - executingRequire: false, + // resolveInstantiate always returns a load record with a link record and no module value + var link = instantiated.linkRecord; - // underlying module object bindings - moduleObj: undefined, + // if already beaten to done, return + if (!link) { + if (instantiated.module) + return instantiated.module; + throw instantiated.evalError; + } - // es only, also indicates if es or not - setters: undefined, + return deepInstantiateDeps(loader, instantiated, link, registry, state) + .then(function () { + return ensureEvaluate(loader, instantiated, link, registry, state); + }); + }); + }; - // promise for instantiated dependencies (dependencyInstantiations populated) - depsInstantiatePromise: undefined, - // will be the array of dependency load record or a module namespace - dependencyInstantiations: undefined, + function resolveInstantiate (loader, key, parentKey, registry, state) { + // normalization shortpath for already-normalized key + // could add a plain name filter, but doesn't yet seem necessary for perf + var module = registry[key]; + if (module) + return Promise.resolve(module); - // top-level await! - evaluatePromise: undefined, + var load = state.records[key]; - // NB optimization and way of ensuring module objects in setters - // indicates setters which should run pre-execution of that dependency - // setters is then just for completely executed module objects - // alternatively we just pass the partially filled module objects as - // arguments into the execute function - // hoisted: undefined - } - }; -} - -RegisterLoader$1.prototype[Loader.resolveInstantiate] = function (key, parentKey) { - var loader = this; - var state = this[REGISTER_INTERNAL]; - var registry = this.registry[REGISTRY]; - - return resolveInstantiate(loader, key, parentKey, registry, state) - .then(function (instantiated) { - if (instantiated instanceof ModuleNamespace || instantiated[toStringTag] === 'module') - return instantiated; - - // resolveInstantiate always returns a load record with a link record and no module value - var link = instantiated.linkRecord; - - // if already beaten to done, return - if (!link) { - if (instantiated.module) - return instantiated.module; - throw instantiated.evalError; + // already linked but not in main registry is ignored + if (load && !load.module) { + if (load.loadError) + return Promise.reject(load.loadError); + return instantiate(loader, load, load.linkRecord, registry, state); } - return deepInstantiateDeps(loader, instantiated, link, registry, state) - .then(function () { - return ensureEvaluate(loader, instantiated, link, registry, state); - }); - }); -}; - -function resolveInstantiate (loader, key, parentKey, registry, state) { - // normalization shortpath for already-normalized key - // could add a plain name filter, but doesn't yet seem necessary for perf - var module = registry[key]; - if (module) - return Promise.resolve(module); - - var load = state.records[key]; - - // already linked but not in main registry is ignored - if (load && !load.module) { - if (load.loadError) - return Promise.reject(load.loadError); - return instantiate(loader, load, load.linkRecord, registry, state); - } + return loader.resolve(key, parentKey) + .then(function (resolvedKey) { + // main loader registry always takes preference + module = registry[resolvedKey]; + if (module) + return module; - return loader.resolve(key, parentKey) - .then(function (resolvedKey) { - // main loader registry always takes preference - module = registry[resolvedKey]; - if (module) - return module; + load = state.records[resolvedKey]; - load = state.records[resolvedKey]; + // already has a module value but not already in the registry (load.module) + // means it was removed by registry.delete, so we should + // disgard the current load record creating a new one over it + // but keep any existing registration + if (!load || load.module) + load = createLoadRecord(state, resolvedKey, load && load.registration); - // already has a module value but not already in the registry (load.module) - // means it was removed by registry.delete, so we should - // disgard the current load record creating a new one over it - // but keep any existing registration - if (!load || load.module) - load = createLoadRecord(state, resolvedKey, load && load.registration); + if (load.loadError) + return Promise.reject(load.loadError); - if (load.loadError) - return Promise.reject(load.loadError); + var link = load.linkRecord; + if (!link) + return load; - var link = load.linkRecord; - if (!link) - return load; + return instantiate(loader, load, link, registry, state); + }); + } - return instantiate(loader, load, link, registry, state); - }); -} + function createProcessAnonRegister (loader, load, state) { + return function () { + var lastRegister = state.lastRegister; -function createProcessAnonRegister (loader, load, state) { - return function () { - var lastRegister = state.lastRegister; + if (!lastRegister) + return !!load.registration; - if (!lastRegister) - return !!load.registration; + state.lastRegister = undefined; + load.registration = lastRegister; - state.lastRegister = undefined; - load.registration = lastRegister; + return true; + }; + } - return true; - }; -} - -function instantiate (loader, load, link, registry, state) { - return link.instantiatePromise || (link.instantiatePromise = - // if there is already an existing registration, skip running instantiate - (load.registration ? resolvedPromise : resolvedPromise.then(function () { - state.lastRegister = undefined; - return loader[INSTANTIATE](load.key, loader[INSTANTIATE].length > 1 && createProcessAnonRegister(loader, load, state)); - })) - .then(function (instantiation) { - // direct module return from instantiate -> we're done - if (instantiation !== undefined) { - if (!(instantiation instanceof ModuleNamespace || instantiation[toStringTag] === 'module')) - throw new TypeError('Instantiate did not return a valid Module object.'); - - delete state.records[load.key]; - if (loader.trace) - traceLoad(loader, load, link); - return registry[load.key] = instantiation; - } + function instantiate (loader, load, link, registry, state) { + return link.instantiatePromise || (link.instantiatePromise = + // if there is already an existing registration, skip running instantiate + (load.registration ? resolvedPromise$1 : resolvedPromise$1.then(function () { + state.lastRegister = undefined; + return loader[INSTANTIATE](load.key, loader[INSTANTIATE].length > 1 && createProcessAnonRegister(loader, load, state)); + })) + .then(function (instantiation) { + // direct module return from instantiate -> we're done + if (instantiation !== undefined) { + if (!(instantiation instanceof ModuleNamespace || instantiation[toStringTag] === 'module')) + throw new TypeError('Instantiate did not return a valid Module object.'); + + delete state.records[load.key]; + if (loader.trace) + traceLoad(loader, load, link); + return registry[load.key] = instantiation; + } - // run the cached loader.register declaration if there is one - var registration = load.registration; - // clear to allow new registrations for future loads (combined with registry delete) - load.registration = undefined; - if (!registration) - throw new TypeError('Module instantiation did not call an anonymous or correctly named System.register.'); + // run the cached loader.register declaration if there is one + var registration = load.registration; + // clear to allow new registrations for future loads (combined with registry delete) + load.registration = undefined; + if (!registration) + throw new TypeError('Module instantiation did not call an anonymous or correctly named System.register.'); - link.dependencies = registration[0]; + link.dependencies = registration[0]; - load.importerSetters = []; + load.importerSetters = []; - link.moduleObj = {}; + link.moduleObj = {}; - // process System.registerDynamic declaration - if (registration[2]) { - link.moduleObj.default = link.moduleObj.__useDefault = {}; - link.executingRequire = registration[1]; - link.execute = registration[2]; - } + // process System.registerDynamic declaration + if (registration[2]) { + link.moduleObj.default = link.moduleObj.__useDefault = {}; + link.executingRequire = registration[1]; + link.execute = registration[2]; + } - // process System.register declaration - else { - registerDeclarative(loader, load, link, registration[1]); - } + // process System.register declaration + else { + registerDeclarative(loader, load, link, registration[1]); + } - return load; - }) - .catch(function (err) { - load.linkRecord = undefined; - throw load.loadError = load.loadError || LoaderError__Check_error_message_for_loader_stack(err, 'Instantiating ' + load.key); - })); -} - -// like resolveInstantiate, but returning load records for linking -function resolveInstantiateDep (loader, key, parentKey, registry, state, traceDepMap) { - // normalization shortpaths for already-normalized key - // DISABLED to prioritise consistent resolver calls - // could add a plain name filter, but doesn't yet seem necessary for perf - /* var load = state.records[key]; - var module = registry[key]; - - if (module) { - if (traceDepMap) - traceDepMap[key] = key; - - // registry authority check in case module was deleted or replaced in main registry - if (load && load.module && load.module === module) return load; - else - return module; + }) + .catch(function (err) { + load.linkRecord = undefined; + throw load.loadError = load.loadError || LoaderError__Check_error_message_for_loader_stack(err, 'Instantiating ' + load.key); + })); } - // already linked but not in main registry is ignored - if (load && !load.module) { - if (traceDepMap) - traceDepMap[key] = key; - return instantiate(loader, load, load.linkRecord, registry, state); - } */ - return loader.resolve(key, parentKey) - .then(function (resolvedKey) { - if (traceDepMap) - traceDepMap[key] = resolvedKey; - + // like resolveInstantiate, but returning load records for linking + function resolveInstantiateDep (loader, key, parentKey, registry, state, traceDepMap) { // normalization shortpaths for already-normalized key - var load = state.records[resolvedKey]; - var module = registry[resolvedKey]; - - // main loader registry always takes preference - if (module && (!load || load.module && module !== load.module)) - return module; - - if (load && load.loadError) - throw load.loadError; + // DISABLED to prioritise consistent resolver calls + // could add a plain name filter, but doesn't yet seem necessary for perf + /* var load = state.records[key]; + var module = registry[key]; + + if (module) { + if (traceDepMap) + traceDepMap[key] = key; + + // registry authority check in case module was deleted or replaced in main registry + if (load && load.module && load.module === module) + return load; + else + return module; + } - // already has a module value but not already in the registry (load.module) - // means it was removed by registry.delete, so we should - // disgard the current load record creating a new one over it - // but keep any existing registration - if (!load || !module && load.module) - load = createLoadRecord(state, resolvedKey, load && load.registration); + // already linked but not in main registry is ignored + if (load && !load.module) { + if (traceDepMap) + traceDepMap[key] = key; + return instantiate(loader, load, load.linkRecord, registry, state); + } */ + return loader.resolve(key, parentKey) + .then(function (resolvedKey) { + if (traceDepMap) + traceDepMap[key] = resolvedKey; + + // normalization shortpaths for already-normalized key + var load = state.records[resolvedKey]; + var module = registry[resolvedKey]; + + // main loader registry always takes preference + if (module && (!load || load.module && module !== load.module)) + return module; + + if (load && load.loadError) + throw load.loadError; + + // already has a module value but not already in the registry (load.module) + // means it was removed by registry.delete, so we should + // disgard the current load record creating a new one over it + // but keep any existing registration + if (!load || !module && load.module) + load = createLoadRecord(state, resolvedKey, load && load.registration); + + var link = load.linkRecord; + if (!link) + return load; + + return instantiate(loader, load, link, registry, state); + }); + } - var link = load.linkRecord; - if (!link) - return load; + function traceLoad (loader, load, link) { + loader.loads = loader.loads || {}; + loader.loads[load.key] = { + key: load.key, + deps: link.dependencies, + dynamicDeps: [], + depMap: link.depMap || {} + }; + } - return instantiate(loader, load, link, registry, state); - }); -} - -function traceLoad (loader, load, link) { - loader.loads = loader.loads || {}; - loader.loads[load.key] = { - key: load.key, - deps: link.dependencies, - dynamicDeps: [], - depMap: link.depMap || {} - }; -} - -/* - * Convert a CJS module.exports into a valid object for new Module: - * - * new Module(getEsModule(module.exports)) - * - * Sets the default value to the module, while also reading off named exports carefully. - */ -function registerDeclarative (loader, load, link, declare) { - var moduleObj = link.moduleObj; - var importerSetters = load.importerSetters; - - var definedExports = false; - - // closure especially not based on link to allow link record disposal - var declared = declare.call(envGlobal, function (name, value) { - if (typeof name === 'object') { - var changed = false; - for (var p in name) { - value = name[p]; - if (p !== '__useDefault' && (!(p in moduleObj) || moduleObj[p] !== value)) { - changed = true; - moduleObj[p] = value; + /* + * Convert a CJS module.exports into a valid object for new Module: + * + * new Module(getEsModule(module.exports)) + * + * Sets the default value to the module, while also reading off named exports carefully. + */ + function registerDeclarative (loader, load, link, declare) { + var moduleObj = link.moduleObj; + var importerSetters = load.importerSetters; + + var definedExports = false; + + // closure especially not based on link to allow link record disposal + var declared = declare.call(envGlobal, function (name, value) { + if (typeof name === 'object') { + var changed = false; + for (var p in name) { + value = name[p]; + if (p !== '__useDefault' && (!(p in moduleObj) || moduleObj[p] !== value)) { + changed = true; + moduleObj[p] = value; + } } + if (changed === false) + return value; + } + else { + if ((definedExports || name in moduleObj) && moduleObj[name] === value) + return value; + moduleObj[name] = value; } - if (changed === false) - return value; - } - else { - if ((definedExports || name in moduleObj) && moduleObj[name] === value) - return value; - moduleObj[name] = value; - } - for (var i = 0; i < importerSetters.length; i++) - importerSetters[i](moduleObj); + for (var i = 0; i < importerSetters.length; i++) + importerSetters[i](moduleObj); - return value; - }, new ContextualLoader(loader, load.key)); + return value; + }, new ContextualLoader(loader, load.key)); - link.setters = declared.setters || []; - link.execute = declared.execute; - if (declared.exports) { - link.moduleObj = moduleObj = declared.exports; - definedExports = true; + link.setters = declared.setters || []; + link.execute = declared.execute; + if (declared.exports) { + link.moduleObj = moduleObj = declared.exports; + definedExports = true; + } } -} -function instantiateDeps (loader, load, link, registry, state) { - if (link.depsInstantiatePromise) - return link.depsInstantiatePromise; + function instantiateDeps (loader, load, link, registry, state) { + if (link.depsInstantiatePromise) + return link.depsInstantiatePromise; - var depsInstantiatePromises = Array(link.dependencies.length); + var depsInstantiatePromises = Array(link.dependencies.length); - for (var i = 0; i < link.dependencies.length; i++) - depsInstantiatePromises[i] = resolveInstantiateDep(loader, link.dependencies[i], load.key, registry, state, loader.trace && link.depMap || (link.depMap = {})); + for (var i = 0; i < link.dependencies.length; i++) + depsInstantiatePromises[i] = resolveInstantiateDep(loader, link.dependencies[i], load.key, registry, state, loader.trace && link.depMap || (link.depMap = {})); - var depsInstantiatePromise = Promise.all(depsInstantiatePromises) - .then(function (dependencyInstantiations) { - link.dependencyInstantiations = dependencyInstantiations; + var depsInstantiatePromise = Promise.all(depsInstantiatePromises) + .then(function (dependencyInstantiations) { + link.dependencyInstantiations = dependencyInstantiations; - // run setters to set up bindings to instantiated dependencies - if (link.setters) { - for (var i = 0; i < dependencyInstantiations.length; i++) { - var setter = link.setters[i]; - if (setter) { - var instantiation = dependencyInstantiations[i]; + // run setters to set up bindings to instantiated dependencies + if (link.setters) { + for (var i = 0; i < dependencyInstantiations.length; i++) { + var setter = link.setters[i]; + if (setter) { + var instantiation = dependencyInstantiations[i]; - if (instantiation instanceof ModuleNamespace || instantiation[toStringTag] === 'module') { - setter(instantiation); - } - else { - if (instantiation.loadError) - throw instantiation.loadError; - setter(instantiation.module || instantiation.linkRecord.moduleObj); - // this applies to both es and dynamic registrations - if (instantiation.importerSetters) - instantiation.importerSetters.push(setter); + if (instantiation instanceof ModuleNamespace || instantiation[toStringTag] === 'module') { + setter(instantiation); + } + else { + if (instantiation.loadError) + throw instantiation.loadError; + setter(instantiation.module || instantiation.linkRecord.moduleObj); + // this applies to both es and dynamic registrations + if (instantiation.importerSetters) + instantiation.importerSetters.push(setter); + } } } } - } - return load; - }); - - if (loader.trace) - depsInstantiatePromise = depsInstantiatePromise.then(function () { - traceLoad(loader, load, link); return load; }); - depsInstantiatePromise = depsInstantiatePromise.catch(function (err) { - // throw up the instantiateDeps stack - link.depsInstantiatePromise = undefined; - throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + load.key); - }); - - depsInstantiatePromise.catch(function () {}); - - return link.depsInstantiatePromise = depsInstantiatePromise; -} - -function deepInstantiateDeps (loader, load, link, registry, state) { - var seen = []; - function addDeps (load, link) { - if (!link) - return resolvedPromise; - if (seen.indexOf(load) !== -1) - return resolvedPromise; - seen.push(load); - - return instantiateDeps(loader, load, link, registry, state) - .then(function () { - var depPromises; - for (var i = 0; i < link.dependencies.length; i++) { - var depLoad = link.dependencyInstantiations[i]; - if (!(depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module')) { - depPromises = depPromises || []; - depPromises.push(addDeps(depLoad, depLoad.linkRecord)); - } - } - if (depPromises) - return Promise.all(depPromises); - }); - } + if (loader.trace) + depsInstantiatePromise = depsInstantiatePromise.then(function () { + traceLoad(loader, load, link); + return load; + }); - return addDeps(load, link); -} + depsInstantiatePromise = depsInstantiatePromise.catch(function (err) { + // throw up the instantiateDeps stack + link.depsInstantiatePromise = undefined; + throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + load.key); + }); -/* - * System.register - */ -RegisterLoader$1.prototype.register = function (key, deps, declare) { - var state = this[REGISTER_INTERNAL]; + depsInstantiatePromise.catch(function () {}); - // anonymous modules get stored as lastAnon - if (declare === undefined) { - state.lastRegister = [key, deps, undefined]; + return link.depsInstantiatePromise = depsInstantiatePromise; } - // everything else registers into the register cache - else { - var load = state.records[key] || createLoadRecord(state, key, undefined); - load.registration = [deps, declare, undefined]; + function deepInstantiateDeps (loader, load, link, registry, state) { + var seen = []; + function addDeps (load, link) { + if (!link) + return resolvedPromise$1; + if (seen.indexOf(load) !== -1) + return resolvedPromise$1; + seen.push(load); + + return instantiateDeps(loader, load, link, registry, state) + .then(function () { + var depPromises; + for (var i = 0; i < link.dependencies.length; i++) { + var depLoad = link.dependencyInstantiations[i]; + if (!(depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module')) { + depPromises = depPromises || []; + depPromises.push(addDeps(depLoad, depLoad.linkRecord)); + } + } + if (depPromises) + return Promise.all(depPromises); + }); + } + return addDeps(load, link); } -}; -/* - * System.registerDyanmic - */ -RegisterLoader$1.prototype.registerDynamic = function (key, deps, executingRequire, execute) { - var state = this[REGISTER_INTERNAL]; + /* + * System.register + */ + RegisterLoader.prototype.register = function (key, deps, declare) { + var state = this[REGISTER_INTERNAL]; - // anonymous modules get stored as lastAnon - if (typeof key !== 'string') { - state.lastRegister = [key, deps, executingRequire]; - } + // anonymous modules get stored as lastAnon + if (declare === undefined) { + state.lastRegister = [key, deps, undefined]; + } - // everything else registers into the register cache - else { - var load = state.records[key] || createLoadRecord(state, key, undefined); - load.registration = [deps, executingRequire, execute]; + // everything else registers into the register cache + else { + var load = state.records[key] || createLoadRecord(state, key, undefined); + load.registration = [deps, declare, undefined]; + } + }; + + /* + * System.registerDyanmic + */ + RegisterLoader.prototype.registerDynamic = function (key, deps, executingRequire, execute) { + var state = this[REGISTER_INTERNAL]; + + // anonymous modules get stored as lastAnon + if (typeof key !== 'string') { + state.lastRegister = [key, deps, executingRequire]; + } + + // everything else registers into the register cache + else { + var load = state.records[key] || createLoadRecord(state, key, undefined); + load.registration = [deps, executingRequire, execute]; + } + }; + + // ContextualLoader class + // backwards-compatible with previous System.register context argument by exposing .id, .key + function ContextualLoader (loader, key) { + this.loader = loader; + this.key = this.id = key; + this.meta = { + url: key + // scriptElement: null + }; } -}; - -// ContextualLoader class -// backwards-compatible with previous System.register context argument by exposing .id, .key -function ContextualLoader (loader, key) { - this.loader = loader; - this.key = this.id = key; - this.meta = { - url: key - // scriptElement: null + /*ContextualLoader.prototype.constructor = function () { + throw new TypeError('Cannot subclass the contextual loader only Reflect.Loader.'); + };*/ + ContextualLoader.prototype.import = function (key) { + if (this.loader.trace) + this.loader.loads[this.key].dynamicDeps.push(key); + return this.loader.import(key, this.key); }; -} -/*ContextualLoader.prototype.constructor = function () { - throw new TypeError('Cannot subclass the contextual loader only Reflect.Loader.'); -};*/ -ContextualLoader.prototype.import = function (key) { - if (this.loader.trace) - this.loader.loads[this.key].dynamicDeps.push(key); - return this.loader.import(key, this.key); -}; -/*ContextualLoader.prototype.resolve = function (key) { - return this.loader.resolve(key, this.key); -};*/ - -function ensureEvaluate (loader, load, link, registry, state) { - if (load.module) + /*ContextualLoader.prototype.resolve = function (key) { + return this.loader.resolve(key, this.key); + };*/ + + function ensureEvaluate (loader, load, link, registry, state) { + if (load.module) + return load.module; + if (load.evalError) + throw load.evalError; + if (link.evaluatePromise) + return link.evaluatePromise; + + if (link.setters) { + var evaluatePromise = doEvaluateDeclarative(loader, load, link, registry, state, [load]); + if (evaluatePromise) + return evaluatePromise; + } + else { + doEvaluateDynamic(loader, load, link, registry, state, [load]); + } return load.module; - if (load.evalError) - throw load.evalError; - if (link.evaluatePromise) - return link.evaluatePromise; - - if (link.setters) { - var evaluatePromise = doEvaluateDeclarative(loader, load, link, registry, state, [load]); - if (evaluatePromise) - return evaluatePromise; } - else { - doEvaluateDynamic(loader, load, link, registry, state, [load]); + + function makeDynamicRequire (loader, key, dependencies, dependencyInstantiations, registry, state, seen) { + // we can only require from already-known dependencies + return function (name) { + for (var i = 0; i < dependencies.length; i++) { + if (dependencies[i] === name) { + var depLoad = dependencyInstantiations[i]; + var module; + + if (depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module') { + module = depLoad; + } + else { + if (depLoad.evalError) + throw depLoad.evalError; + if (depLoad.module === undefined && seen.indexOf(depLoad) === -1 && !depLoad.linkRecord.evaluatePromise) { + if (depLoad.linkRecord.setters) { + doEvaluateDeclarative(loader, depLoad, depLoad.linkRecord, registry, state, [depLoad]); + } + else { + seen.push(depLoad); + doEvaluateDynamic(loader, depLoad, depLoad.linkRecord, registry, state, seen); + } + } + module = depLoad.module || depLoad.linkRecord.moduleObj; + } + + return '__useDefault' in module ? module.__useDefault : module; + } + } + throw new Error('Module ' + name + ' not declared as a System.registerDynamic dependency of ' + key); + }; } - return load.module; -} - -function makeDynamicRequire (loader, key, dependencies, dependencyInstantiations, registry, state, seen) { - // we can only require from already-known dependencies - return function (name) { - for (var i = 0; i < dependencies.length; i++) { - if (dependencies[i] === name) { - var depLoad = dependencyInstantiations[i]; - var module; - - if (depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module') { - module = depLoad; + + function evalError (load, err) { + load.linkRecord = undefined; + var evalError = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key); + if (load.evalError === undefined) + load.evalError = evalError; + throw evalError; + } + + // es modules evaluate dependencies first + // returns the error if any + function doEvaluateDeclarative (loader, load, link, registry, state, seen) { + var depLoad, depLink; + var depLoadPromises; + for (var i = 0; i < link.dependencies.length; i++) { + var depLoad = link.dependencyInstantiations[i]; + if (depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module') + continue; + + // custom Module returned from instantiate + depLink = depLoad.linkRecord; + if (depLink) { + if (depLoad.evalError) { + evalError(load, depLoad.evalError); } - else { - if (depLoad.evalError) - throw depLoad.evalError; - if (depLoad.module === undefined && seen.indexOf(depLoad) === -1 && !depLoad.linkRecord.evaluatePromise) { - if (depLoad.linkRecord.setters) { - doEvaluateDeclarative(loader, depLoad, depLoad.linkRecord, registry, state, [depLoad]); + else if (depLink.setters) { + if (seen.indexOf(depLoad) === -1) { + seen.push(depLoad); + try { + var depLoadPromise = doEvaluateDeclarative(loader, depLoad, depLink, registry, state, seen); } - else { - seen.push(depLoad); - doEvaluateDynamic(loader, depLoad, depLoad.linkRecord, registry, state, seen); + catch (e) { + evalError(load, e); + } + if (depLoadPromise) { + depLoadPromises = depLoadPromises || []; + depLoadPromises.push(depLoadPromise.catch(function (err) { + evalError(load, err); + })); } } - module = depLoad.module || depLoad.linkRecord.moduleObj; } - - return '__useDefault' in module ? module.__useDefault : module; + else { + try { + doEvaluateDynamic(loader, depLoad, depLink, registry, state, [depLoad]); + } + catch (e) { + evalError(load, e); + } + } } } - throw new Error('Module ' + name + ' not declared as a System.registerDynamic dependency of ' + key); - }; -} - -function evalError (load, err) { - load.linkRecord = undefined; - var evalError = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key); - if (load.evalError === undefined) - load.evalError = evalError; - throw evalError; -} - -// es modules evaluate dependencies first -// returns the error if any -function doEvaluateDeclarative (loader, load, link, registry, state, seen) { - var depLoad, depLink; - var depLoadPromises; - for (var i = 0; i < link.dependencies.length; i++) { - var depLoad = link.dependencyInstantiations[i]; - if (depLoad instanceof ModuleNamespace || depLoad[toStringTag] === 'module') - continue; - - // custom Module returned from instantiate - depLink = depLoad.linkRecord; - if (depLink) { - if (depLoad.evalError) { - evalError(load, depLoad.evalError); - } - else if (depLink.setters) { - if (seen.indexOf(depLoad) === -1) { - seen.push(depLoad); + + if (depLoadPromises) + return link.evaluatePromise = Promise.all(depLoadPromises) + .then(function () { + if (link.execute) { + // ES System.register execute + // "this" is null in ES try { - var depLoadPromise = doEvaluateDeclarative(loader, depLoad, depLink, registry, state, seen); + var execPromise = link.execute.call(nullContext); } catch (e) { evalError(load, e); } - if (depLoadPromise) { - depLoadPromises = depLoadPromises || []; - depLoadPromises.push(depLoadPromise.catch(function (err) { - evalError(load, err); - })); - } + if (execPromise) + return execPromise.catch(function (e) { + evalError(load, e); + }) + .then(function () { + load.linkRecord = undefined; + return registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); + }); } + + // dispose link record + load.linkRecord = undefined; + registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); + }); + + if (link.execute) { + // ES System.register execute + // "this" is null in ES + try { + var execPromise = link.execute.call(nullContext); } - else { - try { - doEvaluateDynamic(loader, depLoad, depLink, registry, state, [depLoad]); - } - catch (e) { - evalError(load, e); - } + catch (e) { + evalError(load, e); } + if (execPromise) + return link.evaluatePromise = execPromise.catch(function (e) { + evalError(load, e); + }) + .then(function () { + load.linkRecord = undefined; + return registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); + }); } + + // dispose link record + load.linkRecord = undefined; + registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); } - if (depLoadPromises) - return link.evaluatePromise = Promise.all(depLoadPromises) - .then(function () { - if (link.execute) { - // ES System.register execute - // "this" is null in ES - try { - var execPromise = link.execute.call(nullContext); - } - catch (e) { - evalError(load, e); - } - if (execPromise) - return execPromise.catch(function (e) { - evalError(load, e); - }) - .then(function () { - load.linkRecord = undefined; - return registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - }); + // non es modules explicitly call moduleEvaluate through require + function doEvaluateDynamic (loader, load, link, registry, state, seen) { + // System.registerDynamic execute + // "this" is "exports" in CJS + var module = { id: load.key }; + var moduleObj = link.moduleObj; + Object.defineProperty(module, 'exports', { + configurable: true, + set: function (exports) { + moduleObj.default = moduleObj.__useDefault = exports; + }, + get: function () { + return moduleObj.__useDefault; } - - // dispose link record - load.linkRecord = undefined; - registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); }); - if (link.execute) { - // ES System.register execute - // "this" is null in ES + var require = makeDynamicRequire(loader, load.key, link.dependencies, link.dependencyInstantiations, registry, state, seen); + + // evaluate deps first + if (!link.executingRequire) + for (var i = 0; i < link.dependencies.length; i++) + require(link.dependencies[i]); + try { - var execPromise = link.execute.call(nullContext); + var output = link.execute.call(envGlobal, require, moduleObj.default, module); + if (output !== undefined) + module.exports = output; } catch (e) { evalError(load, e); } - if (execPromise) - return link.evaluatePromise = execPromise.catch(function (e) { - evalError(load, e); - }) - .then(function () { - load.linkRecord = undefined; - return registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - }); - } - - // dispose link record - load.linkRecord = undefined; - registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); -} - -// non es modules explicitly call moduleEvaluate through require -function doEvaluateDynamic (loader, load, link, registry, state, seen) { - // System.registerDynamic execute - // "this" is "exports" in CJS - var module = { id: load.key }; - var moduleObj = link.moduleObj; - Object.defineProperty(module, 'exports', { - configurable: true, - set: function (exports) { - moduleObj.default = moduleObj.__useDefault = exports; - }, - get: function () { - return moduleObj.__useDefault; - } - }); - var require = makeDynamicRequire(loader, load.key, link.dependencies, link.dependencyInstantiations, registry, state, seen); - - // evaluate deps first - if (!link.executingRequire) - for (var i = 0; i < link.dependencies.length; i++) - require(link.dependencies[i]); + load.linkRecord = undefined; - try { - var output = link.execute.call(envGlobal, require, moduleObj.default, module); - if (output !== undefined) - module.exports = output; - } - catch (e) { - evalError(load, e); - } + // pick up defineProperty calls to module.exports when we can + if (module.exports !== moduleObj.__useDefault) + moduleObj.default = moduleObj.__useDefault = module.exports; - load.linkRecord = undefined; + var moduleDefault = moduleObj.default; - // pick up defineProperty calls to module.exports when we can - if (module.exports !== moduleObj.__useDefault) - moduleObj.default = moduleObj.__useDefault = module.exports; + // __esModule flag extension support via lifting + if (moduleDefault && moduleDefault.__esModule) { + for (var p in moduleDefault) { + if (Object.hasOwnProperty.call(moduleDefault, p)) + moduleObj[p] = moduleDefault[p]; + } + } - var moduleDefault = moduleObj.default; + registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - // __esModule flag extension support via lifting - if (moduleDefault && moduleDefault.__esModule) { - for (var p in moduleDefault) { - if (Object.hasOwnProperty.call(moduleDefault, p)) - moduleObj[p] = moduleDefault[p]; - } + // run importer setters and clear them + // this allows dynamic modules to update themselves into es modules + // as soon as execution has completed + if (load.importerSetters) + for (var i = 0; i < load.importerSetters.length; i++) + load.importerSetters[i](load.module); + load.importerSetters = undefined; } - registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - - // run importer setters and clear them - // this allows dynamic modules to update themselves into es modules - // as soon as execution has completed - if (load.importerSetters) - for (var i = 0; i < load.importerSetters.length; i++) - load.importerSetters[i](load.module); - load.importerSetters = undefined; -} - -// the closest we can get to call(undefined) -var nullContext = Object.create(null); -if (Object.freeze) - Object.freeze(nullContext); + // the closest we can get to call(undefined) + var nullContext = Object.create(null); + if (Object.freeze) + Object.freeze(nullContext); -var loader; + var loader; -// - - + @@ -94,55 +88,41 @@

no
VNC

-
- - - -
-
- -
-
- - - - - - -
-
+ +
+
+ + + + + + +
@@ -213,6 +193,15 @@

no
VNC

  • Advanced
      +
    • + + +
    • +
    • + + +
    • +

    • @@ -259,6 +248,11 @@

      no
      VNC

  • +

  • +
  • + Version: + +
  • @@ -290,14 +284,18 @@

    no
    VNC

    -
    +
      -
    • +
    • + + +
    • +
    • - +
    diff --git a/jupyter_desktop/share/web/noVNC-1.2.0/vnc_lite.html b/jupyter_desktop/share/web/noVNC-1.2.0/vnc_lite.html index 7110b551..d17ab9ee 100644 --- a/jupyter_desktop/share/web/noVNC-1.2.0/vnc_lite.html +++ b/jupyter_desktop/share/web/noVNC-1.2.0/vnc_lite.html @@ -3,13 +3,11 @@ + +