diff options
-rw-r--r-- | .github/ISSUE_TEMPLATE.md | 13 | ||||
-rw-r--r-- | .github/config.yml | 15 | ||||
-rw-r--r-- | .github/lock.yml | 4 | ||||
-rw-r--r-- | .github/no-response.yml | 9 | ||||
-rw-r--r-- | .github/stale.yml | 17 | ||||
-rw-r--r-- | .gitignore | 1 | ||||
-rw-r--r-- | AUTHORS.md | 12 | ||||
-rw-r--r-- | CHANGELOG.md | 154 | ||||
-rw-r--r-- | CONTRIBUTING.md | 75 | ||||
-rw-r--r-- | README.md | 13 | ||||
-rw-r--r-- | SECURITY.md | 42 | ||||
-rw-r--r-- | docs/api.md | 63 | ||||
-rw-r--r-- | docs/faq.md | 48 | ||||
-rw-r--r-- | docs/get-started.md | 8 | ||||
-rw-r--r-- | lib/file-stream.js | 3 | ||||
-rw-r--r-- | lib/file.js | 25 | ||||
-rw-r--r-- | lib/server.js | 60 | ||||
-rw-r--r-- | lib/torrent.js | 54 | ||||
-rw-r--r-- | package.json | 28 | ||||
-rw-r--r-- | test/common.js | 13 | ||||
-rw-r--r-- | test/node/blocklist-dht.js | 9 | ||||
-rw-r--r-- | test/node/blocklist-tracker.js | 9 | ||||
-rw-r--r-- | test/node/download-private-dht.js | 104 | ||||
-rw-r--r-- | test/node/torrent-events.js | 83 | ||||
-rw-r--r-- | webtorrent.min.js | 7 |
25 files changed, 591 insertions, 278 deletions
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 73dd38f..0000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,13 +0,0 @@ -<!-- DO NOT POST LINKS OR REFERENCES TO COPYRIGHTED CONTENT IN YOUR ISSUE. --> - -<!-- Issue with the desktop app? Post here: https://github.com/webtorrent/webtorrent-desktop/issues --> - -**What version of WebTorrent?** - -**What operating system and Node.js version?** - -**What browser and version? (if using WebTorrent in the browser)** - -**What did you expect to happen?** - -**What actually happened?** diff --git a/.github/config.yml b/.github/config.yml deleted file mode 100644 index ea6bf58..0000000 --- a/.github/config.yml +++ /dev/null @@ -1,15 +0,0 @@ -# ProBot Request Info (https://probot.github.io/apps/request-info/) - -requestInfoReplyComment: > - 👋 We would appreciate it if you could provide us with more information about this - issue. <br><br> ![](https://feross.net/s/cats/14.gif) -requestInfoLabelToAdd: 'need more info' - -# ProBot Welcome (https://probot.github.io/apps/welcome/) - -newPRWelcomeComment: > - 🙌 Thanks for opening this pull request! You're awesome. - <br><br> ![](https://feross.net/s/cats/6.gif) -firstPRMergeComment: > - 🎉 Congrats on getting your first pull request landed! <br><br> - ![](https://feross.net/s/cats/29.gif) diff --git a/.github/lock.yml b/.github/lock.yml deleted file mode 100644 index 5df3141..0000000 --- a/.github/lock.yml +++ /dev/null @@ -1,4 +0,0 @@ -# ProBot Lock (https://probot.github.io/apps/lock/) - -daysUntilLock: 365 -lockComment: false diff --git a/.github/no-response.yml b/.github/no-response.yml deleted file mode 100644 index 7e320d2..0000000 --- a/.github/no-response.yml +++ /dev/null @@ -1,9 +0,0 @@ -# ProBot No Response (https://probot.github.io/apps/no-response/) - -daysUntilClose: 14 -responseRequiredLabel: 'need more info' -closeComment: > - This issue has been automatically closed because there was no response to a - request for more information from the issue opener. Please leave a comment or - open a new issue if you have additional information related to this issue. - <br><br> ![](https://feross.net/s/cats/7.gif) diff --git a/.github/stale.yml b/.github/stale.yml deleted file mode 100644 index 4de49ea..0000000 --- a/.github/stale.yml +++ /dev/null @@ -1,17 +0,0 @@ -# ProBot Stale (https://probot.github.io/apps/stale/) - -daysUntilStale: 90 -daysUntilClose: 14 -exemptLabels: - - accepted - - blocked - - bug - - enhancement - - greenkeeper - - 'help wanted' - - meta -staleLabel: stale -markComment: > - This issue has been automatically marked as stale because it has not had - recent activity. It will be closed if no further activity occurs. -closeComment: false @@ -1,2 +1,3 @@ node_modules/ package-lock.json +webtorrent.debug.js @@ -145,11 +145,21 @@ - Chocobozzz (me@florianbigard.com) - Gabriel (gabrieel@email.com) - Shachar Itzhaky (corwin.amber@gmail.com) +- Eric Guan (guanzo91@gmail.com) - Arnaldas Augutis (info@untitled.lt) - Diego Rodriguez (diegorbaquero@gmail.com) - Francois Carpentier (Francewhoa@users.noreply.github.com) +- Anton Harniakou (anton.harniakou@gmail.com) - greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) - Dan Dumont (ddumont@gmail.com) -- Eric Guan (guanzo91@gmail.com) +- Gabriel Juchault (gabriel.juchault@gmail.com) +- Feross (feross@feross.org) +- Chandan Chowdary Bhagam (chandandharana@gmail.com) +- Jiayin Pei (pjymymartin@gmail.com) +- Eric Berry (coderberry@gmail.com) +- DeltaF1 (DeltaF1@users.noreply.github.com) +- jsdt (jeffreydallatezza@gmail.com) +- Luc (luc.cadoret@gmail.com) +- Diego Rodriguez Baquero (diego.baquero@pager.com) #### Generated by scripts/update-authors.sh. diff --git a/CHANGELOG.md b/CHANGELOG.md index 27d077c..edf63b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,159 @@ # WebTorrent Version History +## v0.107.13 - 2019-09-10 + +- Added tests to check the order of torrent events + +## v0.107.12 - 2019-09-08 + +- Fixed how first piece's irrelevant bytes are calculated + +## v0.107.11 - 2019-09-07 + +- Added timeout option for `requestIdlecallback` to prevent longer delays in download + +## v0.107.10 - 2019-09-07 + +- Server now uses relative urls + +## v0.107.9 - 2019-09-07 + +- Added a check in case user destroys torrent in response to `metadata` event + +## v0.107.8 - 2019-09-07 + +- Fixed the torrent event emission order; now `metadata` is emitted before `ready` and `done` + +## v0.107.7 - 2019-09-06 + +- Updated to simple-sha1@3 +- Updated jsdelivr urls to use latest Webtorrent + +## v0.107.6 - 2019-08-28 + +- Fixed XSS vulnerability in the http Server ([issue](https://github.com/brave/brave-browser/issues/5821)) + +## v0.107.5 - 2019-08-22 + +- No meaningful changes + +## v0.107.4 - 2019-08-19 + +- Added api documentation for some torrent properties +- Bug fix: trackers now recieve 0 while seeding file instead of the file size +- Updated org-wide security policies and contributing guidelines + +## v0.107.3 - 2019-08-10 + +- No meaningful changes + +## v0.107.2 - 2019-08-09 + +- Scripts are now more verbose + +## v0.107.1 - 2019-08-09 + +- Updated to stream-to-bolob-url@3 +- Added `chromeapp` field to package.json for specifying Chrome App dependency substitutions + +## v0.107.0 - 2019-08-07 + +- Smaller build with tinify +- Added size-disc script to visualize bundle + +## v0.106.0 - 2019-08-05 + +- Updated to electron@6 +- Dropped support for node versions < 10 + +## v0.105.3 - 2019-08-02 + +- Now uses 'application/octet-stream' mimetype as fallback instead of null + +## v0.105.2 - 2019-07-31 + +- Fixed server `hostname` option to mitigate DNS rebinding attack ([issue](https://github.com/webtorrent/webtorrent/pull/1678)) + +## v0.105.1 - 2019-07-24 + +- Bug fixed: Video streaming is now fixed in Brave nightly and chromium nightly ([issue](https://github.com/brave/brave-browser/issues/5358)) + +## v0.105.0 - 2019-07-06 + +- Updated to parse-torrent@7 +- Added manual verification for torrent files + +## v0.104.0 - 2019-06-29 + +- Updated to chunk-store-stream@4 +- Updated to multistream@3 +- Updated to create-torrent@4 +- Dropped support for node versions < 8 + +## v0.103.4 - 2019-06-19 + +- No meaningful changes + +## v0.103.3 - 2019-06-19 + +- Updated to electron@5 + +## v0.103.2 - 2019-06-12 + +- Added the ability to close and restore streaming server + +## v0.103.1 - 2019-03-11 + +- Updated to electron@4 +- Bug fixed: File progress is no longer shown in negative + +## v0.103.0 - 2018-12-11 + +- No longer verifies file hashes passed to seed +- No longer calls torrent.load() when seeding FS filepath +- Reduced download impact on slower computers: now download chunks at a lower priority ([rationale](https://github.com/webtorrent/webtorrent/pull/1513)) + +## v0.102.4 - 2018-08-31 + +- No meaningful changes + +## v0.102.3 - 2018-08-31 + +- Removed xtend +- Removed the concurrency limit in browser +- Reduced installtion size by removing zero-fill +- Updated to bittorrent-dht@9 + +## v0.102.2 - 2018-08-28 + +- Update some webtorrent packages to ES6 ([webtorrent/#1443](https://github.com/webtorrent/webtorrent/issues/1443)) + +## v0.102.1 - 2018-08-10 + +- No meaningful changes + +## v0.102.0 - 2018-08-04 + +- Updated to chunk-store-stream@3 +- Updated to immediate-chunk-store@2 + +## v0.101.2 - 2018-07-27 + +- Updated to torrent-discovery@9.0.2 + +## v0.101.1 - 2018-07-27 + +- Updated to bittorrent-protocol@3 +- Optimized peers: peers now start as uninterested and only move to interested if/once they have a piece that we need ([webtorrent/#1059](https://github.com/webtorrent/webtorrent/issues/1059)) + +## v0.101.0 - 2018-07-19 + +- No meaningful changes + +## v0.100.0 - 2018-05-23 + +- Implemented BEP53 to alow file selection using `select only` parameter in MagnetURIs ([webtorrent/#1395](https://github.com/webtorrent/webtorrent-hybrid/issues/1395)) + ## v0.99.4 - 2018-05-03 - Use updated `babel-minify` minifier instead of deprecated `babili` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 7957636..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,75 +0,0 @@ -# Contributing Guidelines - -Contributions welcome! - -**Before spending lots of time on something, ask for feedback on your idea first!** - -Please search issues and pull requests before adding something new to avoid duplicating -efforts and conversations. - -This project welcomes non-code contributions, too! The following types of contributions -are welcome: - -- **Ideas**: participate in an issue thread or start your own to have your voice heard. -- **Writing**: contribute your expertise in an area by helping expand the included docs. -- **Copy editing**: fix typos, clarify language, and improve the quality of the docs. -- **Formatting**: help keep docs easy to read with consistent formatting. - -## Code Style - -[![standard][standard-image]][standard-url] - -This repository uses [`standard`][standard-url] to maintain code style and consistency, -and to avoid style arguments. `npm test` runs `standard` automatically, so you don't have -to! - -[standard-image]: https://cdn.rawgit.com/feross/standard/master/badge.svg -[standard-url]: https://standardjs.com - -## Project Governance - -Individuals making significant and valuable contributions are given commit-access to the -project to contribute as they see fit. This project is more like an open wiki than a -standard guarded open source project. - -### Rules - -There are a few basic ground-rules for contributors: - -1. **No `--force` pushes** or modifying the Git history in any way. -2. **Non-master branches** should be used for ongoing work. -3. **Significant modifications** like API changes should be subject to a **pull request** - to solicit feedback from other contributors. -4. **Pull requests** are *encouraged* for all contributions to solicit feedback, but left to - the discretion of the contributor. - -### Releases - -Declaring formal releases remains the prerogative of the project maintainer. - -### Changes to this arrangement - -This is an experiment and feedback is welcome! This document may also be subject to pull- -requests or changes by contributors where you believe you have something valuable to add -or change. - -## Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -- (a) The contribution was created in whole or in part by me and I have the right to - submit it under the open source license indicated in the file; or - -- (b) The contribution is based upon previous work that, to the best of my knowledge, is - covered under an appropriate open source license and I have the right under that license - to submit that work with modifications, whether created in whole or in part by me, under - the same open source license (unless I am permitted to submit under a different - license), as indicated in the file; or - -- (c) The contribution was provided directly to me by some other person who certified - (a), (b) or (c) and I have not modified it. - -- (d) I understand and agree that this project and the contribution are public and that a - record of the contribution (including all personal information I submit with it, - including my sign-off) is maintained indefinitely and may be redistributed consistent - with this project or the open source license(s) involved. @@ -10,13 +10,17 @@ <h4 align="center">The streaming torrent client. For node.js and the web.</h4> <p align="center"> - <a href="https://gitter.im/webtorrent/webtorrent"><img src="https://img.shields.io/badge/gitter-join%20chat%20%E2%86%92-brightgreen.svg" alt="gitter"></a> + <a href="https://discord.gg/cnXkm4Z"><img src="https://img.shields.io/discord/612575111718895616" alt="discord"></a> <a href="https://travis-ci.org/webtorrent/webtorrent"><img src="https://img.shields.io/travis/webtorrent/webtorrent/master.svg" alt="travis"></a> <a href="https://ci.appveyor.com/project/webtorrent/webtorrent"><img src="https://ci.appveyor.com/api/projects/status/cgu85xlgl72uoswq/branch/master?svg=true" alt="appveyor"></a> <a href="https://www.npmjs.com/package/webtorrent"><img src="https://img.shields.io/npm/v/webtorrent.svg" alt="npm version"></a> <a href="https://www.npmjs.com/package/webtorrent"><img src="https://img.shields.io/npm/dm/webtorrent.svg" alt="npm downloads"></a> <a href="https://standardjs.com"><img src="https://img.shields.io/badge/code_style-standard-brightgreen.svg" alt="Standard - JavaScript Style Guide"></a> </p> + +<h5 align="center"> + Sponsored by <a href="https://brave.com" rel="nofollow"><img src="https://webtorrent.io/img/supporters/brave.png" alt="Brave" height=35 valign="middle"></a> <a href="https://www.enya.ai/?utm_source=github_webtorrent&utm_medium=web" rel="nofollow"><img src="https://webtorrent.io/img/supporters/enya.png" alt="Enya" height=30 valign="middle"></a> +</h5> <br> **WebTorrent** is a streaming torrent client for **node.js** and the **browser**. YEP, @@ -52,11 +56,6 @@ they can connect to both normal *and* web peers. We hope other clients will foll ![Network](https://webtorrent.io/img/network.png) -### Open Source Sponsors - -[<img src='https://webtorrent.io/img/supporters/brave.png' width=300>](https://brave.com) -|---| - ### Features - **Torrent client for node.js & the browser** (same npm package!) @@ -113,7 +112,7 @@ To install a WebTorrent desktop application for Mac, Windows, or Linux, see with development or to hang out with some mad science hackers :) - **[Create a new issue](https://github.com/webtorrent/webtorrent/issues/new)** to report bugs - **[Fix an issue](https://github.com/webtorrent/webtorrent/issues?state=open)**. WebTorrent - is an [OPEN Open Source Project](CONTRIBUTING.md)! + is an [OPEN Open Source Project](https://github.com/webtorrent/.github/blob/master/CONTRIBUTING.md)! ### Who is using WebTorrent today? diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index fd097c3..0000000 --- a/SECURITY.md +++ /dev/null @@ -1,42 +0,0 @@ -# Security Policies and Procedures - -This document outlines security procedures and general policies for the WebTorrent -project. - - * [Reporting a Bug](#reporting-a-bug) - * [Disclosure Policy](#disclosure-policy) - * [Comments on this Policy](#comments-on-this-policy) - -## Reporting a Bug - -The WebTorrent team and community take all security bugs in WebTorrent seriously. -Thank you for improving the security of WebTorrent. We appreciate your efforts and -responsible disclosure and will make every effort to acknowledge your -contributions. - -Report security bugs by emailing the lead maintainer at feross@feross.org. - -The lead maintainer will acknowledge your email within 48 hours, and will send a -more detailed response within 48 hours indicating the next steps in handling -your report. After the initial reply to your report, the security team will -endeavor to keep you informed of the progress towards a fix and full -announcement, and may ask for additional information or guidance. - -Report security bugs in third-party modules to the person or team maintaining -the module. - -## Disclosure Policy - -When the security team receives a security bug report, they will assign it to a -primary handler. This person will coordinate the fix and release process, -involving the following steps: - - * Confirm the problem and determine the affected versions. - * Audit code to find any potential similar problems. - * Prepare fixes for all releases still under maintenance. These fixes will be - released as fast as possible to npm. - -## Comments on this Policy - -If you have suggestions on how this process could be improved please submit a -pull request. diff --git a/docs/api.md b/docs/api.md index ca3a4f1..062343b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -89,6 +89,7 @@ If `opts` is specified, then the default options (shown below) will be overridde getAnnounceOpts: Function, // Custom callback to allow sending extra parameters to the tracker maxWebConns: Number, // Max number of simultaneous connections per web seed [default=4] path: String, // Folder to download files to (default=`/tmp/webtorrent/`) + private: Boolean, // If true, client will not share the hash with the DHT nor with PEX (default is the privacy of the parsed torrent) store: Function // Custom chunk store (must follow [abstract-chunk-store](https://www.npmjs.com/package/abstract-chunk-store) API) } ``` @@ -221,11 +222,28 @@ Magnet URI of the torrent (string). `.torrent` file of the torrent (Blob URL). +## `torrent.announce[...]` + +Array of all tracker servers. Each announce is an URL (string). + ## `torrent.files[...]` Array of all files in the torrent. See documentation for `File` below to learn what methods/properties files have. +## `torrent.pieces[...]` + +Array of all pieces in the torrent. See documentation for `Piece` below to learn what +properties pieces have. Some pieces can be null. + +## `torrent.pieceLength` + +Length in bytes of every piece but the last one. + +## `torrent.lastPieceLength` + +Length in bytes of the last piece (<= of `torrent.pieceLength`). + ## `torrent.timeRemaining` Time remaining for download to complete (in milliseconds). @@ -262,10 +280,45 @@ Torrent "seed ratio" (uploaded / downloaded). Number of peers in the torrent swarm. +## `torrent.maxWebConns` + +Max number of simultaneous connections per web seed, as passed in the options. + ## `torrent.path` Torrent download location. +## `torrent.ready` + +True when the torrent is ready to be used (i.e. metadata is available and store is +ready). + +## `torrent.paused` + +True when the torrent has stopped connecting to new peers. Note that this does +not pause new incoming connections, nor does it pause the streams of existing +connections or their wires. + +## `torrent.done` + +True when all the torrent files have been downloaded. + +## `torrent.length` + +Sum of the files length (in bytes). + +## `torrent.created` + +Date of creation of the torrent (as a [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object). + +## `torrent.createdBy` + +Author of the torrent (string). + +## `torrent.comment` + +A comment optionnaly set by the author (string). + ## `torrent.destroy([callback])` Alias for `client.remove(torrent)`. If `callback` is provided, it will be called when @@ -637,3 +690,13 @@ file.getBlobURL(function (err, url) { document.body.appendChild(a) }) ``` + +# Piece API + +## `piece.length` + +Piece length (in bytes). *Example: 12345* + +## `piece.missing` + +Piece missing length (in bytes). *Example: 100* diff --git a/docs/faq.md b/docs/faq.md index c04e2f1..334fda5 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -61,21 +61,13 @@ WebTorrent is still pretty new, but it's already being used in cool ways: - **[WebTorrent Desktop][webtorrent-desktop]** - Streaming torrent app. For Mac, Windows, and Linux. ([source code][webtorrent-desktop-source]) - **[Instant.io][instant.io]** – Streaming file transfer over WebTorrent ([source code][instant.io-source]) - **[GitTorrent][gittorrent]** - Decentralized GitHub using BitTorrent and Bitcoin ([source code][gittorrent-source]) -- **[PeerCloud][peercloud]** - Serverless websites via WebTorrent ([source code][peercloud-source]) - **[File.pizza][filepizza]** - Free peer-to-peer file transfers in your browser ([source code][filepizza-source]) - **[Webtorrentapp][webtorrentapp]** – Platform for launching web apps from torrents - **[Fastcast][fastcast]** – Gallery site with some videos ([source code][fastcast-source]) -- **[Colored Coins][coloredcoins]** - Open protocol for creating digital assets on the Blockchain ([source code][coloredcoins-source]) - **[Tokenly Pockets][pockets]** - Digital token issuance with WebTorrent-based metadata ([source code][pockets-source]) - **[βTorrent][btorrent]** - Fully-featured browser WebTorrent client ([source code][btorrent-source]) -- **[Zapsnap][zapsnap]** - Temporary peer to peer screenshot sharing from your browser ([source code][zapsnap-source]) - **[PeerWeb][peerweb]** - Fetch and render a static website from a torrent -- **[Niagara][niagara]** - Video player webtorrent with subtitles (zipped .srt(s)) -- **[Vique][vique]** - Video player queue to share videos - **[YouShark][youshark]** - Web music player for WebTorrent ([source code][youshark-source]) -- **[Peerify][peerify]** - Instant Web-seeded torrents for your files -- **[Instant-Share][instant-share]** - File sharing over WebTorrent -- **[P2PDrop][p2pdrop]** - Securely share files between peers ([source code][p2pdrop-source]) - **[Twister][twister]** - Decentralized microblogging service, using WebTorrent for media attachments ([source code][twister-source]) - **[PeerTube][peertube]** - Prototype of a decentralized video streaming platform in the web browser ([source code][peertube-source]) - **[Cinematrix][cinematrix]** - Stream your favorite free content @@ -87,32 +79,32 @@ WebTorrent is still pretty new, but it's already being used in cool ways: - **[TorrentMedia][torrentmedia]** - Fully-featured desktop WebTorrent client - **[Gaia 3D Star Map][gaia]** - 2 million stars, rendered in 3D with WebGL, WebVR, and WebTorrent - **[Watchtor][watchtor]** - A minimalistic approach for online torrent watching ([source code][watchtor-source]) -- **[CacheP2P][cachep2p]** - Highly distributed cache platform ([source code][cachep2p-source]) - **[DropClickPaste][dropclickpaste]** - Drop Dead Simple Content Sharing -- **[LocalFiles][localfiles]** - Share files by pinning them to geographic locations +- **[FileMap][filemap]** - Share files by pinning them to geographic locations - **[WebTorrent Google Cast (WTGC)][wtgc]** - Play WebTorrent media on Google Cast devices ([source code][wtgc-source]) -- **[WebTorrent Player][webtorrent-player]** - A WebTorrent player built by Angular 2 and ngrx ([source code][webtorrent-player-source]) - **[CodeDump][codedump]** - A WebTorrent based code pastebin ([source code][codedump-source]) - **[Lunik-Torrent][lunik-torrent]** - WebTorrent downloader and file manager. ([source code][lunik-torrent-source]) - **[BitChute][bitchute]** - A decentralized video streaming social network - **[Planktos][planktos]** - Enables websites to serve their static content over BitTorrent ([source code][planktos-source]) -- **[SuperQuickShare][superquickshare]** - Quickly share files between devices using webtorrent and qrcodes ([source code][superquickshare-source]) - **[P2P-CDN][p2pcdn]** - WebTorrent CDN with graceful degradation - **[PearPlayer][PearPlayer]** - A WebTorrent based multi-source and multi-protocol P2P streaming media player - **[Tcloud][tcloud]** - File sharing and torrent downloading - **[Webtorrent-webui][webtorrent-webui]** - A WebTorrent client with a simple web interface for easy remote usage - **[CineTimes][cinetimes]** - A streaming website of public domain movies - **[Bitlove.org][bitlove]** - Your favorite podcasts via BitTorrent -- **[lofiTorrent][lofitorrent]** - Online and offline browser torrent client - **[Live-torrent][live-torrent]** - Simple implementation of a webtorrent powered live streaming solution ([source code][live-torrent-source]) - **[CDNBye][CDNBye]** - CDNBye implements WebRTC datachannel to scale live/vod video streaming by peer-to-peer network using bittorrent-like protocol. - **[Files.fm][Files.fm]** - a fast file sharing and freemium cloud storage service that uses P2P technology to accelerate unlimited downloads and file distribution. - **[imgest][imgest]** - Serverless shareable image gallery built with JavaScript and WebTorrent. - **[Bugout][Bugout]** - build and run back-end web services in a browser tab. - **[P2P Media Loader][p2p-media-loader]** - engine for Hls.js and Shaka Player that enables P2P sharing of live and VOD streams over HLS or DASH protocols. -- **[Cheff][Cheff]** - Share food recipes between your devices. [source code](https://github.com/vasco3/cheff) -- **[Hubzilla](https://hubzilla.org)** - WebTorrent player integration into posts ([source code](https://github.com/demitas-ace/wtplayer/tree/master/wtplayer)) +- **[Hubzilla][hubzilla]** - WebTorrent player integration into posts ([source code][hubzilla-source]) +- **[Come Over][comeover]** - Video stream sharing to watch movies together. +- **[Peer Web Site][peerwebsite]** - Realtime P2P Web Site using WebTorrent for files and WebRTC for text. - ***Your app here – [Send a pull request][pr] with your URL!*** +<!-- - **[PeerCloud][peercloud]** - Serverless websites via WebTorrent ([source code][peercloud-source]) --> +<!-- - **[Niagara][niagara]** - Video player webtorrent with subtitles (zipped .srt(s)) --> +<!-- - **[Vique][vique]** - Video player queue to share videos --> #### WebTorrent Product Alternatives @@ -131,23 +123,15 @@ There's also a list of WebTorrent-powered alternatives to centralized services h [webtorrentapp]: https://github.com/alexeisavca/webtorrentapp [fastcast]: http://fastcast.nz [fastcast-source]: https://github.com/fastcast/fastcast -[coloredcoins]: http://coloredcoins.org -[coloredcoins-source]: https://github.com/Colored-Coins/Metadata-Handler [pockets]: https://tokenly.com/ [pockets-source]: https://github.com/loon3/Tokenly-Pockets [btorrent]: https://btorrent.xyz [btorrent-source]: https://github.com/DiegoRBaquero/bTorrent -[zapsnap]: http://zapsnap.io/ -[zapsnap-source]: https://github.com/twobucks/zapsnap [peerweb]: https://github.com/retrohacker/peerweb.js [niagara]: https://andreapaiola.name/niagara/ [vique]: https://andreapaiola.name/vique/ [youshark]: http://youshark.neocities.org/ [youshark-source]: https://github.com/enorrmann/youshark -[peerify]: https://peerify.btorrent.xyz -[instant-share]: http://fs.lunik.xyz/ -[p2pdrop]: http://p2pdrop.com -[p2pdrop-source]: https://github.com/ajainvivek/P2PDrop [twister]: http://twister.net.co/?p=589 [twister-source]: https://github.com/miguelfreitas/twister-html [peertube]: http://peertube.cpy.re @@ -166,14 +150,10 @@ There's also a list of WebTorrent-powered alternatives to centralized services h [gaia]: http://charliehoey.com/threejs-demos/gaia_dr1.html [watchtor]: https://open-watchtor.hashbase.io [watchtor-source]: https://github.com/codealchemist/watchtor -[cachep2p]: http://www.cachep2p.com/ -[cachep2p-source]: https://github.com/guerrerocarlos/CacheP2P [dropclickpaste]: http://dropclickpaste.com/ -[localfiles]: https://localfiles.alhur.es/ +[filemap]: https://filemap.xyz [wtgc]: https://wtgc.firebaseapp.com [wtgc-source]: https://git.io/wtgc -[webtorrent-player]: http://webtorrent-player.s3-website-us-east-1.amazonaws.com/ -[webtorrent-player-source]: https://github.com/Hongbo-Miao/webtorrent-player [codedump]: http://ronsoros.github.io [codedump-source]: https://github.com/ronsoros/ronsoros.github.io/blob/master/index.html [lunik-torrent]: https://tcloud-lunik.herokuapp.com @@ -181,15 +161,12 @@ There's also a list of WebTorrent-powered alternatives to centralized services h [bitchute]: https://www.bitchute.com [planktos]: https://xuset.github.io/planktos/ [planktos-source]: https://github.com/xuset/planktos -[superquickshare]: https://sqs.fun -[superquickshare-source]: https://github.com/manicphase/super-quick-share [p2pcdn]: https://github.com/andreapaiola/P2P-CDN [PearPlayer]: https://github.com/PearInc/PearPlayer.js [tcloud]: https://github.com/Lunik/tcloud [webtorrent-webui]: https://github.com/pldubouilh/webtorrent-webui [cinetimes]: http://cinetimes.org/ [bitlove]: https://bitlove.org/ -[lofitorrent]: https://lofitorrent.js.org/ [live-torrent]: https://live.computer [live-torrent-source]: https://github.com/pldubouilh/live-torrent [CDNBye]: https://github.com/cdnbye/hlsjs-p2p-engine @@ -197,7 +174,10 @@ There's also a list of WebTorrent-powered alternatives to centralized services h [imgest]: https://imgest.hashbase.io [Bugout]: https://github.com/chr15m/bugout [p2p-media-loader]: https://github.com/novage/p2p-media-loader -[Cheff]: https://cheff.cuadranteweb.com +[hubzilla]: https://hubzilla.org +[hubzilla-source]: https://github.com/demitas-ace/wtplayer/tree/master/wtplayer +[comeover]: https://comeover.io +[peerwebsite]: https://peerweb.site ## How does WebTorrent work? @@ -231,7 +211,7 @@ clients like Transmission, and uTorrent to add support for WebTorrent. **Vuze** ## How do I get started? To start using WebTorrent, simply include the -[`webtorrent.min.js`](https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js) +[`webtorrent.min.js`](https://cdn.jsdelivr.net/npm/webtorrent@latest/webtorrent.min.js) script on your page. If you use [browserify](http://browserify.org/), you can `npm install webtorrent` and `require('webtorrent')`. @@ -403,7 +383,7 @@ IRC at `#webtorrent` (freenode) and how you can get started. [open-issues]: https://github.com/webtorrent/webtorrent/issues?state=open -[contributing]: https://github.com/webtorrent/webtorrent/blob/master/CONTRIBUTING.md +[contributing]: https://github.com/webtorrent/.github/blob/master/CONTRIBUTING.md ## Where can I learn more? diff --git a/docs/get-started.md b/docs/get-started.md index 58529d6..bee3b9d 100644 --- a/docs/get-started.md +++ b/docs/get-started.md @@ -6,7 +6,7 @@ to get started! ## Install To start using WebTorrent, simply include the -[`webtorrent.min.js`](https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js) +[`webtorrent.min.js`](https://cdn.jsdelivr.net/npm/webtorrent@latest/webtorrent.min.js) script on your page. ```html @@ -83,7 +83,7 @@ This example uses the [`drag-drop`][drag-drop] package, to make the HTML5 Drag a Drop API easier to work with. **Note:** If you do not use browserify, use the standalone file -[`dragdrop.min.js`](https://raw.githubusercontent.com/feross/drag-drop/master/dragdrop.min.js). +[`dragdrop.min.js`](https://bundle.run/drag-drop). This exports a `DragDrop` function on `window`. ### Download and save a torrent (in Node.js) @@ -129,7 +129,7 @@ downloaded. <div class="log"></div> <!-- Include the latest version of WebTorrent --> - <script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script> + <script src="https://cdn.jsdelivr.net/npm/webtorrent@latest/webtorrent.min.js"></script> <script> var client = new WebTorrent() @@ -282,7 +282,7 @@ or [Instant.io](https://instant.io) to seed torrents to the WebTorrent network. </div> </div> <!-- Include the latest version of WebTorrent --> - <script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script> + <script src="https://cdn.jsdelivr.net/npm/webtorrent@latest/webtorrent.min.js"></script> <!-- Moment is used to show a human-readable remaining time --> <script src="http://momentjs.com/downloads/moment.min.js"></script> diff --git a/lib/file-stream.js b/lib/file-stream.js index 72622b2..f6a8402 100644 --- a/lib/file-stream.js +++ b/lib/file-stream.js @@ -56,9 +56,10 @@ class FileStream extends stream.Readable { this._torrent.store.get(p, (err, buffer) => { this._notifying = false if (this.destroyed) return - if (err) return this._destroy(err) debug('read %s (length %s) (err %s)', p, buffer.length, err && err.message) + if (err) return this._destroy(err) + if (this._offset) { buffer = buffer.slice(this._offset) this._offset = 0 diff --git a/lib/file.js b/lib/file.js index 993e06a..3e75091 100644 --- a/lib/file.js +++ b/lib/file.js @@ -41,10 +41,12 @@ class File extends EventEmitter { const { _startPiece: start, _endPiece: end } = this const piece = pieces[start] - // Calculate first piece diffrently, it sometimes have a offset + // First piece may have an offset, e.g. irrelevant bytes from the end of + // the previous file + const irrelevantFirstPieceBytes = this.offset % pieceLength let downloaded = bitfield.get(start) - ? pieceLength - (this.offset % pieceLength) - : Math.max(piece.length - piece.missing - this.offset, 0) + ? pieceLength - irrelevantFirstPieceBytes + : Math.max(pieceLength - irrelevantFirstPieceBytes - piece.missing, 0) for (let index = start + 1; index <= end; ++index) { if (bitfield.get(index)) { @@ -53,12 +55,12 @@ class File extends EventEmitter { } else { // "in progress" data const piece = pieces[index] - downloaded += piece.length - piece.missing + downloaded += pieceLength - piece.missing } } - // We don't have a end-offset and one small file can fith in the middle - // of one chunk, so return this.length if it's oversized + // We don't know the end offset, so return this.length if it's oversized. + // e.g. One small file can fit in the middle of a piece. return Math.min(downloaded, this.length) } @@ -105,12 +107,19 @@ class File extends EventEmitter { getBlob (cb) { if (typeof window === 'undefined') throw new Error('browser-only method') streamToBlob(this.createReadStream(), this._getMimeType()) - .then(blob => cb(null, blob), cb) + .then( + blob => cb(null, blob), + err => cb(err) + ) } getBlobURL (cb) { if (typeof window === 'undefined') throw new Error('browser-only method') - streamToBlobURL(this.createReadStream(), this._getMimeType(), cb) + streamToBlobURL(this.createReadStream(), this._getMimeType()) + .then( + blobUrl => cb(null, blobUrl), + err => cb(err) + ) } appendTo (elem, opts, cb) { diff --git a/lib/server.js b/lib/server.js index 0dcce21..b2e307d 100644 --- a/lib/server.js +++ b/lib/server.js @@ -1,4 +1,5 @@ const arrayRemove = require('unordered-array-remove') +const escapeHtml = require('escape-html') const http = require('http') const mime = require('mime') const pump = require('pump') @@ -18,8 +19,7 @@ function Server (torrent, opts = {}) { closed = false server.on('connection', onConnection) server.on('request', onRequest) - _listen.apply(server, args) - return server + return _listen.apply(server, args) } server.close = cb => { @@ -78,10 +78,6 @@ function Server (torrent, opts = {}) { const pathname = new URL(req.url, 'http://example.com').pathname - if (pathname === '/favicon.ico') { - return serve404Page() - } - // Allow cross-origin requests (CORS) if (isOriginAllowed(req)) { res.setHeader('Access-Control-Allow-Origin', req.headers.origin) @@ -90,6 +86,13 @@ function Server (torrent, opts = {}) { // Prevent browser mime-type sniffing res.setHeader('X-Content-Type-Options', 'nosniff') + // Defense-in-depth: Set a strict Content Security Policy to mitigate XSS + res.setHeader('Content-Security-Policy', "base-uri 'none'; default-src 'none'; frame-ancestors 'none'; form-action 'none';") + + if (pathname === '/favicon.ico') { + return serve404Page() + } + // Allow CORS requests to specify arbitrary headers, e.g. 'Range', // by responding to the OPTIONS preflight request with the specified // origin and requested headers. @@ -147,11 +150,26 @@ function Server (torrent, opts = {}) { res.statusCode = 200 res.setHeader('Content-Type', 'text/html') - const listHtml = torrent.files.map((file, i) => `<li><a download="${file.name}" href="/${i}/${file.name}">${file.path}</a> (${file.length} bytes)</li>`).join('<br>') + const listHtml = torrent.files + .map((file, i) => ( + `<li> + <a + download="${escapeHtml(file.name)}" + href="${escapeHtml(i)}/${escapeHtml(file.name)}" + > + ${escapeHtml(file.path)} + </a> + (${escapeHtml(file.length)} bytes) + </li>` + )) + .join('<br>') const html = getPageHTML( - `${torrent.name} - WebTorrent`, - `<h1>${torrent.name}</h1><ol>${listHtml}</ol>` + `${escapeHtml(torrent.name)} - WebTorrent`, + ` + <h1>${escapeHtml(torrent.name)}</h1> + <ol>${listHtml}</ol> + ` ) res.end(html) } @@ -160,7 +178,10 @@ function Server (torrent, opts = {}) { res.statusCode = 404 res.setHeader('Content-Type', 'text/html') - const html = getPageHTML('404 - Not Found', '<h1>404 - Not Found</h1>') + const html = getPageHTML( + '404 - Not Found', + '<h1>404 - Not Found</h1>' + ) res.end(html) } @@ -214,7 +235,10 @@ function Server (torrent, opts = {}) { function serveMethodNotAllowed () { res.statusCode = 405 res.setHeader('Content-Type', 'text/html') - const html = getPageHTML('405 - Method Not Allowed', '<h1>405 - Method Not Allowed</h1>') + const html = getPageHTML( + '405 - Method Not Allowed', + '<h1>405 - Method Not Allowed</h1>' + ) res.end(html) } } @@ -222,8 +246,20 @@ function Server (torrent, opts = {}) { return server } +// NOTE: Arguments must already be HTML-escaped function getPageHTML (title, pageHtml) { - return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>${title}</title></head><body>${pageHtml}</body></html>` + return ` + <!DOCTYPE html> + <html lang="en"> + <head> + <meta charset="utf-8"> + <title>${title}</title> + </head> + <body> + ${pageHtml} + </body> + </html> + ` } // From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent diff --git a/lib/torrent.js b/lib/torrent.js index ef541ea..4ee7a80 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -22,7 +22,6 @@ const pump = require('pump') const randomIterate = require('random-iterate') const sha1 = require('simple-sha1') const speedometer = require('speedometer') -const uniq = require('uniq') const utMetadata = require('ut_metadata') const utPex = require('ut_pex') // browser exclude const parseRange = require('parse-numeric-range') @@ -73,6 +72,9 @@ class Torrent extends EventEmitter { this._store = opts.store || FSChunkStore this._getAnnounceOpts = opts.getAnnounceOpts + // if defined, `opts.private` overrides default privacy of torrent + if (typeof opts.private === 'boolean') this.private = opts.private + this.strategy = opts.strategy || 'sequential' this.maxWebConns = opts.maxWebConns || 4 @@ -161,7 +163,7 @@ class Torrent extends EventEmitter { get progress () { return this.length ? this.downloaded / this.length : 0 } - get ratio () { return this.uploaded / (this.received || 1) } + get ratio () { return this.uploaded / (this.received || this.length) } get numPeers () { return this.wires.length } @@ -252,12 +254,17 @@ class Torrent extends EventEmitter { _processParsedTorrent (parsedTorrent) { this._debugId = parsedTorrent.infoHash.toString('hex').substring(0, 7) + if (typeof this.private !== 'undefined') { + // `private` option overrides default, only if it's defined + parsedTorrent.private = this.private + } + if (this.announce) { // Allow specifying trackers via `opts` parameter parsedTorrent.announce = parsedTorrent.announce.concat(this.announce) } - if (this.client.tracker && global.WEBTORRENT_ANNOUNCE && !this.private) { + if (this.client.tracker && global.WEBTORRENT_ANNOUNCE && !parsedTorrent.private) { // So `webtorrent-hybrid` can force specific trackers to be used parsedTorrent.announce = parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE) } @@ -267,8 +274,9 @@ class Torrent extends EventEmitter { parsedTorrent.urlList = parsedTorrent.urlList.concat(this.urlList) } - uniq(parsedTorrent.announce) - uniq(parsedTorrent.urlList) + // remove duplicates by converting to Set and back + parsedTorrent.announce = Array.from(new Set(parsedTorrent.announce)) + parsedTorrent.urlList = Array.from(new Set(parsedTorrent.urlList)) Object.assign(this, parsedTorrent) @@ -277,6 +285,19 @@ class Torrent extends EventEmitter { } _onListening () { + if (this.destroyed) return + + if (this.info) { + // if full metadata was included in initial torrent id, use it immediately. Otherwise, + // wait for torrent-discovery to find peers and ut_metadata to get the metadata. + this._onMetadata(this) + } else { + if (this.xs) this._getMetadataFromServer() + this._startDiscovery() + } + } + + _startDiscovery () { if (this.discovery || this.destroyed) return let trackerOpts = this.client.tracker @@ -334,14 +355,6 @@ class Torrent extends EventEmitter { this.discovery.on('warning', (err) => { this.emit('warning', err) }) - - if (this.info) { - // if full metadata was included in initial torrent id, use it immediately. Otherwise, - // wait for torrent-discovery to find peers and ut_metadata to get the metadata. - this._onMetadata(this) - } else if (this.xs) { - this._getMetadataFromServer() - } } _getMetadataFromServer () { @@ -500,6 +513,12 @@ class Torrent extends EventEmitter { this._onWireWithMetadata(wire) }) + // Emit 'metadata' before 'ready' and 'done' + this.emit('metadata') + + // User might destroy torrent in response to 'metadata' event + if (this.destroyed) return + if (this.skipVerify) { // Skip verifying exisitng data and just assume it's correct this._markAllVerified() @@ -530,8 +549,6 @@ class Torrent extends EventEmitter { this._verifyPieces(onPiecesVerified) } } - - this.emit('metadata') } /* @@ -611,6 +628,9 @@ class Torrent extends EventEmitter { if (this.destroyed) return this._debug('on store') + // Start discovery before emitting 'ready' + this._startDiscovery() + this.ready = true this.emit('ready') @@ -1163,7 +1183,7 @@ class Torrent extends EventEmitter { const self = this if (typeof window !== 'undefined' && typeof window.requestIdleCallback === 'function') { - window.requestIdleCallback(function () { self._updateWire(wire) }) + window.requestIdleCallback(function () { self._updateWire(wire) }, { timeout: 250 }) } else { self._updateWire(wire) } @@ -1618,7 +1638,7 @@ class Torrent extends EventEmitter { _debug () { const args = [].slice.call(arguments) - args[0] = `[${this.client._debugId}] [${this._debugId}] ${args[0]}` + args[0] = `[${this.client ? this.client._debugId : 'No Client'}] [${this._debugId}] ${args[0]}` debug(...args) } diff --git a/package.json b/package.json index f857ee7..23766d2 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "webtorrent", "description": "Streaming torrent client", - "version": "0.107.2", + "version": "0.108.1", "author": { "name": "WebTorrent, LLC", "email": "feross@webtorrent.io", @@ -41,16 +41,17 @@ "chunk-store-stream": "^4.0.0", "create-torrent": "^4.0.0", "debug": "^4.1.0", - "end-of-stream": "^1.1.0", + "end-of-stream": "1.4.1", + "escape-html": "^1.0.3", "fs-chunk-store": "^2.0.0", - "http-node": "github:feross/http-node#cddd2872f0020ecf5016f326cf5e58c965eef52a", + "http-node": "github:feross/http-node#webtorrent", "immediate-chunk-store": "^2.0.0", "load-ip-set": "^2.1.0", "memory-chunk-store": "^1.2.0", "mime": "^2.4.0", "multistream": "^4.0.0", "package-json-versionify": "^1.0.2", - "parse-numeric-range": "^0.0.2", + "parse-numeric-range": "^1.2.0", "parse-torrent": "^7.0.0", "pump": "^3.0.0", "random-iterate": "^1.0.1", @@ -63,31 +64,30 @@ "simple-concat": "^1.0.0", "simple-get": "^3.0.1", "simple-peer": "^9.0.0", - "simple-sha1": "^2.0.8", + "simple-sha1": "^3.0.1", "speedometer": "^1.0.0", "stream-to-blob": "^2.0.0", - "stream-to-blob-url": "^2.1.0", + "stream-to-blob-url": "^3.0.0", "stream-with-known-length-to-buffer": "^1.0.0", "torrent-discovery": "^9.1.1", "torrent-piece": "^2.0.0", - "uniq": "^1.0.1", "unordered-array-remove": "^1.0.2", "ut_metadata": "^3.3.0", "ut_pex": "^2.0.0" }, "devDependencies": { - "airtap": "^2.0.3", + "airtap": "^3.0.0", + "babel-minify": "^0.5.1", "bittorrent-tracker": "^9.14.0", "browserify": "^16.5.0", "disc": "^1.3.3", - "electron": "^6.0.1", + "electron": "^8.0.0", "finalhandler": "^1.0.0", "network-address": "^1.1.0", "run-series": "^1.1.4", "serve-static": "^1.11.1", "standard": "*", - "tape": "^4.6.0", - "tinyify": "^2.5.1", + "tape": "^5.0.0", "webtorrent-fixtures": "^1.5.0" }, "engines": { @@ -118,13 +118,13 @@ }, "scripts": { "build": "npm run build-js && npm run build-chromeapp", - "build-chromeapp": "browserify --browser-field=chromeapp --standalone WebTorrent --plugin tinyify . > webtorrent.chromeapp.js", + "build-chromeapp": "browserify --browser-field=chromeapp --standalone WebTorrent . | minify --mangle=false > webtorrent.chromeapp.js", "build-chromeapp-debug": "browserify --browser-field=chromeapp --standalone WebTorrent . > webtorrent.chromeapp.js", - "build-js": "browserify --standalone WebTorrent --plugin tinyify . > webtorrent.min.js", + "build-js": "browserify --standalone WebTorrent . | minify --mangle=false > webtorrent.min.js", "build-js-debug": "browserify --standalone WebTorrent . > webtorrent.debug.js", "size": "npm run size-js && npm run size-disc", "size-js": "npm run build && cat webtorrent.min.js | gzip | wc -c", - "size-disc": "browserify --plugin tinyify --full-paths . | discify --open", + "size-disc": "browserify --full-paths . | discify --open", "test": "standard && npm run test-node && npm run test-browser", "test-browser": "airtap -- test/*.js test/browser/*.js", "test-browser-local": "airtap --local -- test/*.js test/browser/*.js", diff --git a/test/common.js b/test/common.js new file mode 100644 index 0000000..6f2ce1e --- /dev/null +++ b/test/common.js @@ -0,0 +1,13 @@ +const os = require('os') +const fs = require('fs') +const path = require('path') + +exports.getDownloadPath = function (infix, infoHash) { + let tmpPath + try { + tmpPath = path.join(fs.statSync('/tmp') && '/tmp') + } catch (err) { + tmpPath = path.join(typeof os.tmpdir === 'function' ? os.tmpdir() : '/') + } + return path.join(tmpPath, 'webtorrent', 'test', infix, infoHash) +} diff --git a/test/node/blocklist-dht.js b/test/node/blocklist-dht.js index e956731..fa3915a 100644 --- a/test/node/blocklist-dht.js +++ b/test/node/blocklist-dht.js @@ -3,6 +3,7 @@ var fixtures = require('webtorrent-fixtures') var series = require('run-series') var test = require('tape') var WebTorrent = require('../../') +var common = require('../common') test('blocklist blocks peers discovered via DHT', function (t) { t.plan(8) @@ -25,7 +26,9 @@ test('blocklist blocks peers discovered via DHT', function (t) { client1.on('error', function (err) { t.fail(err) }) client1.on('warning', function (err) { t.fail(err) }) - var torrent1 = client1.add(fixtures.leaves.parsedTorrent) + var torrent1 = client1.add(fixtures.leaves.parsedTorrent, { + path: common.getDownloadPath('client_1', fixtures.leaves.parsedTorrent.infoHash) + }) torrent1.on('peer', function () { t.fail('client1 should not find any peers') @@ -63,7 +66,9 @@ test('blocklist blocks peers discovered via DHT', function (t) { client2.on('error', function (err) { t.fail(err) }) client2.on('warning', function (err) { t.fail(err) }) - var torrent2 = client2.add(fixtures.leaves.parsedTorrent) + var torrent2 = client2.add(fixtures.leaves.parsedTorrent, { + path: common.getDownloadPath('client_2', fixtures.leaves.parsedTorrent.infoHash) + }) torrent2.on('blockedPeer', function (addr) { t.pass('client2 blocked connection to client1: ' + addr) diff --git a/test/node/blocklist-tracker.js b/test/node/blocklist-tracker.js index 302bd8f..e877d24 100644 --- a/test/node/blocklist-tracker.js +++ b/test/node/blocklist-tracker.js @@ -3,6 +3,7 @@ var series = require('run-series') var test = require('tape') var TrackerServer = require('bittorrent-tracker/server') var WebTorrent = require('../../') +var common = require('../common') test('blocklist blocks peers discovered via tracker', function (t) { t.plan(9) @@ -38,7 +39,9 @@ test('blocklist blocks peers discovered via tracker', function (t) { client1.on('error', function (err) { t.fail(err) }) client1.on('warning', function (err) { t.fail(err) }) - var torrent1 = client1.add(parsedTorrent) + var torrent1 = client1.add(parsedTorrent, { + path: common.getDownloadPath('client_1', parsedTorrent.infoHash) + }) torrent1.on('invalidPeer', function () { t.pass('client1 found itself') @@ -58,7 +61,9 @@ test('blocklist blocks peers discovered via tracker', function (t) { client2.on('error', function (err) { t.fail(err) }) client2.on('warning', function (err) { t.fail(err) }) - var torrent2 = client2.add(parsedTorrent) + var torrent2 = client2.add(parsedTorrent, { + path: common.getDownloadPath('client_2', parsedTorrent.infoHash) + }) torrent2.once('blockedPeer', function () { t.pass('client2 blocked first peer') diff --git a/test/node/download-private-dht.js b/test/node/download-private-dht.js index 35f90d3..0bc43c8 100644 --- a/test/node/download-private-dht.js +++ b/test/node/download-private-dht.js @@ -101,3 +101,107 @@ test('public torrent should use DHT', function (t) { }) }) }) + +test('public torrent with forced private option should not use DHT', function (t) { + t.plan(4) + + var dhtServer = new DHT({ bootstrap: false }) + + dhtServer.on('error', function (err) { t.fail(err) }) + dhtServer.on('warning', function (err) { t.fail(err) }) + + var client + + series([ + function (cb) { + dhtServer.listen(cb) + }, + + function (cb) { + client = new WebTorrent({ + tracker: false, + dht: { bootstrap: '127.0.0.1:' + dhtServer.address().port } + }) + + client.on('error', function (err) { t.fail(err) }) + client.on('warning', function (err) { t.fail(err) }) + + var torrent = client.add(fixtures.leaves.parsedTorrent, { + private: true, + store: MemoryChunkStore + }) + + torrent.on('dhtAnnounce', function () { + t.fail('client announced to dht') + }) + + client.on('torrent', function () { + if (!torrent.discovery.dht) { + t.pass('dht is disabled for this torrent') + cb(null) + } + }) + } + ], function (err) { + t.error(err) + + dhtServer.destroy(function (err) { + t.error(err, 'dht server destroyed') + }) + client.destroy(function (err) { + t.error(err, 'client destroyed') + }) + }) +}) + +test('private torrent with forced public option should use DHT', function (t) { + t.plan(4) + + var dhtServer = new DHT({ bootstrap: false }) + + dhtServer.on('error', function (err) { t.fail(err) }) + dhtServer.on('warning', function (err) { t.fail(err) }) + + var client + + series([ + function (cb) { + dhtServer.listen(cb) + }, + + function (cb) { + client = new WebTorrent({ + tracker: false, + dht: { bootstrap: '127.0.0.1:' + dhtServer.address().port } + }) + + client.on('error', function (err) { t.fail(err) }) + client.on('warning', function (err) { t.fail(err) }) + + var torrent = client.add(fixtures.bunny.parsedTorrent, { + private: false, + store: MemoryChunkStore + }) + + torrent.on('dhtAnnounce', function () { + t.pass('client announced to dht') + cb(null) + }) + + client.on('torrent', function () { + if (!torrent.client.dht) { + t.fail('dht server is null') + } + }) + } + ], function (err) { + t.error(err) + + dhtServer.destroy(function (err) { + t.error(err, 'dht server destroyed') + }) + client.destroy(function (err) { + t.error(err, 'client destroyed') + }) + }) +}) diff --git a/test/node/torrent-events.js b/test/node/torrent-events.js new file mode 100644 index 0000000..916ca4e --- /dev/null +++ b/test/node/torrent-events.js @@ -0,0 +1,83 @@ +const fixtures = require('webtorrent-fixtures') +const test = require('tape') +const WebTorrent = require('../../') +const MemoryChunkStore = require('memory-chunk-store') + +test('client.add: emit torrent events in order', function (t) { + t.plan(6) + + var client1 = new WebTorrent({ dht: false, tracker: false }) + var client2 = new WebTorrent({ dht: false, tracker: false }) + + client1.on('error', function (err) { t.fail(err) }) + client1.on('warning', function (err) { t.fail(err) }) + + client2.on('error', function (err) { t.fail(err) }) + client2.on('warning', function (err) { t.fail(err) }) + + // Start seeding + client2.seed(fixtures.leaves.content, { + name: 'Leaves of Grass by Walt Whitman.epub', + announce: [] + }) + + client2.on('listening', function () { + // Start downloading + var torrent = client1.add(fixtures.leaves.parsedTorrent.infoHash, { store: MemoryChunkStore }) + + // Manually connect peers + torrent.addPeer('127.0.0.1:' + client2.address().port) + + var order = 0 + + torrent.on('infoHash', function () { + t.equal(++order, 1) + }) + + torrent.on('metadata', function () { + t.equal(++order, 2) + }) + + torrent.on('ready', function () { + t.equal(++order, 3) + }) + + torrent.on('done', function () { + t.equal(++order, 4) + + client1.destroy(function (err) { t.error(err, 'client 1 destroyed') }) + client2.destroy(function (err) { t.error(err, 'client 2 destroyed') }) + }) + }) +}) + +test('client.seed: emit torrent events in order', function (t) { + t.plan(5) + + var client = new WebTorrent({ dht: false, tracker: false }) + + client.on('error', function (err) { t.fail(err) }) + client.on('warning', function (err) { t.fail(err) }) + + var torrent = client.seed(fixtures.leaves.content) + + var order = 0 + + torrent.on('infoHash', function () { + t.equal(++order, 1) + }) + + torrent.on('metadata', function () { + t.equal(++order, 2) + }) + + torrent.on('ready', function () { + t.equal(++order, 3) + }) + + torrent.on('done', function () { + t.equal(++order, 4) + + client.destroy(function (err) { t.error(err, 'client destroyed') }) + }) +}) diff --git a/webtorrent.min.js b/webtorrent.min.js index 0f7cc1e..8c579b7 100644 --- a/webtorrent.min.js +++ b/webtorrent.min.js @@ -1 +1,6 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).WebTorrent=e()}}(function(){var e=function(e){var t;return function(n){return t||e(t={exports:{},parent:n},t.exports),t.exports}},t=e(function(e,t){(function(e){var r=n({}),i=t,s={moov:["mvhd","meta","traks","mvex"],trak:["tkhd","tref","trgr","edts","meta","mdia","udta"],edts:["elst"],mdia:["mdhd","hdlr","elng","minf"],minf:["vmhd","smhd","hmhd","sthd","nmhd","dinf","stbl"],dinf:["dref"],stbl:["stsd","stts","ctts","cslg","stsc","stsz","stz2","stco","co64","stss","stsh","padb","stdp","sdtp","sbgps","sgpds","subss","saizs","saios"],mvex:["mehd","trexs","leva"],moof:["mfhd","meta","trafs"],traf:["tfhd","tfdt","trun","sbgps","sgpds","subss","saizs","saios","meta"]};i.encode=function(t,n,r){return i.encodingLength(t),r=r||0,n=n||e.alloc(t.length),i._encode(t,n,r)},i._encode=function(e,t,n){var o=e.type,a=e.length;a>4294967295&&(a=1),t.writeUInt32BE(a,n),t.write(e.type,n+4,4,"ascii");var h=n+8;if(1===a&&(Ir.encode(e.length,t,h),h+=8),r.fullBoxes[o]&&(t.writeUInt32BE(e.flags||0,h),t.writeUInt8(e.version||0,h),h+=4),s[o])s[o].forEach(function(n){if(5===n.length){var r=e[n]||[];n=n.substr(0,4),r.forEach(function(e){i._encode(e,t,h),h+=i.encode.bytes})}else e[n]&&(i._encode(e[n],t,h),h+=i.encode.bytes)}),e.otherBoxes&&e.otherBoxes.forEach(function(e){i._encode(e,t,h),h+=i.encode.bytes});else if(r[o]){var c=r[o].encode;c(e,t,h),h+=c.bytes}else{if(!e.buffer)throw new Error("Either `type` must be set to a known type (not'"+o+"') or `buffer` must be set");e.buffer.copy(t,h),h+=e.buffer.length}return i.encode.bytes=h-n,t},i.readHeaders=function(e,t,n){if(t=t||0,(n=n||e.length)-t<8)return 8;var i,s,o=e.readUInt32BE(t),a=e.toString("ascii",t+4,t+8),h=t+8;if(1===o){if(n-t<16)return 16;o=Ir.decode(e,h),h+=8}return r.fullBoxes[a]&&(i=e.readUInt8(h),s=16777215&e.readUInt32BE(h),h+=4),{length:o,headersLen:h-t,contentLen:o-(h-t),type:a,version:i,flags:s}},i.decode=function(e,t,n){t=t||0,n=n||e.length;var r=i.readHeaders(e,t,n);if(!r||r.length>n-t)throw new Error("Data too short");return i.decodeWithoutHeaders(r,e,t+r.headersLen,t+r.length)},i.decodeWithoutHeaders=function(t,n,o,a){o=o||0,a=a||n.length;var h=t.type,c={};if(s[h]){c.otherBoxes=[];for(var u=s[h],d=o;a-d>=8;){var l=i.decode(n,d,a);if(d+=l.length,u.indexOf(l.type)>=0)c[l.type]=l;else if(u.indexOf(l.type+"s")>=0){var f=l.type+"s";(c[f]=c[f]||[]).push(l)}else c.otherBoxes.push(l)}}else r[h]?c=(0,r[h].decode)(n,o,a):c.buffer=e.from(n.slice(o,a));return c.length=t.length,c.contentLen=t.contentLen,c.type=t.type,c.version=t.version,c.flags=t.flags,c},i.encodingLength=function(e){var t=e.type,n=8;if(r.fullBoxes[t]&&(n+=4),s[t])s[t].forEach(function(t){if(5===t.length){var r=e[t]||[];t=t.substr(0,4),r.forEach(function(e){e.type=t,n+=i.encodingLength(e)})}else if(e[t]){var s=e[t];s.type=t,n+=i.encodingLength(s)}}),e.otherBoxes&&e.otherBoxes.forEach(function(e){n+=i.encodingLength(e)});else if(r[t])n+=r[t].encodingLength(e);else{if(!e.buffer)throw new Error("Either `type` must be set to a known type (not'"+t+"') or `buffer` must be set");n+=e.buffer.length}return n>4294967295&&(n+=8),e.length=n,n}}).call(this,d({}).Buffer)}),n=e(function(e,n){(function(e){var r=t({}),i=20828448e5;function s(e,t,n){for(var r=t;r<n;r++)e[r]=0}function o(e,t,n){t.writeUInt32BE(Math.floor((e.getTime()+i)/1e3),n)}function a(e,t,n){t.writeUIntBE(Math.floor((e.getTime()+i)/1e3),n,6)}function h(e,t,n){t.writeUInt16BE(Math.floor(e)%65536,n),t.writeUInt16BE(Math.floor(256*e*256)%65536,n+2)}function c(e,t,n){e||(e=[0,0,0,0,0,0,0,0,0]);for(var r=0;r<e.length;r++)h(e[r],t,n+4*r)}function u(e){for(var t=new Array(e.length/4),n=0;n<t.length;n++)t[n]=f(e,4*n);return t}function d(e,t){return new Date(1e3*e.readUIntBE(t,6)-i)}function l(e,t){return new Date(1e3*e.readUInt32BE(t)-i)}function f(e,t){return e.readUInt16BE(t)+e.readUInt16BE(t+2)/65536}function p(e,t){return e[t]+e[t+1]/256}function g(e,t,n){var r;for(r=0;r<n&&0!==e[t+r];r++);return e.toString("utf8",t,t+r)}n.fullBoxes={},["mvhd","tkhd","mdhd","vmhd","smhd","stsd","esds","stsz","stco","co64","stss","stts","ctts","stsc","dref","elst","hdlr","mehd","trex","mfhd","tfhd","tfdt","trun"].forEach(function(e){n.fullBoxes[e]=!0}),n.ftyp={},n.ftyp.encode=function(t,r,i){r=r?r.slice(i):e.alloc(n.ftyp.encodingLength(t));var s=t.compatibleBrands||[];r.write(t.brand,0,4,"ascii"),r.writeUInt32BE(t.brandVersion,4);for(var o=0;o<s.length;o++)r.write(s[o],8+4*o,4,"ascii");return n.ftyp.encode.bytes=8+4*s.length,r},n.ftyp.decode=function(e,t){for(var n=(e=e.slice(t)).toString("ascii",0,4),r=e.readUInt32BE(4),i=[],s=8;s<e.length;s+=4)i.push(e.toString("ascii",s,s+4));return{brand:n,brandVersion:r,compatibleBrands:i}},n.ftyp.encodingLength=function(e){return 8+4*(e.compatibleBrands||[]).length},n.mvhd={},n.mvhd.encode=function(t,r,i){return r=r?r.slice(i):e.alloc(96),o(t.ctime||new Date,r,0),o(t.mtime||new Date,r,4),r.writeUInt32BE(t.timeScale||0,8),r.writeUInt32BE(t.duration||0,12),h(t.preferredRate||0,r,16),function(e,t,n){t[20]=Math.floor(e)%256,t[21]=Math.floor(256*e)%256}(t.preferredVolume||0,r),s(r,22,32),c(t.matrix,r,32),r.writeUInt32BE(t.previewTime||0,68),r.writeUInt32BE(t.previewDuration||0,72),r.writeUInt32BE(t.posterTime||0,76),r.writeUInt32BE(t.selectionTime||0,80),r.writeUInt32BE(t.selectionDuration||0,84),r.writeUInt32BE(t.currentTime||0,88),r.writeUInt32BE(t.nextTrackId||0,92),n.mvhd.encode.bytes=96,r},n.mvhd.decode=function(e,t){return{ctime:l(e=e.slice(t),0),mtime:l(e,4),timeScale:e.readUInt32BE(8),duration:e.readUInt32BE(12),preferredRate:f(e,16),preferredVolume:p(e,20),matrix:u(e.slice(32,68)),previewTime:e.readUInt32BE(68),previewDuration:e.readUInt32BE(72),posterTime:e.readUInt32BE(76),selectionTime:e.readUInt32BE(80),selectionDuration:e.readUInt32BE(84),currentTime:e.readUInt32BE(88),nextTrackId:e.readUInt32BE(92)}},n.mvhd.encodingLength=function(e){return 96},n.tkhd={},n.tkhd.encode=function(t,r,i){return r=r?r.slice(i):e.alloc(80),o(t.ctime||new Date,r,0),o(t.mtime||new Date,r,4),r.writeUInt32BE(t.trackId||0,8),s(r,12,16),r.writeUInt32BE(t.duration||0,16),s(r,20,28),r.writeUInt16BE(t.layer||0,28),r.writeUInt16BE(t.alternateGroup||0,30),r.writeUInt16BE(t.volume||0,32),c(t.matrix,r,36),r.writeUInt32BE(t.trackWidth||0,72),r.writeUInt32BE(t.trackHeight||0,76),n.tkhd.encode.bytes=80,r},n.tkhd.decode=function(e,t){return{ctime:l(e=e.slice(t),0),mtime:l(e,4),trackId:e.readUInt32BE(8),duration:e.readUInt32BE(16),layer:e.readUInt16BE(28),alternateGroup:e.readUInt16BE(30),volume:e.readUInt16BE(32),matrix:u(e.slice(36,72)),trackWidth:e.readUInt32BE(72),trackHeight:e.readUInt32BE(76)}},n.tkhd.encodingLength=function(e){return 80},n.mdhd={},n.mdhd.encode=function(t,r,i){return 1===t.version?(r=r?r.slice(i):e.alloc(32),a(t.ctime||new Date,r,0),a(t.mtime||new Date,r,8),r.writeUInt32BE(t.timeScale||0,16),r.writeUIntBE(t.duration||0,20,6),r.writeUInt16BE(t.language||0,28),r.writeUInt16BE(t.quality||0,30),n.mdhd.encode.bytes=32,r):(r=r?r.slice(i):e.alloc(20),o(t.ctime||new Date,r,0),o(t.mtime||new Date,r,4),r.writeUInt32BE(t.timeScale||0,8),r.writeUInt32BE(t.duration||0,12),r.writeUInt16BE(t.language||0,16),r.writeUInt16BE(t.quality||0,18),n.mdhd.encode.bytes=20,r)},n.mdhd.decode=function(e,t,n){return e=e.slice(t),n-t!=20?{ctime:d(e,0),mtime:d(e,8),timeScale:e.readUInt32BE(16),duration:e.readUIntBE(20,6),language:e.readUInt16BE(28),quality:e.readUInt16BE(30)}:{ctime:l(e,0),mtime:l(e,4),timeScale:e.readUInt32BE(8),duration:e.readUInt32BE(12),language:e.readUInt16BE(16),quality:e.readUInt16BE(18)}},n.mdhd.encodingLength=function(e){return 1===e.version?32:20},n.vmhd={},n.vmhd.encode=function(t,r,i){(r=r?r.slice(i):e.alloc(8)).writeUInt16BE(t.graphicsMode||0,0);var s=t.opcolor||[0,0,0];return r.writeUInt16BE(s[0],2),r.writeUInt16BE(s[1],4),r.writeUInt16BE(s[2],6),n.vmhd.encode.bytes=8,r},n.vmhd.decode=function(e,t){return{graphicsMode:(e=e.slice(t)).readUInt16BE(0),opcolor:[e.readUInt16BE(2),e.readUInt16BE(4),e.readUInt16BE(6)]}},n.vmhd.encodingLength=function(e){return 8},n.smhd={},n.smhd.encode=function(t,r,i){return(r=r?r.slice(i):e.alloc(4)).writeUInt16BE(t.balance||0,0),s(r,2,4),n.smhd.encode.bytes=4,r},n.smhd.decode=function(e,t){return{balance:(e=e.slice(t)).readUInt16BE(0)}},n.smhd.encodingLength=function(e){return 4},n.stsd={},n.stsd.encode=function(t,i,s){i=i?i.slice(s):e.alloc(n.stsd.encodingLength(t));var o=t.entries||[];i.writeUInt32BE(o.length,0);for(var a=4,h=0;h<o.length;h++){var c=o[h];r.encode(c,i,a),a+=r.encode.bytes}return n.stsd.encode.bytes=a,i},n.stsd.decode=function(e,t,n){for(var i=(e=e.slice(t)).readUInt32BE(0),s=new Array(i),o=4,a=0;a<i;a++){var h=r.decode(e,o,n);s[a]=h,o+=h.length}return{entries:s}},n.stsd.encodingLength=function(e){var t=4;if(!e.entries)return t;for(var n=0;n<e.entries.length;n++)t+=r.encodingLength(e.entries[n]);return t},n.avc1=n.VisualSampleEntry={},n.VisualSampleEntry.encode=function(t,i,o){s(i=i?i.slice(o):e.alloc(n.VisualSampleEntry.encodingLength(t)),0,6),i.writeUInt16BE(t.dataReferenceIndex||0,6),s(i,8,24),i.writeUInt16BE(t.width||0,24),i.writeUInt16BE(t.height||0,26),i.writeUInt32BE(t.hResolution||4718592,28),i.writeUInt32BE(t.vResolution||4718592,32),s(i,36,40),i.writeUInt16BE(t.frameCount||1,40);var a=t.compressorName||"",h=Math.min(a.length,31);i.writeUInt8(h,42),i.write(a,43,h,"utf8"),i.writeUInt16BE(t.depth||24,74),i.writeInt16BE(-1,76);var c=78;(t.children||[]).forEach(function(e){r.encode(e,i,c),c+=r.encode.bytes}),n.VisualSampleEntry.encode.bytes=c},n.VisualSampleEntry.decode=function(e,t,n){e=e.slice(t);for(var i=n-t,s=Math.min(e.readUInt8(42),31),o={dataReferenceIndex:e.readUInt16BE(6),width:e.readUInt16BE(24),height:e.readUInt16BE(26),hResolution:e.readUInt32BE(28),vResolution:e.readUInt32BE(32),frameCount:e.readUInt16BE(40),compressorName:e.toString("utf8",43,43+s),depth:e.readUInt16BE(74),children:[]},a=78;i-a>=8;){var h=r.decode(e,a,i);o.children.push(h),o[h.type]=h,a+=h.length}return o},n.VisualSampleEntry.encodingLength=function(e){var t=78;return(e.children||[]).forEach(function(e){t+=r.encodingLength(e)}),t},n.avcC={},n.avcC.encode=function(t,r,i){r=r?r.slice(i):e.alloc(t.buffer.length),t.buffer.copy(r),n.avcC.encode.bytes=t.buffer.length},n.avcC.decode=function(t,n,r){return{mimeCodec:(t=t.slice(n,r)).toString("hex",1,4),buffer:e.from(t)}},n.avcC.encodingLength=function(e){return e.buffer.length},n.mp4a=n.AudioSampleEntry={},n.AudioSampleEntry.encode=function(t,i,o){s(i=i?i.slice(o):e.alloc(n.AudioSampleEntry.encodingLength(t)),0,6),i.writeUInt16BE(t.dataReferenceIndex||0,6),s(i,8,16),i.writeUInt16BE(t.channelCount||2,16),i.writeUInt16BE(t.sampleSize||16,18),s(i,20,24),i.writeUInt32BE(t.sampleRate||0,24);var a=28;(t.children||[]).forEach(function(e){r.encode(e,i,a),a+=r.encode.bytes}),n.AudioSampleEntry.encode.bytes=a},n.AudioSampleEntry.decode=function(e,t,n){for(var i=n-t,s={dataReferenceIndex:(e=e.slice(t,n)).readUInt16BE(6),channelCount:e.readUInt16BE(16),sampleSize:e.readUInt16BE(18),sampleRate:e.readUInt32BE(24),children:[]},o=28;i-o>=8;){var a=r.decode(e,o,i);s.children.push(a),s[a.type]=a,o+=a.length}return s},n.AudioSampleEntry.encodingLength=function(e){var t=28;return(e.children||[]).forEach(function(e){t+=r.encodingLength(e)}),t},n.esds={},n.esds.encode=function(t,r,i){r=r?r.slice(i):e.alloc(t.buffer.length),t.buffer.copy(r,0),n.esds.encode.bytes=t.buffer.length},n.esds.decode=function(t,n,r){t=t.slice(n,r);var i=Rr.Descriptor.decode(t,0,t.length),s=("ESDescriptor"===i.tagName?i:{}).DecoderConfigDescriptor||{},o=s.oti||0,a=s.DecoderSpecificInfo,h=a?(248&a.buffer.readUInt8(0))>>3:0,c=null;return o&&(c=o.toString(16),h&&(c+="."+h)),{mimeCodec:c,buffer:e.from(t.slice(0))}},n.esds.encodingLength=function(e){return e.buffer.length},n.stsz={},n.stsz.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.stsz.encodingLength(t))).writeUInt32BE(0,0),r.writeUInt32BE(s.length,4);for(var o=0;o<s.length;o++)r.writeUInt32BE(s[o],4*o+8);return n.stsz.encode.bytes=8+4*s.length,r},n.stsz.decode=function(e,t){for(var n=(e=e.slice(t)).readUInt32BE(0),r=e.readUInt32BE(4),i=new Array(r),s=0;s<r;s++)i[s]=0===n?e.readUInt32BE(4*s+8):n;return{entries:i}},n.stsz.encodingLength=function(e){return 8+4*e.entries.length},n.stss=n.stco={},n.stco.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.stco.encodingLength(t))).writeUInt32BE(s.length,0);for(var o=0;o<s.length;o++)r.writeUInt32BE(s[o],4*o+4);return n.stco.encode.bytes=4+4*s.length,r},n.stco.decode=function(e,t){for(var n=(e=e.slice(t)).readUInt32BE(0),r=new Array(n),i=0;i<n;i++)r[i]=e.readUInt32BE(4*i+4);return{entries:r}},n.stco.encodingLength=function(e){return 4+4*e.entries.length},n.co64={},n.co64.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.co64.encodingLength(t))).writeUInt32BE(s.length,0);for(var o=0;o<s.length;o++)Ir.encode(s[o],r,8*o+4);return n.co64.encode.bytes=4+8*s.length,r},n.co64.decode=function(e,t){for(var n=(e=e.slice(t)).readUInt32BE(0),r=new Array(n),i=0;i<n;i++)r[i]=Ir.decode(e,8*i+4);return{entries:r}},n.co64.encodingLength=function(e){return 4+8*e.entries.length},n.stts={},n.stts.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.stts.encodingLength(t))).writeUInt32BE(s.length,0);for(var o=0;o<s.length;o++){var a=8*o+4;r.writeUInt32BE(s[o].count||0,a),r.writeUInt32BE(s[o].duration||0,a+4)}return n.stts.encode.bytes=4+8*t.entries.length,r},n.stts.decode=function(e,t){for(var n=(e=e.slice(t)).readUInt32BE(0),r=new Array(n),i=0;i<n;i++){var s=8*i+4;r[i]={count:e.readUInt32BE(s),duration:e.readUInt32BE(s+4)}}return{entries:r}},n.stts.encodingLength=function(e){return 4+8*e.entries.length},n.ctts={},n.ctts.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.ctts.encodingLength(t))).writeUInt32BE(s.length,0);for(var o=0;o<s.length;o++){var a=8*o+4;r.writeUInt32BE(s[o].count||0,a),r.writeUInt32BE(s[o].compositionOffset||0,a+4)}return n.ctts.encode.bytes=4+8*s.length,r},n.ctts.decode=function(e,t){for(var n=(e=e.slice(t)).readUInt32BE(0),r=new Array(n),i=0;i<n;i++){var s=8*i+4;r[i]={count:e.readUInt32BE(s),compositionOffset:e.readInt32BE(s+4)}}return{entries:r}},n.ctts.encodingLength=function(e){return 4+8*e.entries.length},n.stsc={},n.stsc.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.stsc.encodingLength(t))).writeUInt32BE(s.length,0);for(var o=0;o<s.length;o++){var a=12*o+4;r.writeUInt32BE(s[o].firstChunk||0,a),r.writeUInt32BE(s[o].samplesPerChunk||0,a+4),r.writeUInt32BE(s[o].sampleDescriptionId||0,a+8)}return n.stsc.encode.bytes=4+12*s.length,r},n.stsc.decode=function(e,t){for(var n=(e=e.slice(t)).readUInt32BE(0),r=new Array(n),i=0;i<n;i++){var s=12*i+4;r[i]={firstChunk:e.readUInt32BE(s),samplesPerChunk:e.readUInt32BE(s+4),sampleDescriptionId:e.readUInt32BE(s+8)}}return{entries:r}},n.stsc.encodingLength=function(e){return 4+12*e.entries.length},n.dref={},n.dref.encode=function(t,r,i){r=r?r.slice(i):e.alloc(n.dref.encodingLength(t));var s=t.entries||[];r.writeUInt32BE(s.length,0);for(var o=4,a=0;a<s.length;a++){var h=s[a],c=(h.buf?h.buf.length:0)+4+4;r.writeUInt32BE(c,o),o+=4,r.write(h.type,o,4,"ascii"),o+=4,h.buf&&(h.buf.copy(r,o),o+=h.buf.length)}return n.dref.encode.bytes=o,r},n.dref.decode=function(e,t){for(var n=(e=e.slice(t)).readUInt32BE(0),r=new Array(n),i=4,s=0;s<n;s++){var o=e.readUInt32BE(i),a=e.toString("ascii",i+4,i+8),h=e.slice(i+8,i+o);i+=o,r[s]={type:a,buf:h}}return{entries:r}},n.dref.encodingLength=function(e){var t=4;if(!e.entries)return t;for(var n=0;n<e.entries.length;n++){var r=e.entries[n].buf;t+=(r?r.length:0)+4+4}return t},n.elst={},n.elst.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.elst.encodingLength(t))).writeUInt32BE(s.length,0);for(var o=0;o<s.length;o++){var a=12*o+4;r.writeUInt32BE(s[o].trackDuration||0,a),r.writeUInt32BE(s[o].mediaTime||0,a+4),h(s[o].mediaRate||0,r,a+8)}return n.elst.encode.bytes=4+12*s.length,r},n.elst.decode=function(e,t){for(var n=(e=e.slice(t)).readUInt32BE(0),r=new Array(n),i=0;i<n;i++){var s=12*i+4;r[i]={trackDuration:e.readUInt32BE(s),mediaTime:e.readInt32BE(s+4),mediaRate:f(e,s+8)}}return{entries:r}},n.elst.encodingLength=function(e){return 4+12*e.entries.length},n.hdlr={},n.hdlr.encode=function(t,r,i){r=r?r.slice(i):e.alloc(n.hdlr.encodingLength(t));var s=21+(t.name||"").length;return r.fill(0,0,s),r.write(t.handlerType||"",4,4,"ascii"),function(t,n,r){var i=e.from(t,"utf8");i.copy(n,20),n[20+i.length]=0}(t.name||"",r),n.hdlr.encode.bytes=s,r},n.hdlr.decode=function(e,t,n){return{handlerType:(e=e.slice(t)).toString("ascii",4,8),name:g(e,20,n)}},n.hdlr.encodingLength=function(e){return 21+(e.name||"").length},n.mehd={},n.mehd.encode=function(t,r,i){return(r=r?r.slice(i):e.alloc(4)).writeUInt32BE(t.fragmentDuration||0,0),n.mehd.encode.bytes=4,r},n.mehd.decode=function(e,t){return{fragmentDuration:(e=e.slice(t)).readUInt32BE(0)}},n.mehd.encodingLength=function(e){return 4},n.trex={},n.trex.encode=function(t,r,i){return(r=r?r.slice(i):e.alloc(20)).writeUInt32BE(t.trackId||0,0),r.writeUInt32BE(t.defaultSampleDescriptionIndex||0,4),r.writeUInt32BE(t.defaultSampleDuration||0,8),r.writeUInt32BE(t.defaultSampleSize||0,12),r.writeUInt32BE(t.defaultSampleFlags||0,16),n.trex.encode.bytes=20,r},n.trex.decode=function(e,t){return{trackId:(e=e.slice(t)).readUInt32BE(0),defaultSampleDescriptionIndex:e.readUInt32BE(4),defaultSampleDuration:e.readUInt32BE(8),defaultSampleSize:e.readUInt32BE(12),defaultSampleFlags:e.readUInt32BE(16)}},n.trex.encodingLength=function(e){return 20},n.mfhd={},n.mfhd.encode=function(t,r,i){return(r=r?r.slice(i):e.alloc(4)).writeUInt32BE(t.sequenceNumber||0,0),n.mfhd.encode.bytes=4,r},n.mfhd.decode=function(e,t){return{sequenceNumber:e.readUInt32BE(0)}},n.mfhd.encodingLength=function(e){return 4},n.tfhd={},n.tfhd.encode=function(t,r,i){return(r=r?r.slice(i):e.alloc(4)).writeUInt32BE(t.trackId,0),n.tfhd.encode.bytes=4,r},n.tfhd.decode=function(e,t){},n.tfhd.encodingLength=function(e){return 4},n.tfdt={},n.tfdt.encode=function(t,r,i){return(r=r?r.slice(i):e.alloc(4)).writeUInt32BE(t.baseMediaDecodeTime||0,0),n.tfdt.encode.bytes=4,r},n.tfdt.decode=function(e,t){},n.tfdt.encodingLength=function(e){return 4},n.trun={},n.trun.encode=function(t,r,i){(r=r?r.slice(i):e.alloc(8+16*t.entries.length)).writeUInt32BE(t.entries.length,0),r.writeInt32BE(t.dataOffset,4);for(var s=8,o=0;o<t.entries.length;o++){var a=t.entries[o];r.writeUInt32BE(a.sampleDuration,s),s+=4,r.writeUInt32BE(a.sampleSize,s),s+=4,r.writeUInt32BE(a.sampleFlags,s),s+=4,0===(t.version||0)?r.writeUInt32BE(a.sampleCompositionTimeOffset,s):r.writeInt32BE(a.sampleCompositionTimeOffset,s),s+=4}n.trun.encode.bytes=s},n.trun.decode=function(e,t){},n.trun.encodingLength=function(e){return 8+16*e.entries.length},n.mdat={},n.mdat.encode=function(e,t,r){e.buffer?(e.buffer.copy(t,r),n.mdat.encode.bytes=e.buffer.length):n.mdat.encode.bytes=n.mdat.encodingLength(e)},n.mdat.decode=function(t,n,r){return{buffer:e.from(t.slice(n,r))}},n.mdat.encodingLength=function(e){return e.buffer?e.buffer.length:e.contentLength}}).call(this,d({}).Buffer)}),r=e(function(e,t){var n=1e3,r=6e4,i=36e5,s=24*i;function o(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}e.exports=function(e,t){t=t||{};var a,h,c=typeof e;if("string"===c&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return 6048e5*o;case"days":case"day":case"d":return o*s;case"hours":case"hour":case"hrs":case"hr":case"h":return o*i;case"minutes":case"minute":case"mins":case"min":case"m":return o*r;case"seconds":case"second":case"secs":case"sec":case"s":return o*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===c&&isFinite(e))return t.long?(a=e,(h=Math.abs(a))>=s?o(a,h,s,"day"):h>=i?o(a,h,i,"hour"):h>=r?o(a,h,r,"minute"):h>=n?o(a,h,n,"second"):a+" ms"):function(e){var t=Math.abs(e);return t>=s?Math.round(e/s)+"d":t>=i?Math.round(e/i)+"h":t>=r?Math.round(e/r)+"m":t>=n?Math.round(e/n)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}),i=e(function(e,t){var n=Math.abs;e.exports=function(e,t,r){for(var i,s,o,a=1/0,h=0,c=t.length-1;h<=c&&((o=t[i=h+(c-h>>1)]-e)<0?h=i+1:o>0&&(c=i-1),(o=n(o))<a&&(a=o,s=i),t[i]!==e););return r?s:t[s]}}),s=e(function(e,t){(function(t,n){"use strict";var r;e.exports=S,S.ReadableState=k,l.EventEmitter;var i,s=function(e,t){return e.listeners(t).length},a=d({}).Buffer,u=n.Uint8Array||function(){};i=ne&&ne.debuglog?ne.debuglog("stream"):function(){};var f,p,g=Ae.getHighWaterMark,m=Se.codes,_=m.ERR_INVALID_ARG_TYPE,y=m.ERR_STREAM_PUSH_AFTER_EOF,b=m.ERR_METHOD_NOT_IMPLEMENTED,w=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,v=Re.emitExperimentalWarning;Be(S,te);var E=["error","close","destroy","pause","resume"];function k(e,t,n){r=r||c({}),e=e||{},"boolean"!=typeof n&&(n=t instanceof r),this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=g(this,e,"readableHighWaterMark",n),this.buffer=new ce,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==e.emitClose,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(f||(f=h({}).StringDecoder),this.decoder=new f(e.encoding),this.encoding=e.encoding)}function S(e){if(r=r||c({}),!(this instanceof S))return new S(e);var t=this instanceof r;this._readableState=new k(e,this,t),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),te.call(this)}function C(e,t,n,r,s){i("readableAddChunk",t);var o,h=e._readableState;if(null===t)h.reading=!1,function(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?A(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,R(e)))}}(e,h);else if(s||(o=function(e,t){var n,r;return r=t,a.isBuffer(r)||r instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new _("chunk",["string","Buffer","Uint8Array"],t)),n}(h,t)),o)e.emit("error",o);else if(h.objectMode||t&&t.length>0)if("string"==typeof t||h.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),r)h.endEmitted?e.emit("error",new w):x(e,h,t,!0);else if(h.ended)e.emit("error",new y);else{if(h.destroyed)return!1;h.reading=!1,h.decoder&&!n?(t=h.decoder.write(t),h.objectMode||0!==t.length?x(e,h,t,!1):B(e,h)):x(e,h,t,!1)}else r||(h.reading=!1,B(e,h));return!h.ended&&(h.length<h.highWaterMark||0===h.length)}function x(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&A(e)),B(e,t)}Object.defineProperty(S.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),S.prototype.destroy=ke.destroy,S.prototype._undestroy=ke.undestroy,S.prototype._destroy=function(e,t){t(e)},S.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=a.from(e,t),t=""),n=!0),C(this,e,t,!1,n)},S.prototype.unshift=function(e){return C(this,e,null,!0,!1)},S.prototype.isPaused=function(){return!1===this._readableState.flowing},S.prototype.setEncoding=function(e){return f||(f=h({}).StringDecoder),this._readableState.decoder=new f(e),this._readableState.encoding=this._readableState.decoder.encoding,this};var T=8388608;function I(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=T?e=T:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function A(e){var n=e._readableState;n.needReadable=!1,n.emittedReadable||(i("emitReadable",n.flowing),n.emittedReadable=!0,t.nextTick(R,e))}function R(e){var t=e._readableState;i("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||e.emit("readable"),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,P(e)}function B(e,n){n.readingMore||(n.readingMore=!0,t.nextTick(L,e,n))}function L(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(i("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function U(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function O(e){i("readable nexttick read 0"),e.read(0)}function M(e,t){i("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),P(e),t.flowing&&!t.reading&&e.read(0)}function P(e){var t=e._readableState;for(i("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function H(e){var n=e._readableState;i("endReadable",n.endEmitted),n.endEmitted||(n.ended=!0,t.nextTick(j,n,e))}function j(e,t){i("endReadableNT",e.endEmitted,e.length),e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function D(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}S.prototype.read=function(e){i("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return i("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?H(this):A(this),null;if(0===(e=I(e,t))&&t.ended)return 0===t.length&&H(this),null;var r,s=t.needReadable;return i("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&i("length less than watermark",s=!0),t.ended||t.reading?i("reading or ended",s=!1):s&&(i("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=I(n,t))),null===(r=e>0?N(e,t):null)?(t.needReadable=!0,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&H(this)),null!==r&&this.emit("data",r),r},S.prototype._read=function(e){this.emit("error",new b("_read()"))},S.prototype.pipe=function(e,n){var r=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,i("pipe count=%d opts=%j",o.pipesCount,n);var a=n&&!1===n.end||e===t.stdout||e===t.stderr?g:h;function h(){i("onend"),e.end()}o.endEmitted?t.nextTick(a):r.once("end",a),e.on("unpipe",function t(n,s){i("onunpipe"),n===r&&s&&!1===s.hasUnpiped&&(s.hasUnpiped=!0,i("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",c),e.removeListener("error",l),e.removeListener("unpipe",t),r.removeListener("end",h),r.removeListener("end",g),r.removeListener("data",d),u=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||c())});var c=function(e){return function(){var t=e._readableState;i("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,P(e))}}(r);e.on("drain",c);var u=!1;function d(t){i("ondata");var n=e.write(t);i("dest.write",n),!1===n&&((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==D(o.pipes,e))&&!u&&(i("false write response, pause",o.awaitDrain),o.awaitDrain++),r.pause())}function l(t){i("onerror",t),g(),e.removeListener("error",l),0===s(e,"error")&&e.emit("error",t)}function f(){e.removeListener("finish",p),g()}function p(){i("onfinish"),e.removeListener("close",f),g()}function g(){i("unpipe"),r.unpipe(e)}return r.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener("error",n);e._events&&e._events.error?Array.isArray(e._events.error)?e._events.error.unshift(n):e._events.error=[n,e._events.error]:e.on("error",n)}(e,0,l),e.once("close",f),e.once("finish",p),e.emit("pipe",r),o.flowing||(i("pipe resume"),r.resume()),e},S.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=D(t.pipes,e);return-1===o?this:(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n),this)},S.prototype.on=function(e,n){var r=te.prototype.on.call(this,e,n),s=this._readableState;return"data"===e?(s.readableListening=this.listenerCount("readable")>0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,i("on readable",s.length,s.reading),s.length?A(this):s.reading||t.nextTick(O,this))),r},S.prototype.addListener=S.prototype.on,S.prototype.removeListener=function(e,n){var r=te.prototype.removeListener.call(this,e,n);return"readable"===e&&t.nextTick(U,this),r},S.prototype.removeAllListeners=function(e){var n=te.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||t.nextTick(U,this),n},S.prototype.resume=function(){var e=this._readableState;return e.flowing||(i("resume"),e.flowing=!e.readableListening,function(e,n){n.resumeScheduled||(n.resumeScheduled=!0,t.nextTick(M,e,n))}(this,e)),e.paused=!1,this},S.prototype.pause=function(){return i("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(i("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},S.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var s in e.on("end",function(){if(i("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(s){i("wrapped data"),n.decoder&&(s=n.decoder.write(s)),n.objectMode&&null==s||(n.objectMode||s&&s.length)&&(t.push(s)||(r=!0,e.pause()))}),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var o=0;o<E.length;o++)e.on(E[o],this.emit.bind(this,E[o]));return this._read=function(t){i("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(S.prototype[Symbol.asyncIterator]=function(){return v("Readable[Symbol.asyncIterator]"),void 0===p&&(p=o({})),p(this)}),Object.defineProperty(S.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(S.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(S.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),S._fromList=N,Object.defineProperty(S.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}})}).call(this,ue,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})}),o=e(function(e,t){(function(t){"use strict";var n;function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var i=a({}),s=Symbol("lastResolve"),o=Symbol("lastReject"),h=Symbol("error"),c=Symbol("ended"),u=Symbol("lastPromise"),d=Symbol("handlePromise"),l=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[s];if(null!==t){var n=e[l].read();null!==n&&(e[u]=null,e[s]=null,e[o]=null,t(f(n,!1)))}}var g=Object.getPrototypeOf(function(){}),m=Object.setPrototypeOf((r(n={get stream(){return this[l]},next:function(){var e=this,n=this[h];if(null!==n)return Promise.reject(n);if(this[c])return Promise.resolve(f(void 0,!0));if(this[l].destroyed)return new Promise(function(n,r){t.nextTick(function(){e[h]?r(e[h]):n(f(void 0,!0))})});var r,i=this[u];if(i)r=new Promise(function(e,t){return function(n,r){e.then(function(){t[c]?n(f(void 0,!0)):t[d](n,r)},r)}}(i,this));else{var s=this[l].read();if(null!==s)return Promise.resolve(f(s,!1));r=new Promise(this[d])}return this[u]=r,r}},Symbol.asyncIterator,function(){return this}),r(n,"return",function(){var e=this;return new Promise(function(t,n){e[l].destroy(null,function(e){e?n(e):t(f(void 0,!0))})})}),n),g);e.exports=function(e){var n,a=Object.create(m,(r(n={},l,{value:e,writable:!0}),r(n,s,{value:null,writable:!0}),r(n,o,{value:null,writable:!0}),r(n,h,{value:null,writable:!0}),r(n,c,{value:e._readableState.endEmitted,writable:!0}),r(n,d,{value:function(e,t){var n=a[l].read();n?(a[u]=null,a[s]=null,a[o]=null,e(f(n,!1))):(a[s]=e,a[o]=t)},writable:!0}),n));return a[u]=null,i(e,function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=a[o];return null!==t&&(a[u]=null,a[s]=null,a[o]=null,t(e)),void(a[h]=e)}var n=a[s];null!==n&&(a[u]=null,a[s]=null,a[o]=null,n(f(void 0,!0))),a[c]=!0}),e.on("readable",function(e){t.nextTick(p,e)}.bind(null,a)),a}}).call(this,ue)}),a=e(function(e,t){"use strict";var n=Se.codes.ERR_STREAM_PREMATURE_CLOSE;function r(){}e.exports=function e(t,i,s){if("function"==typeof i)return e(t,null,i);i||(i={}),s=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(s||r);var o=i.readable||!1!==i.readable&&t.readable,a=i.writable||!1!==i.writable&&t.writable,h=function(){t.writable||u()},c=t._writableState&&t._writableState.finished,u=function(){a=!1,c=!0,o||s.call(t)},d=t._readableState&&t._readableState.endEmitted,l=function(){o=!1,d=!0,a||s.call(t)},f=function(e){s.call(t,e)},p=function(){var e;return o&&!d?(t._readableState&&t._readableState.ended||(e=new n),s.call(t,e)):a&&!c?(t._writableState&&t._writableState.ended||(e=new n),s.call(t,e)):void 0},g=function(){t.req.on("finish",u)};return function(e){return e.setHeader&&"function"==typeof e.abort}(t)?(t.on("complete",u),t.on("abort",p),t.req?g():t.on("request",g)):a&&!t._writableState&&(t.on("end",h),t.on("close",h)),t.on("end",l),t.on("finish",u),!1!==i.error&&t.on("error",f),t.on("close",p),function(){t.removeListener("complete",u),t.removeListener("abort",p),t.removeListener("request",g),t.req&&t.req.removeListener("finish",u),t.removeListener("end",h),t.removeListener("close",h),t.removeListener("finish",u),t.removeListener("end",l),t.removeListener("error",f),t.removeListener("close",p)}}}),h=e(function(e,t){"use strict";var n=Ue.Buffer,r=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function i(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===r||!r(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=a,this.end=h,t=4;break;case"utf8":this.fillLast=o,t=4;break;case"base64":this.text=c,this.end=u,t=3;break;default:return this.write=d,void(this.end=l)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function o(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"\ufffd";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"\ufffd";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"\ufffd"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function a(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function h(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function c(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function u(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function l(e){return e&&e.length?this.write(e):""}t.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},i.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\ufffd":t},i.prototype.text=function(e,t){var n=function(e,t,n){var r=t.length-1;if(r<n)return 0;var i=s(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||-2===i?0:(i=s(t[r]))>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||-2===i?0:(i=s(t[r]))>=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}}),c=e(function(e,t){(function(t){"use strict";var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=c;var r=s({}),i=u({});Be(c,r);for(var o=n(i.prototype),a=0;a<o.length;a++){var h=o[a];c.prototype[h]||(c.prototype[h]=i.prototype[h])}function c(e){if(!(this instanceof c))return new c(e);r.call(this,e),i.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||t.nextTick(l,this)}function l(e){e.end()}Object.defineProperty(c.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(c.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this,ue)}),u=e(function(e,t){(function(t,n){"use strict";function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(void 0),r=r.next}t.corkedRequestsFree.next=e}(t,e)}}var i;e.exports=k,k.WritableState=E;var s,o={deprecate:Le},a=d({}).Buffer,h=n.Uint8Array||function(){},u=Ae.getHighWaterMark,l=Se.codes,f=l.ERR_INVALID_ARG_TYPE,p=l.ERR_METHOD_NOT_IMPLEMENTED,g=l.ERR_MULTIPLE_CALLBACK,m=l.ERR_STREAM_CANNOT_PIPE,_=l.ERR_STREAM_DESTROYED,y=l.ERR_STREAM_NULL_VALUES,b=l.ERR_STREAM_WRITE_AFTER_END,w=l.ERR_UNKNOWN_ENCODING;function v(){}function E(e,n,s){i=i||c({}),e=e||{},"boolean"!=typeof s&&(s=n instanceof i),this.objectMode=!!e.objectMode,s&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=u(this,e,"writableHighWaterMark",s),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===e.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,n){var r=e._writableState,i=r.sync,s=r.writecb;if("function"!=typeof s)throw new g;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),n)!function(e,n,r,i,s){--n.pendingcb,r?(t.nextTick(s,i),t.nextTick(A,e,n),e._writableState.errorEmitted=!0,e.emit("error",i)):(s(i),e._writableState.errorEmitted=!0,e.emit("error",i),A(e,n))}(e,r,i,n,s);else{var o=T(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||x(e,r),i?t.nextTick(C,e,r,o,s):C(e,r,o,s)}}(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==e.emitClose,this.bufferedRequestCount=0,this.corkedRequestsFree=new r(this)}function k(e){var t=this instanceof(i=i||c({}));if(!t&&!s.call(k,this))return new k(e);this._writableState=new E(e,this,t),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),te.call(this)}function S(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new _("write")):n?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=!1}function C(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),A(e,t)}function x(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var i=t.bufferedRequestCount,s=new Array(i),o=t.corkedRequestsFree;o.entry=n;for(var a=0,h=!0;n;)s[a]=n,n.isBuf||(h=!1),n=n.next,a+=1;s.allBuffers=h,S(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new r(t),t.bufferedRequestCount=0}else{for(;n;){var c=n.chunk,u=n.encoding,d=n.callback;if(S(e,t,!1,t.objectMode?1:c.length,c,u,d),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function T(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function I(e,t){e._final(function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),A(e,t)})}function A(e,n){var r=T(n);return r&&(function(e,n){n.prefinished||n.finalCalled||("function"!=typeof e._final||n.destroyed?(n.prefinished=!0,e.emit("prefinish")):(n.pendingcb++,n.finalCalled=!0,t.nextTick(I,e,n)))}(e,n),0===n.pendingcb&&(n.finished=!0,e.emit("finish"))),r}Be(k,te),E.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(E.prototype,"buffer",{get:o.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(s=Function.prototype[Symbol.hasInstance],Object.defineProperty(k,Symbol.hasInstance,{value:function(e){return!!s.call(this,e)||this===k&&e&&e._writableState instanceof E}})):s=function(e){return e instanceof this},k.prototype.pipe=function(){this.emit("error",new m)},k.prototype.write=function(e,n,r){var i,s=this._writableState,o=!1,c=!s.objectMode&&(i=e,a.isBuffer(i)||i instanceof h);return c&&!a.isBuffer(e)&&(e=function(e){return a.from(e)}(e)),"function"==typeof n&&(r=n,n=null),c?n="buffer":n||(n=s.defaultEncoding),"function"!=typeof r&&(r=v),s.ending?function(e,n){var r=new b;e.emit("error",r),t.nextTick(n,r)}(this,r):(c||function(e,n,r,i){var s;return null===r?s=new y:"string"==typeof r||n.objectMode||(s=new f("chunk",["string","Buffer"],r)),!s||(e.emit("error",s),t.nextTick(i,s),!1)}(this,s,e,r))&&(s.pendingcb++,o=function(e,t,n,r,i,s){if(!n){var o=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=a.from(t,n)),t}(t,r,i);r!==o&&(n=!0,i="buffer",r=o)}var h=t.objectMode?1:r.length;t.length+=h;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var u=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:s,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else S(e,t,!1,h,r,i,s);return c}(this,s,c,e,n,r)),o},k.prototype.cork=function(){this._writableState.corked++},k.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||x(this,e))},k.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new w(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(k.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(k.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),k.prototype._write=function(e,t,n){n(new p("_write()"))},k.prototype._writev=null,k.prototype.end=function(e,n,r){var i=this._writableState;return"function"==typeof e?(r=e,e=null,n=null):"function"==typeof n&&(r=n,n=null),null!=e&&this.write(e,n),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,n,r){n.ending=!0,A(e,n),r&&(n.finished?t.nextTick(r):e.once("finish",r)),n.ended=!0,e.writable=!1}(this,i,r),this},Object.defineProperty(k.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(k.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),k.prototype.destroy=ke.destroy,k.prototype._undestroy=ke.undestroy,k.prototype._destroy=function(e,t){t(e)}}).call(this,ue,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})}),d=e(function(e,t){(function(e){"use strict";t.Buffer=e,t.SlowBuffer=function(t){return+t!=t&&(t=0),e.alloc(+t)},t.INSPECT_MAX_BYTES=50;var n=2147483647;function r(t){if(t>n)throw new RangeError('The value "'+t+'" is invalid for option "size"');var r=new Uint8Array(t);return r.__proto__=e.prototype,r}function e(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return i(e,t,n)}function i(t,n,i){if("string"==typeof t)return function(t,n){if("string"==typeof n&&""!==n||(n="utf8"),!e.isEncoding(n))throw new TypeError("Unknown encoding: "+n);var i=0|c(t,n),s=r(i),o=s.write(t,n);return o!==i&&(s=s.slice(0,o)),s}(t,n);if(ArrayBuffer.isView(t))return a(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(N(t,ArrayBuffer)||t&&N(t.buffer,ArrayBuffer))return function(t,n,r){if(n<0||t.byteLength<n)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<n+(r||0))throw new RangeError('"length" is outside of buffer bounds');var i;return(i=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r)).__proto__=e.prototype,i}(t,n,i);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');var s=t.valueOf&&t.valueOf();if(null!=s&&s!==t)return e.from(s,n,i);var o=function(t){if(e.isBuffer(t)){var n=0|h(t.length),i=r(n);return 0===i.length?i:(t.copy(i,0,0,n),i)}return void 0!==t.length?"number"!=typeof t.length||H(t.length)?r(0):a(t):"Buffer"===t.type&&Array.isArray(t.data)?a(t.data):void 0}(t);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return e.from(t[Symbol.toPrimitive]("string"),n,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function s(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function o(e){return s(e),r(e<0?0:0|h(e))}function a(e){for(var t=e.length<0?0:0|h(e.length),n=r(t),i=0;i<t;i+=1)n[i]=255&e[i];return n}function h(e){if(e>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function c(t,n){if(e.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||N(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var s=!1;;)switch(n){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return U(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return O(t).length;default:if(s)return i?-1:U(t).length;n=(""+n).toLowerCase(),s=!0}}function u(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function d(t,n,r,i,s){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=s?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(s)return-1;r=t.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof n&&(n=e.from(n,i)),e.isBuffer(n))return 0===n.length?-1:l(t,n,r,i,s);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,n,r):Uint8Array.prototype.lastIndexOf.call(t,n,r):l(t,[n],r,i,s);throw new TypeError("val must be string, number or Buffer")}function l(e,t,n,r,i){var s,o=1,a=e.length,h=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,h/=2,n/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var u=-1;for(s=n;s<a;s++)if(c(e,s)===c(t,-1===u?0:s-u)){if(-1===u&&(u=s),s-u+1===h)return u*o}else-1!==u&&(s-=s-u),u=-1}else for(n+h>a&&(n=a-h),s=n;s>=0;s--){for(var d=!0,l=0;l<h;l++)if(c(e,s+l)!==c(t,l)){d=!1;break}if(d)return s}return-1}function f(e,t,n,r){n=Number(n)||0;var i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;var s=t.length;r>s/2&&(r=s/2);for(var o=0;o<r;++o){var a=parseInt(t.substr(2*o,2),16);if(H(a))return o;e[n+o]=a}return o}function p(e,t,n,r){return M(U(t,e.length-n),e,n,r)}function g(e,t,n,r){return M(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function m(e,t,n,r){return g(e,t,n,r)}function _(e,t,n,r){return M(O(t),e,n,r)}function y(e,t,n,r){return M(function(e,t){for(var n,r,i,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function b(e,t,n){return 0===t&&n===e.length?T.fromByteArray(e):T.fromByteArray(e.slice(t,n))}function w(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i<n;){var s,o,a,h,c=e[i],u=null,d=c>239?4:c>223?3:c>191?2:1;if(i+d<=n)switch(d){case 1:c<128&&(u=c);break;case 2:128==(192&(s=e[i+1]))&&(h=(31&c)<<6|63&s)>127&&(u=h);break;case 3:s=e[i+1],o=e[i+2],128==(192&s)&&128==(192&o)&&(h=(15&c)<<12|(63&s)<<6|63&o)>2047&&(h<55296||h>57343)&&(u=h);break;case 4:s=e[i+1],o=e[i+2],a=e[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(h=(15&c)<<18|(63&s)<<12|(63&o)<<6|63&a)>65535&&h<1114112&&(u=h)}null===u?(u=65533,d=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),i+=d}return function(e){var t=e.length;if(t<=v)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=v));return n}(r)}t.kMaxLength=n,e.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),e.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(e.prototype,"parent",{enumerable:!0,get:function(){if(e.isBuffer(this))return this.buffer}}),Object.defineProperty(e.prototype,"offset",{enumerable:!0,get:function(){if(e.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&e[Symbol.species]===e&&Object.defineProperty(e,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),e.poolSize=8192,e.from=function(e,t,n){return i(e,t,n)},e.prototype.__proto__=Uint8Array.prototype,e.__proto__=Uint8Array,e.alloc=function(e,t,n){return function(e,t,n){return s(e),e<=0?r(e):void 0!==t?"string"==typeof n?r(e).fill(t,n):r(e).fill(t):r(e)}(e,t,n)},e.allocUnsafe=function(e){return o(e)},e.allocUnsafeSlow=function(e){return o(e)},e.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==e.prototype},e.compare=function(t,n){if(N(t,Uint8Array)&&(t=e.from(t,t.offset,t.byteLength)),N(n,Uint8Array)&&(n=e.from(n,n.offset,n.byteLength)),!e.isBuffer(t)||!e.isBuffer(n))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===n)return 0;for(var r=t.length,i=n.length,s=0,o=Math.min(r,i);s<o;++s)if(t[s]!==n[s]){r=t[s],i=n[s];break}return r<i?-1:i<r?1:0},e.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},e.concat=function(t,n){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return e.alloc(0);var r;if(void 0===n)for(n=0,r=0;r<t.length;++r)n+=t[r].length;var i=e.allocUnsafe(n),s=0;for(r=0;r<t.length;++r){var o=t[r];if(N(o,Uint8Array)&&(o=e.from(o)),!e.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,s),s+=o.length}return i},e.byteLength=c,e.prototype._isBuffer=!0,e.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)u(this,t,t+1);return this},e.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)u(this,t,t+3),u(this,t+1,t+2);return this},e.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)u(this,t,t+7),u(this,t+1,t+6),u(this,t+2,t+5),u(this,t+3,t+4);return this},e.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?w(this,0,e):function(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return S(this,t,n);case"utf8":case"utf-8":return w(this,t,n);case"ascii":return E(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return b(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}.apply(this,arguments)},e.prototype.toLocaleString=e.prototype.toString,e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===e.compare(this,t)},e.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},e.prototype.compare=function(t,n,r,i,s){if(N(t,Uint8Array)&&(t=e.from(t,t.offset,t.byteLength)),!e.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===n&&(n=0),void 0===r&&(r=t?t.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),n<0||r>t.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&n>=r)return 0;if(i>=s)return-1;if(n>=r)return 1;if(this===t)return 0;for(var o=(s>>>=0)-(i>>>=0),a=(r>>>=0)-(n>>>=0),h=Math.min(o,a),c=this.slice(i,s),u=t.slice(n,r),d=0;d<h;++d)if(c[d]!==u[d]){o=c[d],a=u[d];break}return o<a?-1:a<o?1:0},e.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},e.prototype.indexOf=function(e,t,n){return d(this,e,t,n,!0)},e.prototype.lastIndexOf=function(e,t,n){return d(this,e,t,n,!1)},e.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return f(this,e,t,n);case"utf8":case"utf-8":return p(this,e,t,n);case"ascii":return g(this,e,t,n);case"latin1":case"binary":return m(this,e,t,n);case"base64":return _(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var v=4096;function E(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(127&e[i]);return r}function k(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function S(e,t,n){var r,i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);for(var s="",o=t;o<n;++o)s+=(r=e[o])<16?"0"+r.toString(16):r.toString(16);return s}function C(e,t,n){for(var r=e.slice(t,n),i="",s=0;s<r.length;s+=2)i+=String.fromCharCode(r[s]+256*r[s+1]);return i}function x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function I(t,n,r,i,s,o){if(!e.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>s||n<o)throw new RangeError('"value" argument is out of bounds');if(r+i>t.length)throw new RangeError("Index out of range")}function A(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,n,r,i){return t=+t,n>>>=0,i||A(e,0,n,4),P.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,i){return t=+t,n>>>=0,i||A(e,0,n,8),P.write(e,t,n,r,52,8),n+8}e.prototype.slice=function(t,n){var r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(n=void 0===n?r:~~n)<0?(n+=r)<0&&(n=0):n>r&&(n=r),n<t&&(n=t);var i=this.subarray(t,n);return i.__proto__=e.prototype,i},e.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r},e.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},e.prototype.readUInt8=function(e,t){return e>>>=0,t||x(e,1,this.length),this[e]},e.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},e.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},e.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},e.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},e.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r>=(i*=128)&&(r-=Math.pow(2,8*t)),r},e.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);for(var r=t,i=1,s=this[e+--r];r>0&&(i*=256);)s+=this[e+--r]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},e.prototype.readInt8=function(e,t){return e>>>=0,t||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},e.prototype.readInt16LE=function(e,t){e>>>=0,t||x(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt16BE=function(e,t){e>>>=0,t||x(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},e.prototype.readInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},e.prototype.readFloatLE=function(e,t){return e>>>=0,t||x(e,4,this.length),P.read(this,e,!0,23,4)},e.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),P.read(this,e,!1,23,4)},e.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),P.read(this,e,!0,52,8)},e.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(e,8,this.length),P.read(this,e,!1,52,8)},e.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||I(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,s=0;for(this[t]=255&e;++s<n&&(i*=256);)this[t+s]=e/i&255;return t+n},e.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||I(this,e,t,n,Math.pow(2,8*n)-1,0);var i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+n},e.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,1,255,0),this[t]=255&e,t+1},e.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},e.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},e.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},e.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},e.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);I(this,e,t,n,i-1,-i)}var s=0,o=1,a=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===a&&0!==this[t+s-1]&&(a=1),this[t+s]=(e/o>>0)-a&255;return t+n},e.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);I(this,e,t,n,i-1,-i)}var s=n-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o>>0)-a&255;return t+n},e.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},e.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},e.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},e.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},e.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},e.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},e.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},e.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},e.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},e.prototype.copy=function(t,n,r,i){if(!e.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),n>=t.length&&(n=t.length),n||(n=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===t.length||0===this.length)return 0;if(n<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-n<i-r&&(i=t.length-n+r);var s=i-r;if(this===t&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(n,r,i);else if(this===t&&r<n&&n<i)for(var o=s-1;o>=0;--o)t[o+n]=this[o+r];else Uint8Array.prototype.set.call(t,this.subarray(r,i),n);return s},e.prototype.fill=function(t,n,r,i){if("string"==typeof t){if("string"==typeof n?(i=n,n=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!e.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var s=t.charCodeAt(0);("utf8"===i&&s<128||"latin1"===i)&&(t=s)}}else"number"==typeof t&&(t&=255);if(n<0||this.length<n||this.length<r)throw new RangeError("Out of range index");if(r<=n)return this;var o;if(n>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=n;o<r;++o)this[o]=t;else{var a=e.isBuffer(t)?t:e.from(t,i),h=a.length;if(0===h)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(o=0;o<r-n;++o)this[o+n]=a[o%h]}return this};var L=/[^+\/0-9A-Za-z-_]/g;function U(e,t){var n;t=t||1/0;for(var r=e.length,i=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function O(e){return T.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(L,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function M(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function N(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function H(e){return e!=e}}).call(this,d({}).Buffer)}),l={},f=Object.create||function(e){var t=function(){};return t.prototype=e,new t},p=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return n},g=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function m(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=f(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}l=m,m.EventEmitter=m,m.prototype._events=void 0,m.prototype._maxListeners=void 0;var _,y=10;try{var b={};Object.defineProperty&&Object.defineProperty(b,"x",{value:0}),_=0===b.x}catch(_i){_=!1}function w(e){return void 0===e._maxListeners?m.defaultMaxListeners:e._maxListeners}function v(e,t,n,r){var i,s,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]):(s=e._events=f(null),e._eventsCount=0),o){if("function"==typeof o?o=s[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),!o.warned&&(i=w(e))&&i>0&&o.length>i){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else o=s[t]=n,++e._eventsCount;return e}function E(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function k(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=g.call(E,r);return i.listener=n,r.wrapFn=i,i}function S(e,t,n){var r=e._events;if(!r)return[];var i=r[t];return i?"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):x(i,i.length):[]}function C(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function x(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}_?Object.defineProperty(m,"defaultMaxListeners",{enumerable:!0,get:function(){return y},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');y=e}}):m.defaultMaxListeners=y,m.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},m.prototype.getMaxListeners=function(){return w(this)},m.prototype.emit=function(e){var t,n,r,i,s,o,a="error"===e;if(o=this._events)a=a&&null==o.error;else if(!a)return!1;if(a){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var h=new Error('Unhandled "error" event. ('+t+")");throw h.context=t,h}if(!(n=o[e]))return!1;var c="function"==typeof n;switch(r=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var r=e.length,i=x(e,r),s=0;s<r;++s)i[s].call(n)}(n,c,this);break;case 2:!function(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,s=x(e,i),o=0;o<i;++o)s[o].call(n,r)}(n,c,this,arguments[1]);break;case 3:!function(e,t,n,r,i){if(t)e.call(n,r,i);else for(var s=e.length,o=x(e,s),a=0;a<s;++a)o[a].call(n,r,i)}(n,c,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,r,i,s){if(t)e.call(n,r,i,s);else for(var o=e.length,a=x(e,o),h=0;h<o;++h)a[h].call(n,r,i,s)}(n,c,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),s=1;s<r;s++)i[s-1]=arguments[s];!function(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,s=x(e,i),o=0;o<i;++o)s[o].apply(n,r)}(n,c,this,i)}return!0},m.prototype.addListener=function(e,t){return v(this,e,t,!1)},m.prototype.on=m.prototype.addListener,m.prototype.prependListener=function(e,t){return v(this,e,t,!0)},m.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,k(this,e,t)),this},m.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,k(this,e,t)),this},m.prototype.removeListener=function(e,t){var n,r,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=f(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():function(e,t){for(var n=i,r=n+1,s=e.length;r<s;n+=1,r+=1)e[n]=e[r];e.pop()}(n),1===n.length&&(r[e]=n[0]),r.removeListener&&this.emit("removeListener",e,o||t)}return this},m.prototype.removeAllListeners=function(e){var t,n,r;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=f(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=f(null):delete n[e]),this;if(0===arguments.length){var i,s=p(n);for(r=0;r<s.length;++r)"removeListener"!==(i=s[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=f(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},m.prototype.listeners=function(e){return S(this,e,!0)},m.prototype.rawListeners=function(e){return S(this,e,!1)},m.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):C.call(e,t)},m.prototype.listenerCount=C,m.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};for(var T={toByteArray:function(e){var t,n,r=O(e),i=r[0],s=r[1],o=new R(function(e,t,n){return 3*(t+n)/4-n}(0,i,s)),a=0,h=s>0?i-4:i;for(n=0;n<h;n+=4)t=A[e.charCodeAt(n)]<<18|A[e.charCodeAt(n+1)]<<12|A[e.charCodeAt(n+2)]<<6|A[e.charCodeAt(n+3)],o[a++]=t>>16&255,o[a++]=t>>8&255,o[a++]=255&t;return 2===s&&(t=A[e.charCodeAt(n)]<<2|A[e.charCodeAt(n+1)]>>4,o[a++]=255&t),1===s&&(t=A[e.charCodeAt(n)]<<10|A[e.charCodeAt(n+1)]<<4|A[e.charCodeAt(n+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t),o},fromByteArray:function(e){for(var t,n=e.length,r=n%3,i=[],s=0,o=n-r;s<o;s+=16383)i.push(M(e,s,s+16383>o?o:s+16383));return 1===r?(t=e[n-1],i.push(I[t>>2]+I[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(I[t>>10]+I[t>>4&63]+I[t<<2&63]+"=")),i.join("")}},I=[],A=[],R="undefined"!=typeof Uint8Array?Uint8Array:Array,B="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",L=0,U=B.length;L<U;++L)I[L]=B[L],A[B.charCodeAt(L)]=L;function O(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function M(e,t,n){for(var r,i,s=[],o=t;o<n;o+=3)r=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),s.push(I[(i=r)>>18&63]+I[i>>12&63]+I[i>>6&63]+I[63&i]);return s.join("")}A["-".charCodeAt(0)]=62,A["_".charCodeAt(0)]=63;var P={read:function(e,t,n,r,i){var s,o,a=8*i-r-1,h=(1<<a)-1,c=h>>1,u=-7,d=n?i-1:0,l=n?-1:1,f=e[t+d];for(d+=l,s=f&(1<<-u)-1,f>>=-u,u+=a;u>0;s=256*s+e[t+d],d+=l,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=r;u>0;o=256*o+e[t+d],d+=l,u-=8);if(0===s)s=1-c;else{if(s===h)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),s-=c}return(f?-1:1)*o*Math.pow(2,s-r)},write:function(e,t,n,r,i,s){var o,a,h,c=8*s-i-1,u=(1<<c)-1,d=u>>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(h=Math.pow(2,-o))<1&&(o--,h*=2),(t+=o+d>=1?l/h:l*Math.pow(2,1-d))*h>=2&&(o++,h/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*h-1)*Math.pow(2,i),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=255&a,f+=p,a/=256,i-=8);for(o=o<<i|a,c+=i;c>0;e[n+f]=255&o,f+=p,o/=256,c-=8);e[n+f-p]|=128*g}},N={};(function(e){N=function(t,n){var r=[];t.on("data",function(e){r.push(e)}),t.once("end",function(){n&&n(null,e.concat(r)),n=null}),t.once("error",function(e){n&&n(e),n=null})}}).call(this,d({}).Buffer);var H={},j=d({}),D=j.Buffer;function q(e,t){for(var n in e)t[n]=e[n]}function F(e,t,n){return D(e,t,n)}D.from&&D.alloc&&D.allocUnsafe&&D.allocUnsafeSlow?H=j:(q(j,H),H.Buffer=F),F.prototype=Object.create(D.prototype),q(D,F),F.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return D(e,t,n)},F.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=D(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},F.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return D(e)},F.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return j.SlowBuffer(e)};var W,z=H.Buffer;function $(e,t,n){var r=[],i=null;return $._encode(r,e),i=z.concat(r),$.bytes=i.length,z.isBuffer(t)?(i.copy(t,n),t):i}$.bytes=-1,$._floatConversionDetected=!1,$.getType=function(e){return z.isBuffer(e)?"buffer":Array.isArray(e)?"array":ArrayBuffer.isView(e)?"arraybufferview":e instanceof Number?"number":e instanceof Boolean?"boolean":e instanceof ArrayBuffer?"arraybuffer":typeof e},$._encode=function(e,t){if(null!=t)switch($.getType(t)){case"buffer":$.buffer(e,t);break;case"object":$.dict(e,t);break;case"array":$.list(e,t);break;case"string":$.string(e,t);break;case"number":case"boolean":$.number(e,t);break;case"arraybufferview":$.buffer(e,z.from(t.buffer,t.byteOffset,t.byteLength));break;case"arraybuffer":$.buffer(e,z.from(t))}};var V=z.from("e"),G=z.from("d"),K=z.from("l");$.buffer=function(e,t){e.push(z.from(t.length+":"),t)},$.string=function(e,t){e.push(z.from(z.byteLength(t)+":"+t))},$.number=function(e,t){var n=2147483648*(t/2147483648<<0)+(t%2147483648<<0);e.push(z.from("i"+n+"e")),n===t||$._floatConversionDetected||($._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+t+'":','Bencoding only defines support for integers, value was converted to "'+n+'"'),console.trace())},$.dict=function(e,t){e.push(G);for(var n,r=0,i=Object.keys(t).sort(),s=i.length;r<s;r++)null!=t[n=i[r]]&&($.string(e,n),$._encode(e,t[n]));e.push(V)},$.list=function(e,t){var n=0,r=t.length;for(e.push(K);n<r;n++)null!=t[n]&&$._encode(e,t[n]);e.push(V)},W=$;var Y,J=H.Buffer;function X(e,t,n){for(var r=0,i=1,s=t;s<n;s++){var o=e[s];if(o<58&&o>=48)r=10*r+(o-48);else if(s!==t||43!==o){if(s!==t||45!==o){if(46===o)break;throw new Error("not a number: buffer["+s+"] = "+o)}i=-1}}return r*i}function Z(e,t,n,r){return null==e||0===e.length?null:("number"!=typeof t&&null==r&&(r=t,t=void 0),"number"!=typeof n&&null==r&&(r=n,n=void 0),Z.position=0,Z.encoding=r||null,Z.data=J.isBuffer(e)?e.slice(t,n):J.from(e),Z.bytes=Z.data.length,Z.next())}Z.bytes=0,Z.position=0,Z.data=null,Z.encoding=null,Z.next=function(){switch(Z.data[Z.position]){case 100:return Z.dictionary();case 108:return Z.list();case 105:return Z.integer();default:return Z.buffer()}},Z.find=function(e){for(var t=Z.position,n=Z.data.length,r=Z.data;t<n;){if(r[t]===e)return t;t++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(e)+'" [0x'+e.toString(16)+"]")},Z.dictionary=function(){Z.position++;for(var e={};101!==Z.data[Z.position];)e[Z.buffer()]=Z.next();return Z.position++,e},Z.list=function(){Z.position++;for(var e=[];101!==Z.data[Z.position];)e.push(Z.next());return Z.position++,e},Z.integer=function(){var e=Z.find(101),t=X(Z.data,Z.position+1,e);return Z.position+=e+1-Z.position,t},Z.buffer=function(){var e=Z.find(58),t=X(Z.data,Z.position,e),n=++e+t;return Z.position=n,Z.encoding?Z.data.toString(Z.encoding,e,n):Z.data.slice(e,n)},Y=Z;var Q={},ee=Q;ee.encode=W,ee.decode=Y,ee.byteLength=ee.encodingLength=function(e){return ee.encode(e).length};var te=l.EventEmitter,ne={};function re(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var ie,se,oe=d({}).Buffer,ae=ne.inspect,he=ae&&ae.custom||"inspect",ce=function(){function e(){this.head=null,this.tail=null,this.length=0}var t=e.prototype;return t.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},t.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},t.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},t.clear=function(){this.head=this.tail=null,this.length=0},t.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},t.concat=function(e){if(0===this.length)return oe.alloc(0);for(var t,n,r,i=oe.allocUnsafe(e>>>0),s=this.head,o=0;s;)t=s.data,n=i,r=o,oe.prototype.copy.call(t,n,r),o+=s.data.length,s=s.next;return i},t.consume=function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n},t.first=function(){return this.head.data},t._getString=function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,s=e>i.length?i.length:e;if(s===i.length?r+=i:r+=i.slice(0,e),0==(e-=s)){s===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r},t._getBuffer=function(e){var t=oe.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0==(e-=s)){s===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t},t[he]=function(e,t){return ae(this,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){re(e,t,n[t])})}return e}({},t,{depth:0,customInspect:!1}))},e}(),ue={},de=ue={};function le(){throw new Error("setTimeout has not been defined")}function fe(){throw new Error("clearTimeout has not been defined")}function pe(e){if(ie===setTimeout)return setTimeout(e,0);if((ie===le||!ie)&&setTimeout)return ie=setTimeout,setTimeout(e,0);try{return ie(e,0)}catch(t){try{return ie.call(null,e,0)}catch(t){return ie.call(this,e,0)}}}!function(){try{ie="function"==typeof setTimeout?setTimeout:le}catch(e){ie=le}try{se="function"==typeof clearTimeout?clearTimeout:fe}catch(e){se=fe}}();var ge,me=[],_e=!1,ye=-1;function be(){_e&&ge&&(_e=!1,ge.length?me=ge.concat(me):ye=-1,me.length&&we())}function we(){if(!_e){var e=pe(be);_e=!0;for(var t=me.length;t;){for(ge=me,me=[];++ye<t;)ge&&ge[ye].run();ye=-1,t=me.length}ge=null,_e=!1,function(e){if(se===clearTimeout)return clearTimeout(e);if((se===fe||!se)&&clearTimeout)return se=clearTimeout,clearTimeout(e);try{se(e)}catch(t){try{return se.call(null,e)}catch(t){return se.call(this,e)}}}(e)}}function ve(e,t){this.fun=e,this.array=t}function Ee(){}de.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];me.push(new ve(e,t)),1!==me.length||_e||pe(we)},ve.prototype.run=function(){this.fun.apply(null,this.array)},de.title="browser",de.browser=!0,de.env={},de.argv=[],de.version="",de.versions={},de.on=Ee,de.addListener=Ee,de.once=Ee,de.off=Ee,de.removeListener=Ee,de.removeAllListeners=Ee,de.emit=Ee,de.prependListener=Ee,de.prependOnceListener=Ee,de.listeners=function(e){return[]},de.binding=function(e){throw new Error("process.binding is not supported")},de.cwd=function(){return"/"},de.chdir=function(e){throw new Error("process.chdir is not supported")},de.umask=function(){return 0};var ke={};(function(e){"use strict";function t(e,t){r(e,t),n(e)}function n(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}ke={destroy:function(i,s){var o=this,a=this._readableState&&this._readableState.destroyed,h=this._writableState&&this._writableState.destroyed;return a||h?(s?s(i):!i||this._writableState&&this._writableState.errorEmitted||e.nextTick(r,this,i),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(i||null,function(r){!s&&r?(e.nextTick(t,o,r),o._writableState&&(o._writableState.errorEmitted=!0)):s?(e.nextTick(n,o),s(r)):e.nextTick(n,o)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}}).call(this,ue);var Se={},Ce={};function xe(e,t,n){n||(n=Error);var r=function(e){var n,r;function i(n,r,i){return e.call(this,function(e,n,r){return"string"==typeof t?t:t(e,n,r)}(n,r,i))||this}return r=e,(n=i).prototype=Object.create(r.prototype),n.prototype.constructor=n,n.__proto__=r,i}(n);r.prototype.name=n.name,r.prototype.code=e,Ce[e]=r}function Te(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return String(e)}),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}xe("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError),xe("ERR_INVALID_ARG_TYPE",function(e,t,n){var r,i,s,o;if("string"==typeof t&&("not ","not "===t.substr(0,"not ".length))?(r="must not be",t=t.replace(/^not /,"")):r="must be",s=e,(void 0===o||o>s.length)&&(o=s.length)," argument"===s.substring(o-" argument".length,o))i="The ".concat(e," ").concat(r," ").concat(Te(t,"type"));else{var a=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+".".length>e.length)&&-1!==e.indexOf(".",n)}(e)?"property":"argument";i='The "'.concat(e,'" ').concat(a," ").concat(r," ").concat(Te(t,"type"))}return i+". Received type ".concat(typeof n)},TypeError),xe("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),xe("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),xe("ERR_STREAM_PREMATURE_CLOSE","Premature close"),xe("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),xe("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),xe("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),xe("ERR_STREAM_WRITE_AFTER_END","write after end"),xe("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),xe("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),xe("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Se.codes=Ce;var Ie=Se.codes.ERR_INVALID_OPT_VALUE,Ae={getHighWaterMark:function(e,t,n,r){var i=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(t,r,n);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Ie(r?n:"highWaterMark",i);return Math.floor(i)}return e.objectMode?16:16384}},Re={};(function(e){"use strict";var t=new Set;Re.emitExperimentalWarning=e.emitWarning?function(n){if(!t.has(n)){var r=n+" is an experimental feature. This feature could change at any time";t.add(n),e.emitWarning(r,"ExperimentalWarning")}}:function(){}}).call(this,ue);var Be={};Be="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}};var Le={};(function(e){function t(t){try{if(!e.localStorage)return!1}catch(r){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}Le=function(e,n){if(t("noDeprecation"))return e;var r=!1;return function(){if(!r){if(t("throwDeprecation"))throw new Error(n);t("traceDeprecation")?console.trace(n):console.warn(n),r=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Ue={},Oe=d({}),Me=Oe.Buffer;function Pe(e,t){for(var n in e)t[n]=e[n]}function Ne(e,t,n){return Me(e,t,n)}Me.from&&Me.alloc&&Me.allocUnsafe&&Me.allocUnsafeSlow?Ue=Oe:(Pe(Oe,Ue),Ue.Buffer=Ne),Pe(Me,Ne),Ne.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return Me(e,t,n)},Ne.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=Me(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},Ne.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return Me(e)},Ne.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return Oe.SlowBuffer(e)};var He=Ve,je=Se.codes,De=je.ERR_METHOD_NOT_IMPLEMENTED,qe=je.ERR_MULTIPLE_CALLBACK,Fe=je.ERR_TRANSFORM_ALREADY_TRANSFORMING,We=je.ERR_TRANSFORM_WITH_LENGTH_0,ze=c({});function $e(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new qe);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function Ve(e){if(!(this instanceof Ve))return new Ve(e);ze.call(this,e),this._transformState={afterTransform:$e.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",Ge)}function Ge(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?Ke(this,null,null):this._flush(function(t,n){Ke(e,t,n)})}function Ke(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new We;if(e._transformState.transforming)throw new Fe;return e.push(null)}Be(Ve,ze),Ve.prototype.push=function(e,t){return this._transformState.needTransform=!1,ze.prototype.push.call(this,e,t)},Ve.prototype._transform=function(e,t,n){n(new De("_transform()"))},Ve.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},Ve.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},Ve.prototype._destroy=function(e,t){ze.prototype._destroy.call(this,e,function(e){t(e)})};var Ye,Je=Xe;function Xe(e){if(!(this instanceof Xe))return new Xe(e);He.call(this,e)}Be(Xe,He),Xe.prototype._transform=function(e,t,n){n(null,e)};var Ze=Se.codes,Qe=Ze.ERR_MISSING_ARGS,et=Ze.ERR_STREAM_DESTROYED;function tt(e){if(e)throw e}function nt(e){e()}function rt(e,t){return e.pipe(t)}var it={};(it=it=s({})).Stream=it,it.Readable=it,it.Writable=u({}),it.Duplex=c({}),it.Transform=He,it.PassThrough=Je,it.finished=a({}),it.pipeline=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,i=function(e){return e.length?"function"!=typeof e[e.length-1]?tt:e.pop():tt}(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new Qe("streams");var s=t.map(function(e,n){var o=n<t.length-1;return function(e,t,n,r){r=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(r);var i=!1;e.on("close",function(){i=!0}),void 0===Ye&&(Ye=a({})),Ye(e,{readable:t,writable:n},function(e){if(e)return r(e);i=!0,r()});var s=!1;return function(t){if(!i&&!s)return s=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(e)?e.abort():"function"==typeof e.destroy?e.destroy():void r(t||new et("pipe"))}}(e,o,n>0,function(e){r||(r=e),e&&s.forEach(nt),o||(s.forEach(nt),i(r))})});return t.reduce(rt)};var st={};(function(e){const{Transform:t}=it;st=class extends t{constructor(e,t={}){super(t),"object"==typeof e&&(e=(t=e).size),this.size=e||512;const{nopad:n,zeroPadding:r=!0}=t;this._zeroPadding=!n&&!!r,this._buffered=[],this._bufferedBytes=0}_transform(t,n,r){for(this._bufferedBytes+=t.length,this._buffered.push(t);this._bufferedBytes>=this.size;){const t=e.concat(this._buffered);this._bufferedBytes-=this.size,this.push(t.slice(0,this.size)),this._buffered=[t.slice(this.size,t.length)]}r()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const t=e.alloc(this.size-this._bufferedBytes);this._buffered.push(t),this.push(e.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(e.concat(this._buffered)),this._buffered=null);this.push(null)}}}).call(this,d({}).Buffer);for(var ot=i({}),at=Math.pow(2,10),ht=13,ct=[];ht++<22;)ct.push(Math.pow(2,ht));var ut={};(function(e){function t(e,t){for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function n(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r<e.length;r++)t(e[r],r,e)&&n.push(e[r]);return n}ut.normalize=function(e){var i=ut.isAbsolute(e),s="/"===r(e,-1);return(e=t(n(e.split("/"),function(e){return!!e}),!i).join("/"))||i||(e="."),e&&s&&(e+="/"),(i?"/":"")+e},ut.isAbsolute=function(e){return"/"===e.charAt(0)},ut.join=function(){var e=Array.prototype.slice.call(arguments,0);return ut.normalize(n(e,function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},ut.sep="/",ut.dirname=function(e){if("string"!=typeof e&&(e+=""),0===e.length)return".";for(var t=e.charCodeAt(0),n=47===t,r=-1,i=!0,s=e.length-1;s>=1;--s)if(47===(t=e.charCodeAt(s))){if(!i){r=s;break}}else i=!1;return-1===r?n?"/":".":n&&1===r?"/":e.slice(0,r)},ut.basename=function(e,t){var n=function(e){"string"!=typeof e&&(e+="");var t,n=0,r=-1,i=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!i){n=t+1;break}}else-1===r&&(i=!1,r=t+1);return-1===r?"":e.slice(n,r)}(e);return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},ut.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,n=0,r=-1,i=!0,s=0,o=e.length-1;o>=0;--o){var a=e.charCodeAt(o);if(47!==a)-1===r&&(i=!1,r=o+1),46===a?-1===t?t=o:1!==s&&(s=1):-1!==t&&(s=-1);else if(!i){n=o+1;break}}return-1===t||-1===r||0===s||1===s&&t===r-1&&t===n+1?"":e.slice(t,r)};var r="b"==="ab".substr(-1)?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return t<0&&(t=e.length+t),e.substr(t,n)}}).call(this,ue);var dt;dt=pt,pt.strict=gt,pt.loose=mt;var lt=Object.prototype.toString,ft={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0};function pt(e){return gt(e)||mt(e)}function gt(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function mt(e){return ft[lt.call(e)]}var _t={};(function(e){var t=dt.strict;_t=function(n){if(t(n)){var r=e.from(n.buffer);return n.byteLength!==n.buffer.byteLength&&(r=r.slice(n.byteOffset,n.byteOffset+n.byteLength)),r}return e.from(n)}}).call(this,d({}).Buffer);const{Readable:yt}=it;var bt=class extends yt{constructor(e,t={}){super(t),this._offset=0,this._ready=!1,this._file=e,this._size=e.size,this._chunkSize=t.chunkSize||Math.max(this._size/1e3,204800);const n=new FileReader;n.onload=(()=>{this.push(_t(n.result))}),n.onerror=(()=>{this.emit("error",n.error)}),this.reader=n,this._generateHeaderBlocks(e,t,(e,t)=>{if(e)return this.emit("error",e);Array.isArray(t)&&t.forEach(e=>this.push(e)),this._ready=!0,this.emit("_ready")})}_generateHeaderBlocks(e,t,n){n(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const e=this._offset;let t=this._offset+this._chunkSize;if(t>this._size&&(t=this._size),e===this._size)return this.destroy(),void this.push(null);this.reader.readAsArrayBuffer(this._file.slice(e,t)),this._offset=t}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}},wt={},vt={};function Et(e){return wt.existsSync(e)&&wt.statSync(e).isFile()}(vt=function(e,t){if(!t)return Et(e);wt.stat(e,function(e,n){return e?t(e):t(null,n.isFile())})}).sync=Et;var kt={};kt.regex=new RegExp(["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"].join("|")),kt.is=(e=>kt.regex.test(e)),kt.not=(e=>!kt.is(e));var St={};function Ct(e){return Tt(e,{objectMode:!0,highWaterMark:16})}function xt(e){return Tt(e)}function Tt(e,t){if(!e||"function"==typeof e||e._readableState)return e;var n=new it.Readable(t).wrap(e);return e.destroy&&(n.destroy=e.destroy.bind(e)),n}class It extends it.Readable{constructor(e,t){super(t),this.destroyed=!1,this._drained=!1,this._forwarding=!1,this._current=null,this._toStreams2=t&&t.objectMode?Ct:xt,"function"==typeof e?this._queue=e:(this._queue=e.map(this._toStreams2),this._queue.forEach(e=>{"function"!=typeof e&&this._attachErrorListener(e)})),this._next()}_read(){this._drained=!0,this._forward()}_forward(){if(!this._forwarding&&this._drained&&this._current){var e;for(this._forwarding=!0;null!==(e=this._current.read())&&this._drained;)this._drained=this.push(e);this._forwarding=!1}}destroy(e){this.destroyed||(this.destroyed=!0,this._current&&this._current.destroy&&this._current.destroy(),"function"!=typeof this._queue&&this._queue.forEach(e=>{e.destroy&&e.destroy()}),e&&this.emit("error",e),this.emit("close"))}_next(){if(this._current=null,"function"==typeof this._queue)this._queue((e,t)=>{if(e)return this.destroy(e);t=this._toStreams2(t),this._attachErrorListener(t),this._gotNextStream(t)});else{var e=this._queue.shift();"function"==typeof e&&(e=this._toStreams2(e()),this._attachErrorListener(e)),this._gotNextStream(e)}}_gotNextStream(e){if(!e)return this.push(null),void this.destroy();this._current=e,this._forward();const t=()=>{this._forward()},n=()=>{e._readableState.ended||this.destroy()},r=()=>{this._current=null,e.removeListener("readable",t),e.removeListener("end",r),e.removeListener("close",n),this._next()};e.on("readable",t),e.once("end",r),e.once("close",n)}_attachErrorListener(e){if(!e)return;const t=n=>{e.removeListener("error",t),this.destroy(n)};e.once("error",t)}}It.obj=(e=>new It(e,{objectMode:!0,highWaterMark:16})),St=It;var At=function e(t,n){if(t&&n)return e(t)(n);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach(function(e){r[e]=t[e]}),r;function r(){for(var e=new Array(arguments.length),n=0;n<e.length;n++)e[n]=arguments[n];var r=t.apply(this,e),i=e[e.length-1];return"function"==typeof r&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}},Rt={};function Bt(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function Lt(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}(Rt=At(Bt)).strict=At(Lt),Bt.proto=Bt(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return Bt(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return Lt(this)},configurable:!0})});var Ut={};(function(e){Ut=function(t,n){var r,i,s,o=!0;function a(t){function i(){n&&n(t,r),n=null}o?e.nextTick(i):i()}function h(e,t,n){r[e]=n,(0==--i||t)&&a(t)}Array.isArray(t)?(r=[],i=t.length):(s=Object.keys(t),r={},i=s.length),i?s?s.forEach(function(e){t[e](function(t,n){h(e,t,n)})}):t.forEach(function(e,t){e(function(e,n){h(t,e,n)})}):a(null),o=!1}}).call(this,ue);var Ot,Mt,Pt={exports:{}};Ot="undefined"!=typeof self?self:this,Mt=function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=3)}([function(e,t,n){var r=n(5),i=n(1),s=i.toHex,o=i.ceilHeapSize,a=n(6),h=function(e){for(e+=9;e%64>0;e+=1);return e},c=function(e,t){var n=new Int32Array(e,t+320,5),r=new Int32Array(5),i=new DataView(r.buffer);return i.setInt32(0,n[0],!1),i.setInt32(4,n[1],!1),i.setInt32(8,n[2],!1),i.setInt32(12,n[3],!1),i.setInt32(16,n[4],!1),r},u=function(){function e(t){if(function(t,n){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this),(t=t||65536)%64>0)throw new Error("Chunk size must be a multiple of 128 bit");this._offset=0,this._maxChunkLen=t,this._padMaxChunkLen=h(t),this._heap=new ArrayBuffer(o(this._padMaxChunkLen+320+20)),this._h32=new Int32Array(this._heap),this._h8=new Int8Array(this._heap),this._core=new r({Int32Array:Int32Array},{},this._heap)}return e.prototype._initState=function(e,t){this._offset=0;var n=new Int32Array(e,t+320,5);n[0]=1732584193,n[1]=-271733879,n[2]=-1732584194,n[3]=271733878,n[4]=-1009589776},e.prototype._padChunk=function(e,t){var n=h(e),r=new Int32Array(this._heap,0,n>>2);return function(e,t){var n=new Uint8Array(e.buffer),r=t%4,i=t-r;switch(r){case 0:n[i+3]=0;case 1:n[i+2]=0;case 2:n[i+1]=0;case 3:n[i+0]=0}for(var s=1+(t>>2);s<e.length;s++)e[s]=0}(r,e),function(e,t,n){e[t>>2]|=128<<24-(t%4<<3),e[14+(2+(t>>2)&-16)]=n/(1<<29)|0,e[15+(2+(t>>2)&-16)]=n<<3}(r,e,t),n},e.prototype._write=function(e,t,n,r){a(e,this._h8,this._h32,t,n,r||0)},e.prototype._coreCall=function(e,t,n,r,i){var s=n;this._write(e,t,n),i&&(s=this._padChunk(n,r)),this._core.hash(s,this._padMaxChunkLen)},e.prototype.rawDigest=function(e){var t=e.byteLength||e.length||e.size||0;this._initState(this._heap,this._padMaxChunkLen);var n=0,r=this._maxChunkLen;for(n=0;t>n+r;n+=r)this._coreCall(e,n,r,t,!1);return this._coreCall(e,n,t-n,t,!0),c(this._heap,this._padMaxChunkLen)},e.prototype.digest=function(e){return s(this.rawDigest(e).buffer)},e.prototype.digestFromString=function(e){return this.digest(e)},e.prototype.digestFromBuffer=function(e){return this.digest(e)},e.prototype.digestFromArrayBuffer=function(e){return this.digest(e)},e.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},e.prototype.append=function(e){var t=0,n=e.byteLength||e.length||e.size||0,r=this._offset%this._maxChunkLen,i=void 0;for(this._offset+=n;t<n;)i=Math.min(n-t,this._maxChunkLen-r),this._write(e,t,i,r),t+=i,(r+=i)===this._maxChunkLen&&(this._core.hash(this._maxChunkLen,this._padMaxChunkLen),r=0);return this},e.prototype.getState=function(){var e=void 0;if(this._offset%this._maxChunkLen)e=this._heap.slice(0);else{var t=new Int32Array(this._heap,this._padMaxChunkLen+320,5);e=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}return{offset:this._offset,heap:e}},e.prototype.setState=function(e){return this._offset=e.offset,20===e.heap.byteLength?new Int32Array(this._heap,this._padMaxChunkLen+320,5).set(new Int32Array(e.heap)):this._h32.set(new Int32Array(e.heap)),this},e.prototype.rawEnd=function(){var e=this._offset,t=e%this._maxChunkLen,n=this._padChunk(t,e);this._core.hash(n,this._padMaxChunkLen);var r=c(this._heap,this._padMaxChunkLen);return this._initState(this._heap,this._padMaxChunkLen),r},e.prototype.end=function(){return s(this.rawEnd().buffer)},e}();e.exports=u,e.exports._core=r},function(e,t){for(var n=new Array(256),r=0;r<256;r++)n[r]=(r<16?"0":"")+r.toString(16);e.exports.toHex=function(e){for(var t=new Uint8Array(e),r=new Array(e.byteLength),i=0;i<r.length;i++)r[i]=n[t[i]];return r.join("")},e.exports.ceilHeapSize=function(e){var t=0;if(e<=65536)return 65536;if(e<16777216)for(t=1;t<e;t<<=1);else for(t=16777216;t<e;t+=16777216);return t},e.exports.isDedicatedWorkerScope=function(e){var t="WorkerGlobalScope"in e&&e instanceof e.WorkerGlobalScope,n="SharedWorkerGlobalScope"in e&&e instanceof e.SharedWorkerGlobalScope,r="ServiceWorkerGlobalScope"in e&&e instanceof e.ServiceWorkerGlobalScope;return t&&!n&&!r}},function(e,t,n){e.exports=function(){var e=n(0),t=function(e,n,r,i,s){var o=new self.FileReader;o.onloadend=function(){if(o.error)return s(o.error);var a=o.result;n+=o.result.byteLength;try{e.append(a)}catch(h){return void s(h)}n<i.size?t(e,n,r,i,s):s(null,e.end())},o.readAsArrayBuffer(i.slice(n,n+r))},r=!0;return self.onmessage=function(n){if(r){var i=n.data.data,s=n.data.file,o=n.data.id;if(void 0!==o&&(s||i)){var a=n.data.blockSize||4194304,h=new e(a);h.resetState();var c=function(e,t){e?self.postMessage({id:o,error:e.name}):self.postMessage({id:o,hash:t})};i&&function(e,t,n){try{n(null,e.digest(t))}catch(r){return n(r)}}(h,i,c),s&&t(h,0,a,s,c)}}},function(){r=!1}}},function(e,t,n){var r=n(4),i=n(0),s=n(7),o=n(2),a=n(1).isDedicatedWorkerScope,h="undefined"!=typeof self&&a(self);i.disableWorkerBehaviour=h?o():function(){},i.createWorker=function(){var e=r(2),t=e.terminate;return e.terminate=function(){URL.revokeObjectURL(e.objectURL),t.call(e)},e},i.createHash=s,e.exports=i},function(e,t,n){function r(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="/",n.oe=function(e){throw console.error(e),e};var r=n(n.s=ENTRY_MODULE);return r.default||r}var i="[\\.|\\-|\\+|\\w|/|@]+",s="\\((/\\*.*?\\*/)?s?.*?("+i+").*?\\)";function o(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function a(e,t,r){var a={};a[r]=[];var h=t.toString(),c=h.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!c)return a;for(var u,d=c[1],l=new RegExp("(\\\\n|\\W)"+o(d)+s,"g");u=l.exec(h);)"dll-reference"!==u[3]&&a[r].push(u[3]);for(l=new RegExp("\\("+o(d)+'\\("(dll-reference\\s('+i+'))"\\)\\)'+s,"g");u=l.exec(h);)e[u[2]]||(a[r].push(u[1]),e[u[2]]=n(u[1]).m),a[u[2]]=a[u[2]]||[],a[u[2]].push(u[4]);return a}function h(e){return Object.keys(e).reduce(function(t,n){return t||e[n].length>0},!1)}e.exports=function(e,t){t=t||{};var i={main:n.m},s=t.all?{main:Object.keys(i)}:function(e,t){for(var n={main:[t]},r={main:[]},i={main:{}};h(n);)for(var s=Object.keys(n),o=0;o<s.length;o++){var c=s[o],u=n[c].pop();if(i[c]=i[c]||{},!i[c][u]&&e[c][u]){i[c][u]=!0,r[c]=r[c]||[],r[c].push(u);for(var d=a(e,e[c][u],c),l=Object.keys(d),f=0;f<l.length;f++)n[l[f]]=n[l[f]]||[],n[l[f]]=n[l[f]].concat(d[l[f]])}}return r}(i,e),o="";Object.keys(s).filter(function(e){return"main"!==e}).forEach(function(e){for(var t=0;s[e][t];)t++;s[e].push(t),i[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",o=o+"var "+e+" = ("+r.toString().replace("ENTRY_MODULE",JSON.stringify(t))+")({"+s[e].map(function(t){return JSON.stringify(t)+": "+i[e][t].toString()}).join(",")+"});\n"}),o=o+"("+r.toString().replace("ENTRY_MODULE",JSON.stringify(e))+")({"+s.main.map(function(e){return JSON.stringify(e)+": "+i.main[e].toString()}).join(",")+"})(self);";var c=new window.Blob([o],{type:"text/javascript"});if(t.bare)return c;var u=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(c),d=new window.Worker(u);return d.objectURL=u,d}},function(e,t){e.exports=function(e,t,n){"use asm";var r=new e.Int32Array(n);function i(e,t){e=e|0;t=t|0;var n=0,i=0,s=0,o=0,a=0,h=0,c=0,u=0,d=0,l=0,f=0,p=0,g=0,m=0;s=r[t+320>>2]|0;a=r[t+324>>2]|0;c=r[t+328>>2]|0;d=r[t+332>>2]|0;f=r[t+336>>2]|0;for(n=0;(n|0)<(e|0);n=n+64|0){o=s;h=a;u=c;l=d;p=f;for(i=0;(i|0)<64;i=i+4|0){m=r[n+i>>2]|0;g=((s<<5|s>>>27)+(a&c|~a&d)|0)+((m+f|0)+1518500249|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[e+i>>2]=m}for(i=e+64|0;(i|0)<(e+80|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a&c|~a&d)|0)+((m+f|0)+1518500249|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+80|0;(i|0)<(e+160|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a^c^d)|0)+((m+f|0)+1859775393|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+160|0;(i|0)<(e+240|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a&c|a&d|c&d)|0)+((m+f|0)-1894007588|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+240|0;(i|0)<(e+320|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a^c^d)|0)+((m+f|0)-899497514|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}s=s+o|0;a=a+h|0;c=c+u|0;d=d+l|0;f=f+p|0}r[t+320>>2]=s;r[t+324>>2]=a;r[t+328>>2]=c;r[t+332>>2]=d;r[t+336>>2]=f}return{hash:i}}},function(e,t){var n=this,r=void 0;"undefined"!=typeof self&&void 0!==self.FileReaderSync&&(r=new self.FileReaderSync);var i=function(e,t,n,r,i,s){var o=void 0,a=s%4,h=(i+a)%4,c=i-h;switch(a){case 0:t[s]=e[r+3];case 1:t[s+1-(a<<1)|0]=e[r+2];case 2:t[s+2-(a<<1)|0]=e[r+1];case 3:t[s+3-(a<<1)|0]=e[r]}if(!(i<h+(4-a))){for(o=4-a;o<c;o=o+4|0)n[s+o>>2|0]=e[r+o]<<24|e[r+o+1]<<16|e[r+o+2]<<8|e[r+o+3];switch(h){case 3:t[s+c+1|0]=e[r+c+2];case 2:t[s+c+2|0]=e[r+c+1];case 1:t[s+c+3|0]=e[r+c]}}};e.exports=function(e,t,s,o,a,h){if("string"==typeof e)return function(e,t,n,r,i,s){var o=void 0,a=s%4,h=(i+a)%4,c=i-h;switch(a){case 0:t[s]=e.charCodeAt(r+3);case 1:t[s+1-(a<<1)|0]=e.charCodeAt(r+2);case 2:t[s+2-(a<<1)|0]=e.charCodeAt(r+1);case 3:t[s+3-(a<<1)|0]=e.charCodeAt(r)}if(!(i<h+(4-a))){for(o=4-a;o<c;o=o+4|0)n[s+o>>2]=e.charCodeAt(r+o)<<24|e.charCodeAt(r+o+1)<<16|e.charCodeAt(r+o+2)<<8|e.charCodeAt(r+o+3);switch(h){case 3:t[s+c+1|0]=e.charCodeAt(r+c+2);case 2:t[s+c+2|0]=e.charCodeAt(r+c+1);case 1:t[s+c+3|0]=e.charCodeAt(r+c)}}}(e,t,s,o,a,h);if(e instanceof Array)return i(e,t,s,o,a,h);if(n&&n.Buffer&&n.Buffer.isBuffer(e))return i(e,t,s,o,a,h);if(e instanceof ArrayBuffer)return i(new Uint8Array(e),t,s,o,a,h);if(e.buffer instanceof ArrayBuffer)return i(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),t,s,o,a,h);if(e instanceof Blob)return function(e,t,n,i,s,o){var a=void 0,h=o%4,c=(s+h)%4,u=s-c,d=new Uint8Array(r.readAsArrayBuffer(e.slice(i,i+s)));switch(h){case 0:t[o]=d[3];case 1:t[o+1-(h<<1)|0]=d[2];case 2:t[o+2-(h<<1)|0]=d[1];case 3:t[o+3-(h<<1)|0]=d[0]}if(!(s<c+(4-h))){for(a=4-h;a<u;a=a+4|0)n[o+a>>2|0]=d[a]<<24|d[a+1]<<16|d[a+2]<<8|d[a+3];switch(c){case 3:t[o+u+1|0]=d[u+2];case 2:t[o+u+2|0]=d[u+1];case 1:t[o+u+3|0]=d[u]}}}(e,t,s,o,a,h);throw new Error("Unsupported data type.")}},function(e,t,n){var r=n(0),i=n(1).toHex,s=function(){function e(){!function(t,n){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this),this._rusha=new r,this._rusha.resetState()}return e.prototype.update=function(e){return this._rusha.append(e),this},e.prototype.digest=function(e){var t=this._rusha.rawEnd().buffer;if(!e)return t;if("hex"===e)return i(t);throw new Error("unsupported digest encoding")},e}();e.exports=function(){return new s}}])},"object"==typeof Pt.exports?Pt.exports=Mt():"object"==typeof Pt.exports?Pt.exports.Rusha=Mt():Ot.Rusha=Mt(),Pt=Pt.exports;var Nt={},Ht=new Pt,jt="undefined"!=typeof window?window:self,Dt=jt.crypto||jt.msCrypto||{},qt=Dt.subtle||Dt.webkitSubtle;function Ft(e){return Ht.digest(e)}try{qt.digest({name:"sha-1"},new Uint8Array).catch(function(){qt=!1})}catch(_i){qt=!1}(Nt=function(e,t){qt?("string"==typeof e&&(e=function(e){for(var t=e.length,n=new Uint8Array(t),r=0;r<t;r++)n[r]=e.charCodeAt(r);return n}(e)),qt.digest({name:"sha-1"},e).then(function(e){t(function(e){for(var t=e.length,n=[],r=0;r<t;r++){var i=e[r];n.push((i>>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")}(new Uint8Array(e)))},function(n){t(Ft(e))})):setTimeout(t,0,Ft(e))}).sync=Ft;var Wt={};(function(e,t,n){function r(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(r(t)):e.concat(t),[])}function i(t,i,a){if("undefined"!=typeof FileList&&t instanceof FileList&&(t=Array.from(t)),Array.isArray(t)||(t=[t]),0===t.length)throw new Error("invalid input type");t.forEach(e=>{if(null==e)throw new Error(`invalid input type: ${e}`)}),1!==(t=t.map(e=>h(e)&&"string"==typeof e.path&&"function"==typeof wt.stat?e.path:e)).length||"string"==typeof t[0]||t[0].name||(t[0].name=i.name);let u=null;t.forEach((e,n)=>{if("string"==typeof e)return;let r=e.fullPath||e.name;r||(r=`Unknown File ${n+1}`,e.unknownName=!0),e.path=r.split("/"),e.path[0]||e.path.shift(),e.path.length<2?u=null:0===n&&t.length>1?u=e.path[0]:e.path[0]!==u&&(u=null)}),t=t.filter(e=>{if("string"==typeof e)return!0;const t=e.path[e.path.length-1];return o(t)&&kt.not(t)}),u&&t.forEach(e=>{const t=(n.isBuffer(e)||c(e))&&!e.path;"string"==typeof e||t||e.path.shift()}),!i.name&&u&&(i.name=u),i.name||t.some(e=>"string"==typeof e?(i.name=ut.basename(e),!0):e.unknownName?void 0:(i.name=e.path[e.path.length-1],!0)),i.name||(i.name=`Unnamed Torrent ${Date.now()}`);const d=t.reduce((e,t)=>e+Number("string"==typeof t),0);let l=1===t.length;if(1===t.length&&"string"==typeof t[0]){if("function"!=typeof wt.stat)throw new Error("filesystem paths do not work in the browser");vt(t[0],(e,t)=>{if(e)return a(e);l=t,f()})}else e.nextTick(()=>{f()});function f(){Ut(t.map(e=>t=>{const i={};if(h(e))i.getStream=function(e){return()=>new bt(e)}(e),i.length=e.size;else if(n.isBuffer(e))i.getStream=function(e){return()=>{const t=new it.PassThrough;return t.end(e),t}}(e),i.length=e.length;else{if(!c(e)){if("string"==typeof e){if("function"!=typeof wt.stat)throw new Error("filesystem paths do not work in the browser");return void function(e,t,n){!function e(t,n,r){wt.stat(t,(i,s)=>{if(i)return r(i);s.isDirectory()?wt.readdir(t,(i,s)=>{if(i)return r(i);Ut(s.filter(o).filter(kt.not).map(r=>i=>{e(ut.join(t,r),n,i)}),r)}):s.isFile()&&n(t,r)})}(e,s,(i,s)=>{if(i)return n(i);s=Array.isArray(s)?r(s):[s],e=ut.normalize(e),t&&(e=e.slice(0,e.lastIndexOf(ut.sep)+1)),e[e.length-1]!==ut.sep&&(e+=ut.sep),s.forEach(t=>{t.getStream=function(e){return()=>wt.createReadStream(e)}(t.path),t.path=t.path.replace(e,"").split(ut.sep)}),n(null,s)})}(e,d>1||l,t)}throw new Error("invalid input type")}i.getStream=function(e,t){return()=>{const n=new it.Transform;return n._transform=function(e,n,r){t.length+=e.length,this.push(e),r()},e.pipe(n),n}}(e,i),i.length=0}i.path=e.path,t(null,i)}),(e,t)=>{if(e)return a(e);t=r(t),a(null,t,l)})}}function s(e,t){t=Rt(t),wt.stat(e,(n,r)=>{if(n)return t(n);const i={length:r.size,path:e};t(null,i)})}function o(e){return"."!==e[0]}function a(e,t){return e+t.length}function h(e){return"undefined"!=typeof Blob&&e instanceof Blob}function c(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(Wt=function(e,r,s){"function"==typeof r&&([r,s]=[s,r]),i(e,r=r?Object.assign({},r):{},(e,i,o)=>{if(e)return s(e);r.singleFileTorrent=o,function(e,r,i){let s=r.announceList;s||("string"==typeof r.announce?s=[[r.announce]]:Array.isArray(r.announce)&&(s=r.announce.map(e=>[e]))),s||(s=[]),t.WEBTORRENT_ANNOUNCE&&("string"==typeof t.WEBTORRENT_ANNOUNCE?s.push([[t.WEBTORRENT_ANNOUNCE]]):Array.isArray(t.WEBTORRENT_ANNOUNCE)&&(s=s.concat(t.WEBTORRENT_ANNOUNCE.map(e=>[e])))),void 0===r.announce&&void 0===r.announceList&&(s=s.concat(Wt.announceList)),"string"==typeof r.urlList&&(r.urlList=[r.urlList]);const o={info:{name:r.name},"creation date":Math.ceil((Number(r.creationDate)||Date.now())/1e3),encoding:"UTF-8"};0!==s.length&&(o.announce=s[0][0],o["announce-list"]=s),void 0!==r.comment&&(o.comment=r.comment),void 0!==r.createdBy&&(o["created by"]=r.createdBy),void 0!==r.private&&(o.info.private=Number(r.private)),void 0!==r.sslCert&&(o.info["ssl-cert"]=r.sslCert),void 0!==r.urlList&&(o["url-list"]=r.urlList);const h=r.pieceLength||(c=e.reduce(a,0),ot(c/at,ct));var c;o.info["piece length"]=h,function(e,t,r){r=Rt(r);const i=[];let s=0;const o=e.map(e=>e.getStream);let a=0,h=0,c=!1;const u=new St(o),d=new st(t,{zeroPadding:!1});function l(e){s+=e.length;const t=h;Nt(e,e=>{i[t]=e,a-=1,m()}),a+=1,h+=1}function f(){c=!0,m()}function p(e){g(),r(e)}function g(){u.removeListener("error",p),d.removeListener("data",l),d.removeListener("end",f),d.removeListener("error",p)}function m(){c&&0===a&&(g(),r(null,n.from(i.join(""),"hex"),s))}u.on("error",p),u.pipe(d).on("data",l).on("end",f).on("error",p)}(e,h,(t,n,s)=>{if(t)return i(t);o.info.pieces=n,e.forEach(e=>{delete e.getStream}),r.singleFileTorrent?o.info.length=s:o.info.files=e,i(null,Q.encode(o))})}(i,r,s)})}).parseInput=function(e,t,n){"function"==typeof t&&([t,n]=[n,t]),i(e,t=t?Object.assign({},t):{},n)},Wt.announceList=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"],["wss://tracker.fastcast.nz"]]}).call(this,ue,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},d({}).Buffer);var zt={};(function(e){zt.log=function(...e){return"object"==typeof console&&console.log&&console.log(...e)},zt.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+zt.humanize(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let n=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(r=n))}),e.splice(r,0,t)},zt.save=function(e){try{e?zt.storage.setItem("debug",e):zt.storage.removeItem("debug")}catch(t){}},zt.load=function(){let t;try{t=zt.storage.getItem("debug")}catch(n){}return!t&&void 0!==e&&"env"in e&&(t=e.env.DEBUG),t},zt.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},zt.storage=function(){try{return localStorage}catch(e){}}(),zt.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"],zt=function(e){function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}function n(e){let r;function o(...e){if(!o.enabled)return;const t=o,i=Number(new Date),s=i-(r||i);t.diff=s,t.prev=r,t.curr=i,r=i,e[0]=n.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return r;a++;const s=n.formatters[i];if("function"==typeof s){const n=e[a];r=s.call(t,n),e.splice(a,1),a--}return r}),n.formatArgs.call(t,e),(t.log||n.log).apply(t,e)}return o.namespace=e,o.enabled=n.enabled(e),o.useColors=n.useColors(),o.color=t(e),o.destroy=i,o.extend=s,"function"==typeof n.init&&n.init(o),n.instances.push(o),o}function i(){const e=n.instances.indexOf(this);return-1!==e&&(n.instances.splice(e,1),!0)}function s(e,t){const r=n(this.namespace+(void 0===t?":":t)+e);return r.log=this.log,r}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return n.debug=n,n.default=n,n.coerce=function(e){return e instanceof Error?e.stack||e.message:e},n.disable=function(){const e=[...n.names.map(o),...n.skips.map(o).map(e=>"-"+e)].join(",");return n.enable(""),e},n.enable=function(e){let t;n.save(e),n.names=[],n.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(t=0;t<i;t++)r[t]&&("-"===(e=r[t].replace(/\*/g,".*?"))[0]?n.skips.push(new RegExp("^"+e.substr(1)+"$")):n.names.push(new RegExp("^"+e+"$")));for(t=0;t<n.instances.length;t++){const e=n.instances[t];e.enabled=n.enabled(e.namespace)}},n.enabled=function(e){if("*"===e[e.length-1])return!0;let t,r;for(t=0,r=n.skips.length;t<r;t++)if(n.skips[t].test(e))return!1;for(t=0,r=n.names.length;t<r;t++)if(n.names[t].test(e))return!0;return!1},n.humanize=r({}),Object.keys(e).forEach(t=>{n[t]=e[t]}),n.instances=[],n.names=[],n.skips=[],n.formatters={},n.selectColor=t,n.enable(n.load()),n}(zt);const{formatters:t}=zt;t.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}).call(this,ue);var $t={};(function(e){$t=function(t,n){if("undefined"==typeof Blob||!(t instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof n)throw new Error("second argument must be a function");var r=new FileReader;r.addEventListener("loadend",function t(i){r.removeEventListener("loadend",t,!1),i.error?n(i.error):n(null,e.from(r.result))},!1),r.readAsArrayBuffer(t)}}).call(this,d({}).Buffer);var Vt={};(function(e){var t;function n(){if(void 0!==t)return t;if(e.XMLHttpRequest){t=new e.XMLHttpRequest;try{t.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(n){t=null}}else t=null;return t}function r(e){var t=n();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(r){}return!1}function i(e){return"function"==typeof e}Vt.fetch=i(e.fetch)&&i(e.ReadableStream),Vt.writableStream=i(e.WritableStream),Vt.abortController=i(e.AbortController),Vt.arraybuffer=Vt.fetch||r("arraybuffer"),Vt.msstream=!Vt.fetch&&r("ms-stream"),Vt.mozchunkedarraybuffer=!Vt.fetch&&r("moz-chunked-arraybuffer"),Vt.overrideMimeType=Vt.fetch||!!n()&&i(n().overrideMimeType),t=null}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Gt={};(function(e,t,n){var r=Gt.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},i=Gt.IncomingMessage=function(r,i,s,o){var a=this;if(it.Readable.call(a),a._mode=s,a.headers={},a.rawHeaders=[],a.trailers={},a.rawTrailers=[],a.on("end",function(){e.nextTick(function(){a.emit("close")})}),"fetch"===s){if(a._fetchResponse=i,a.url=i.url,a.statusCode=i.status,a.statusMessage=i.statusText,i.headers.forEach(function(e,t){a.headers[t.toLowerCase()]=e,a.rawHeaders.push(t,e)}),Vt.writableStream){var h=new WritableStream({write:function(e){return new Promise(function(t,r){a._destroyed?r():a.push(n.from(e))?t():a._resumeFetch=t})},close:function(){t.clearTimeout(o),a._destroyed||a.push(null)},abort:function(e){a._destroyed||a.emit("error",e)}});try{return void i.body.pipeTo(h).catch(function(e){t.clearTimeout(o),a._destroyed||a.emit("error",e)})}catch(l){}}var c=i.body.getReader();!function e(){c.read().then(function(r){if(!a._destroyed){if(r.done)return t.clearTimeout(o),void a.push(null);a.push(n.from(r.value)),e()}}).catch(function(e){t.clearTimeout(o),a._destroyed||a.emit("error",e)})}()}else if(a._xhr=r,a._pos=0,a.url=r.responseURL,a.statusCode=r.status,a.statusMessage=r.statusText,r.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var n=t[1].toLowerCase();"set-cookie"===n?(void 0===a.headers[n]&&(a.headers[n]=[]),a.headers[n].push(t[2])):void 0!==a.headers[n]?a.headers[n]+=", "+t[2]:a.headers[n]=t[2],a.rawHeaders.push(t[1],t[2])}}),a._charset="x-user-defined",!Vt.overrideMimeType){var u=a.rawHeaders["mime-type"];if(u){var d=u.match(/;\s*charset=([^;])(;|$)/);d&&(a._charset=d[1].toLowerCase())}a._charset||(a._charset="utf-8")}};Be(i,it.Readable),i.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},i.prototype._onXHRProgress=function(){var e=this,i=e._xhr,s=null;switch(e._mode){case"text":if((s=i.responseText).length>e._pos){var o=s.substr(e._pos);if("x-user-defined"===e._charset){for(var a=n.alloc(o.length),h=0;h<o.length;h++)a[h]=255&o.charCodeAt(h);e.push(a)}else e.push(o,e._charset);e._pos=s.length}break;case"arraybuffer":if(i.readyState!==r.DONE||!i.response)break;s=i.response,e.push(n.from(new Uint8Array(s)));break;case"moz-chunked-arraybuffer":if(s=i.response,i.readyState!==r.LOADING||!s)break;e.push(n.from(new Uint8Array(s)));break;case"ms-stream":if(s=i.response,i.readyState!==r.LOADING)break;var c=new t.MSStreamReader;c.onprogress=function(){c.result.byteLength>e._pos&&(e.push(n.from(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(s)}e._xhr.readyState===r.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,ue,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},d({}).Buffer);var Kt={};(function(e,t,n){var r=Gt.IncomingMessage,i=Gt.readyStates,s=Kt=function(e){var t,r=this;it.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+n.from(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var i=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!Vt.abortController)i=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!Vt.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return Vt.fetch&&t?"fetch":Vt.mozchunkedarraybuffer?"moz-chunked-arraybuffer":Vt.msstream?"ms-stream":Vt.arraybuffer&&e?"arraybuffer":"text"}(t,i),r._fetchTimer=null,r.on("finish",function(){r._onFinish()})};Be(s,it.Writable),s.prototype.setHeader=function(e,t){var n=e.toLowerCase();-1===o.indexOf(n)&&(this._headers[n]={name:e,value:t})},s.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},s.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},s.prototype._onFinish=function(){var n=this;if(!n._destroyed){var r=n._opts,s=n._headers,o=null;"GET"!==r.method&&"HEAD"!==r.method&&(o=new Blob(n._body,{type:(s["content-type"]||{}).value||""}));var a=[];if(Object.keys(s).forEach(function(e){var t=s[e].name,n=s[e].value;Array.isArray(n)?n.forEach(function(e){a.push([t,e])}):a.push([t,n])}),"fetch"===n._mode){var h=null;if(Vt.abortController){var c=new AbortController;h=c.signal,n._fetchAbortController=c,"requestTimeout"in r&&0!==r.requestTimeout&&(n._fetchTimer=t.setTimeout(function(){n.emit("requestTimeout"),n._fetchAbortController&&n._fetchAbortController.abort()},r.requestTimeout))}t.fetch(n._opts.url,{method:n._opts.method,headers:a,body:o||void 0,mode:"cors",credentials:r.withCredentials?"include":"same-origin",signal:h}).then(function(e){n._fetchResponse=e,n._connect()},function(e){t.clearTimeout(n._fetchTimer),n._destroyed||n.emit("error",e)})}else{var u=n._xhr=new t.XMLHttpRequest;try{u.open(n._opts.method,n._opts.url,!0)}catch(_i){return void e.nextTick(function(){n.emit("error",_i)})}"responseType"in u&&(u.responseType=n._mode),"withCredentials"in u&&(u.withCredentials=!!r.withCredentials),"text"===n._mode&&"overrideMimeType"in u&&u.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in r&&(u.timeout=r.requestTimeout,u.ontimeout=function(){n.emit("requestTimeout")}),a.forEach(function(e){u.setRequestHeader(e[0],e[1])}),n._response=null,u.onreadystatechange=function(){switch(u.readyState){case i.LOADING:case i.DONE:n._onXHRProgress()}},"moz-chunked-arraybuffer"===n._mode&&(u.onprogress=function(){n._onXHRProgress()}),u.onerror=function(){n._destroyed||n.emit("error",new Error("XHR error"))};try{u.send(o)}catch(_i){return void e.nextTick(function(){n.emit("error",_i)})}}}},s.prototype._onXHRProgress=function(){(function(e){try{var t=e.status;return null!==t&&0!==t}catch(n){return!1}})(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},s.prototype._connect=function(){var e=this;e._destroyed||(e._response=new r(e._xhr,e._fetchResponse,e._mode,e._fetchTimer),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},s.prototype._write=function(e,t,n){this._body.push(e),n()},s.prototype.abort=s.prototype.destroy=function(){this._destroyed=!0,t.clearTimeout(this._fetchTimer),this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},s.prototype.end=function(e,t,n){"function"==typeof e&&(n=e,e=void 0),it.Writable.prototype.end.call(this,e,t,n)},s.prototype.flushHeaders=function(){},s.prototype.setTimeout=function(){},s.prototype.setNoDelay=function(){},s.prototype.setSocketKeepAlive=function(){};var o=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this,ue,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},d({}).Buffer);var Yt=Object.prototype.hasOwnProperty,Jt={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},Xt={exports:{}};(function(e){!function(t){var n="object"==typeof Xt.exports&&Xt.exports&&!Xt.exports.nodeType&&Xt.exports,r=Xt&&!Xt.nodeType&&Xt,i="object"==typeof e&&e;i.global!==i&&i.window!==i&&i.self!==i||(t=i);var s,o,a=2147483647,h=36,c=1,u=26,d=38,l=700,f=72,p=128,g="-",m=/^xn--/,_=/[^\x20-\x7E]/,y=/[\x2E\u3002\uFF0E\uFF61]/g,b={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},w=h-c,v=Math.floor,E=String.fromCharCode;function k(e){throw new RangeError(b[e])}function S(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function C(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+S((e=e.replace(y,".")).split("."),t).join(".")}function x(e){for(var t,n,r=[],i=0,s=e.length;i<s;)(t=e.charCodeAt(i++))>=55296&&t<=56319&&i<s?56320==(64512&(n=e.charCodeAt(i++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),i--):r.push(t);return r}function T(e){return S(e,function(e){var t="";return e>65535&&(t+=E((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+E(e)}).join("")}function I(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function A(e,t,n){var r=0;for(e=n?v(e/l):e>>1,e+=v(e/t);e>w*u>>1;r+=h)e=v(e/w);return v(r+(w+1)*e/(e+d))}function R(e){var t,n,r,i,s,o,d,l,m,_,y,b=[],w=e.length,E=0,S=p,C=f;for((n=e.lastIndexOf(g))<0&&(n=0),r=0;r<n;++r)e.charCodeAt(r)>=128&&k("not-basic"),b.push(e.charCodeAt(r));for(i=n>0?n+1:0;i<w;){for(s=E,o=1,d=h;i>=w&&k("invalid-input"),((l=(y=e.charCodeAt(i++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:h)>=h||l>v((a-E)/o))&&k("overflow"),E+=l*o,!(l<(m=d<=C?c:d>=C+u?u:d-C));d+=h)o>v(a/(_=h-m))&&k("overflow"),o*=_;C=A(E-s,t=b.length+1,0==s),v(E/t)>a-S&&k("overflow"),S+=v(E/t),E%=t,b.splice(E++,0,S)}return T(b)}function B(e){var t,n,r,i,s,o,d,l,m,_,y,b,w,S,C,T=[];for(b=(e=x(e)).length,t=p,n=0,s=f,o=0;o<b;++o)(y=e[o])<128&&T.push(E(y));for(r=i=T.length,i&&T.push(g);r<b;){for(d=a,o=0;o<b;++o)(y=e[o])>=t&&y<d&&(d=y);for(d-t>v((a-n)/(w=r+1))&&k("overflow"),n+=(d-t)*w,t=d,o=0;o<b;++o)if((y=e[o])<t&&++n>a&&k("overflow"),y==t){for(l=n,m=h;!(l<(_=m<=s?c:m>=s+u?u:m-s));m+=h)C=l-_,S=h-_,T.push(E(I(_+C%S,0))),l=v(C/S);T.push(E(I(l,0))),s=A(n,w,r==i),n=0,++r}++n,++t}return T.join("")}if(s={version:"1.4.1",ucs2:{decode:x,encode:T},decode:R,encode:B,toASCII:function(e){return C(e,function(e){return _.test(e)?"xn--"+B(e):e})},toUnicode:function(e){return C(e,function(e){return m.test(e)?R(e.slice(4).toLowerCase()):e})}},n&&r)if(Xt.exports==n)r.exports=s;else for(o in s)s.hasOwnProperty(o)&&(n[o]=s[o]);else t.punycode=s}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),Xt=Xt.exports;var Zt={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}};function Qt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var en=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},tn=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},nn=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function rn(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var sn=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},on={parse:function(e,t,n,r){t=t||"&",n=n||"=";var i={};if("string"!=typeof e||0===e.length)return i;var s=/\+/g;e=e.split(t);var o=1e3;r&&"number"==typeof r.maxKeys&&(o=r.maxKeys);var a=e.length;o>0&&a>o&&(a=o);for(var h=0;h<a;++h){var c,u,d,l,f=e[h].replace(s,"%20"),p=f.indexOf(n);p>=0?(c=f.substr(0,p),u=f.substr(p+1)):(c=f,u=""),d=decodeURIComponent(c),l=decodeURIComponent(u),Qt(i,d)?en(i[d])?i[d].push(l):i[d]=[i[d],l]:i[d]=l}return i},stringify:function(e,t,n,r){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?rn(sn(e),function(r){var i=encodeURIComponent(tn(r))+n;return nn(e[r])?rn(e[r],function(e){return i+encodeURIComponent(tn(e))}).join(t):i+encodeURIComponent(tn(e[r]))}).join(t):r?encodeURIComponent(tn(r))+n+encodeURIComponent(tn(e)):""}},an={};function hn(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}an.parse=vn;var cn=/^([a-z0-9.+-]+:)/i,un=/:[0-9]*$/,dn=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,ln=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),fn=["'"].concat(ln),pn=["%","/","?",";","#"].concat(fn),gn=["/","?","#"],mn=/^[+a-z0-9A-Z_-]{0,63}$/,_n=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,yn={javascript:!0,"javascript:":!0},bn={javascript:!0,"javascript:":!0},wn={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function vn(e,t,n){if(e&&Zt.isObject(e)&&e instanceof hn)return e;var r=new hn;return r.parse(e,t,n),r}hn.prototype.parse=function(e,t,n){if(!Zt.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var r=e.indexOf("?"),i=-1!==r&&r<e.indexOf("#")?"?":"#",s=e.split(i);s[0]=s[0].replace(/\\/g,"/");var o=e=s.join(i);if(o=o.trim(),!n&&1===e.split("#").length){var a=dn.exec(o);if(a)return this.path=o,this.href=o,this.pathname=a[1],a[2]?(this.search=a[2],this.query=t?on.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var h=cn.exec(o);if(h){var c=(h=h[0]).toLowerCase();this.protocol=c,o=o.substr(h.length)}if(n||h||o.match(/^\/\/[^@\/]+@[^@\/]+/)){var u="//"===o.substr(0,2);!u||h&&bn[h]||(o=o.substr(2),this.slashes=!0)}if(!bn[h]&&(u||h&&!wn[h])){for(var d,l,f=-1,p=0;p<gn.length;p++)-1!==(g=o.indexOf(gn[p]))&&(-1===f||g<f)&&(f=g);for(-1!==(l=-1===f?o.lastIndexOf("@"):o.lastIndexOf("@",f))&&(d=o.slice(0,l),o=o.slice(l+1),this.auth=decodeURIComponent(d)),f=-1,p=0;p<pn.length;p++){var g;-1!==(g=o.indexOf(pn[p]))&&(-1===f||g<f)&&(f=g)}-1===f&&(f=o.length),this.host=o.slice(0,f),o=o.slice(f),this.parseHost(),this.hostname=this.hostname||"";var m="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!m)for(var _=this.hostname.split(/\./),y=(p=0,_.length);p<y;p++){var b=_[p];if(b&&!b.match(mn)){for(var w="",v=0,E=b.length;v<E;v++)b.charCodeAt(v)>127?w+="x":w+=b[v];if(!w.match(mn)){var k=_.slice(0,p),S=_.slice(p+1),C=b.match(_n);C&&(k.push(C[1]),S.unshift(C[2])),S.length&&(o="/"+S.join(".")+o),this.hostname=k.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),m||(this.hostname=Xt.toASCII(this.hostname));var x=this.port?":"+this.port:"",T=this.hostname||"";this.host=T+x,this.href+=this.host,m&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==o[0]&&(o="/"+o))}if(!yn[c])for(p=0,y=fn.length;p<y;p++){var I=fn[p];if(-1!==o.indexOf(I)){var A=encodeURIComponent(I);A===I&&(A=escape(I)),o=o.split(I).join(A)}}var R=o.indexOf("#");-1!==R&&(this.hash=o.substr(R),o=o.slice(0,R));var B=o.indexOf("?");if(-1!==B?(this.search=o.substr(B),this.query=o.substr(B+1),t&&(this.query=on.parse(this.query)),o=o.slice(0,B)):t&&(this.search="",this.query={}),o&&(this.pathname=o),wn[c]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){x=this.pathname||"";var L=this.search||"";this.path=x+L}return this.href=this.format(),this},hn.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",i=!1,s="";this.host?i=e+this.host:this.hostname&&(i=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(i+=":"+this.port)),this.query&&Zt.isObject(this.query)&&Object.keys(this.query).length&&(s=on.stringify(this.query));var o=this.search||s&&"?"+s||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||wn[t])&&!1!==i?(i="//"+(i||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):i||(i=""),r&&"#"!==r.charAt(0)&&(r="#"+r),o&&"?"!==o.charAt(0)&&(o="?"+o),t+i+(n=n.replace(/[?#]/g,function(e){return encodeURIComponent(e)}))+(o=o.replace("#","%23"))+r},hn.prototype.resolve=function(e){return this.resolveObject(vn(e,!1,!0)).format()},hn.prototype.resolveObject=function(e){if(Zt.isString(e)){var t=new hn;t.parse(e,!1,!0),e=t}for(var n=new hn,r=Object.keys(this),i=0;i<r.length;i++){var s=r[i];n[s]=this[s]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var o=Object.keys(e),a=0;a<o.length;a++){var h=o[a];"protocol"!==h&&(n[h]=e[h])}return wn[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!wn[e.protocol]){for(var c=Object.keys(e),u=0;u<c.length;u++){var d=c[u];n[d]=e[d]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||bn[e.protocol])n.pathname=e.pathname;else{for(var l=(e.pathname||"").split("/");l.length&&!(e.host=l.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==l[0]&&l.unshift(""),l.length<2&&l.unshift(""),n.pathname=l.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var f=n.pathname||"",p=n.search||"";n.path=f+p}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var g=n.pathname&&"/"===n.pathname.charAt(0),m=e.host||e.pathname&&"/"===e.pathname.charAt(0),_=m||g||n.host&&e.pathname,y=_,b=n.pathname&&n.pathname.split("/")||[],w=(l=e.pathname&&e.pathname.split("/")||[],n.protocol&&!wn[n.protocol]);if(w&&(n.hostname="",n.port=null,n.host&&(""===b[0]?b[0]=n.host:b.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===l[0]?l[0]=e.host:l.unshift(e.host)),e.host=null),_=_&&(""===l[0]||""===b[0])),m)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,b=l;else if(l.length)b||(b=[]),b.pop(),b=b.concat(l),n.search=e.search,n.query=e.query;else if(!Zt.isNullOrUndefined(e.search))return w&&(n.hostname=n.host=b.shift(),(C=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=C.shift(),n.host=n.hostname=C.shift())),n.search=e.search,n.query=e.query,Zt.isNull(n.pathname)&&Zt.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!b.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var v=b.slice(-1)[0],E=(n.host||e.host||b.length>1)&&("."===v||".."===v)||""===v,k=0,S=b.length;S>=0;S--)"."===(v=b[S])?b.splice(S,1):".."===v?(b.splice(S,1),k++):k&&(b.splice(S,1),k--);if(!_&&!y)for(;k--;k)b.unshift("..");!_||""===b[0]||b[0]&&"/"===b[0].charAt(0)||b.unshift(""),E&&"/"!==b.join("/").substr(-1)&&b.push("");var C,x=""===b[0]||b[0]&&"/"===b[0].charAt(0);return w&&(n.hostname=n.host=x?"":b.length?b.shift():"",(C=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=C.shift(),n.host=n.hostname=C.shift())),(_=_||n.host&&b.length)&&!x&&b.unshift(""),b.length?n.pathname=b.join("/"):(n.pathname=null,n.path=null),Zt.isNull(n.pathname)&&Zt.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},hn.prototype.parseHost=function(){var e=this.host,t=un.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var En={};(function(e){var t=En;t.request=function(t,n){t="string"==typeof t?an.parse(t):function(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var r in n)Yt.call(n,r)&&(e[r]=n[r])}return e}(t);var r=-1===e.location.protocol.search(/^https?:$/)?"http:":"",i=t.protocol||r,s=t.hostname||t.host,o=t.port,a=t.path||"/";s&&-1!==s.indexOf(":")&&(s="["+s+"]"),t.url=(s?i+"//"+s:"")+(o?":"+o:"")+a,t.method=(t.method||"GET").toUpperCase(),t.headers=t.headers||{};var h=new Kt(t);return n&&h.on("response",n),h},t.get=function(e,n){var r=t.request(e,n);return r.end(),r},t.ClientRequest=Kt,t.IncomingMessage=Gt.IncomingMessage,t.Agent=function(){},t.Agent.defaultMaxSockets=4,t.globalAgent=new t.Agent,t.STATUS_CODES=Jt,t.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var kn={},Sn=kn;for(var Cn in En)En.hasOwnProperty(Cn)&&(Sn[Cn]=En[Cn]);function xn(e){if("string"==typeof e&&(e=an.parse(e)),e.protocol||(e.protocol="https:"),"https:"!==e.protocol)throw new Error('Protocol "'+e.protocol+'" not supported. Expected "https:"');return e}Sn.request=function(e,t){return e=xn(e),En.request.call(this,e,t)},Sn.get=function(e,t){return e=xn(e),En.get.call(this,e,t)};var Tn={};(function(e){Tn=n;const t=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;function n(r,i){if(r=Object.assign({maxRedirects:10},"string"==typeof r?{url:r}:r),i=Rt(i),r.url){const{hostname:e,port:t,protocol:n,auth:i,path:s}=an.parse(r.url);delete r.url,e||t||n||i?Object.assign(r,{hostname:e,port:t,protocol:n,auth:i,path:s}):r.path=s}const s={"accept-encoding":"gzip, deflate"};let o;r.headers&&Object.keys(r.headers).forEach(e=>s[e.toLowerCase()]=r.headers[e]),r.headers=s,r.body?o=r.json&&!t(r.body)?JSON.stringify(r.body):r.body:r.form&&(o="string"==typeof r.form?r.form:on.stringify(r.form),r.headers["content-type"]="application/x-www-form-urlencoded"),o&&(r.method||(r.method="POST"),t(o)||(r.headers["content-length"]=e.byteLength(o)),r.json&&!r.form&&(r.headers["content-type"]="application/json")),delete r.body,delete r.form,r.json&&(r.headers.accept="application/json"),r.method&&(r.method=r.method.toUpperCase());const a=("https:"===r.protocol?kn:En).request(r,e=>{if(e.statusCode>=300&&e.statusCode<400&&e.headers.location)return r.url=e.headers.location,delete r.headers.host,e.resume(),"POST"===r.method&&[301,302].includes(e.statusCode)&&(r.method="GET",delete r.headers["content-length"],delete r.headers["content-type"]),0==r.maxRedirects--?i(new Error("too many redirects")):n(r,i);const t="function"==typeof ne&&"HEAD"!==r.method;i(null,t?ne(e):e)});return a.on("timeout",()=>{a.abort(),i(new Error("Request timed out"))}),a.on("error",i),t(o)?o.on("error",i).pipe(a):a.end(o),a}n.concat=((e,t)=>n(e,(n,r)=>{if(n)return t(n);N(r,(n,i)=>{if(n)return t(n);if(e.json)try{i=JSON.parse(i.toString())}catch(n){return t(n,r,i)}t(null,r,i)})})),["get","post","put","patch","head","delete"].forEach(e=>{n[e]=((t,r)=>("string"==typeof t&&(t={url:t}),n(Object.assign({method:e.toUpperCase()},t),r)))})}).call(this,d({}).Buffer);var In={};(function(e){"use strict";var t=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];In.decode=function(n){var r,i=0,s=0,o=0;e.isBuffer(n)||(n=new e(n));for(var a=new e(Math.ceil(5*n.length/8)),h=0;h<n.length&&61!==n[h];h++){var c=n[h]-48;if(!(c<t.length))throw new Error("Invalid input - it is not base32 encoded string");s=t[c],i<=3?0==(i=(i+5)%8)?(r|=s,a[o]=r,o++,r=0):r|=255&s<<8-i:(r|=255&s>>>(i=(i+5)%8),a[o]=r,o++,r=255&s<<8-i)}return a.slice(0,o)}}).call(this,d({}).Buffer);var An={};In.encode,An.decode=In.decode;var Rn=function(e,t,n){return 0===e.length?e:t?(n||e.sort(t),function(e,t){for(var n=1,r=e.length,i=e[0],s=e[0],o=1;o<r;++o)if(s=i,t(i=e[o],s)){if(o===n){n++;continue}e[n++]=i}return e.length=n,e}(e,t)):(n||e.sort(),function(e){for(var t=1,n=e.length,r=e[0],i=e[0],s=1;s<n;++s,i=r)if(i=r,(r=e[s])!==i){if(s===t){t++;continue}e[t++]=r}return e.length=t,e}(e))},Bn={};(function(e){function t(t){const n={},r=t.split("magnet:?")[1];let i;return(r&&r.length>=0?r.split("&"):[]).forEach(e=>{const t=e.split("=");if(2!==t.length)return;const r=t[0];let i=t[1];if("dn"===r&&(i=decodeURIComponent(i).replace(/\+/g," ")),"tr"!==r&&"xs"!==r&&"as"!==r&&"ws"!==r||(i=decodeURIComponent(i)),"kt"===r&&(i=decodeURIComponent(i).split("+")),"ix"===r&&(i=Number(i)),n[r])if(Array.isArray(n[r]))n[r].push(i);else{const e=n[r];n[r]=[e,i]}else n[r]=i}),n.xt&&(Array.isArray(n.xt)?n.xt:[n.xt]).forEach(t=>{if(i=t.match(/^urn:btih:(.{40})/))n.infoHash=i[1].toLowerCase();else if(i=t.match(/^urn:btih:(.{32})/)){const t=An.decode(i[1]);n.infoHash=e.from(t,"binary").toString("hex")}}),n.infoHash&&(n.infoHashBuffer=e.from(n.infoHash,"hex")),n.dn&&(n.name=n.dn),n.kt&&(n.keywords=n.kt),"string"==typeof n.tr?n.announce=[n.tr]:Array.isArray(n.tr)?n.announce=n.tr:n.announce=[],n.urlList=[],("string"==typeof n.as||Array.isArray(n.as))&&(n.urlList=n.urlList.concat(n.as)),("string"==typeof n.ws||Array.isArray(n.ws))&&(n.urlList=n.urlList.concat(n.ws)),Rn(n.announce),Rn(n.urlList),n}(Bn=t).decode=t,Bn.encode=function(e){(e=Object.assign({},e)).infoHashBuffer&&(e.xt=`urn:btih:${e.infoHashBuffer.toString("hex")}`),e.infoHash&&(e.xt=`urn:btih:${e.infoHash}`),e.name&&(e.dn=e.name),e.keywords&&(e.kt=e.keywords),e.announce&&(e.tr=e.announce),e.urlList&&(e.ws=e.urlList,delete e.as);let t="magnet:?";return Object.keys(e).filter(e=>2===e.length).forEach((n,r)=>{(Array.isArray(e[n])?e[n]:[e[n]]).forEach((e,i)=>{!(r>0||i>0)||"kt"===n&&0!==i||(t+="&"),"dn"===n&&(e=encodeURIComponent(e).replace(/%20/g,"+")),"tr"!==n&&"xs"!==n&&"as"!==n&&"ws"!==n||(e=encodeURIComponent(e)),"kt"===n&&(e=encodeURIComponent(e)),t+="kt"===n&&i>0?`+${e}`:`${n}=${e}`})}),t}}).call(this,d({}).Buffer);var Ln={};(function(e,t){function n(e){if("string"==typeof e&&/^(stream-)?magnet:/.test(e))return Bn(e);if("string"==typeof e&&(/^[a-f0-9]{40}$/i.test(e)||/^[a-z2-7]{32}$/i.test(e)))return Bn(`magnet:?xt=urn:btih:${e}`);if(t.isBuffer(e)&&20===e.length)return Bn(`magnet:?xt=urn:btih:${e.toString("hex")}`);if(t.isBuffer(e))return function(e){t.isBuffer(e)&&(e=Q.decode(e)),i(e.info,"info"),i(e.info["name.utf-8"]||e.info.name,"info.name"),i(e.info["piece length"],"info['piece length']"),i(e.info.pieces,"info.pieces"),e.info.files?e.info.files.forEach(e=>{i("number"==typeof e.length,"info.files[0].length"),i(e["path.utf-8"]||e.path,"info.files[0].path")}):i("number"==typeof e.info.length,"info.length");const n={info:e.info,infoBuffer:Q.encode(e.info),name:(e.info["name.utf-8"]||e.info.name).toString(),announce:[]};n.infoHash=Nt.sync(n.infoBuffer),n.infoHashBuffer=t.from(n.infoHash,"hex"),void 0!==e.info.private&&(n.private=!!e.info.private),e["creation date"]&&(n.created=new Date(1e3*e["creation date"])),e["created by"]&&(n.createdBy=e["created by"].toString()),t.isBuffer(e.comment)&&(n.comment=e.comment.toString()),Array.isArray(e["announce-list"])&&e["announce-list"].length>0?e["announce-list"].forEach(e=>{e.forEach(e=>{n.announce.push(e.toString())})}):e.announce&&n.announce.push(e.announce.toString()),t.isBuffer(e["url-list"])&&(e["url-list"]=e["url-list"].length>0?[e["url-list"]]:[]),n.urlList=(e["url-list"]||[]).map(e=>e.toString()),Rn(n.announce),Rn(n.urlList);const s=e.info.files||[e.info];n.files=s.map((e,t)=>{const i=[].concat(n.name,e["path.utf-8"]||e.path||[]).map(e=>e.toString());return{path:ut.join.apply(null,[ut.sep].concat(i)).slice(1),name:i[i.length-1],length:e.length,offset:s.slice(0,t).reduce(r,0)}}),n.length=s.reduce(r,0);const o=n.files[n.files.length-1];return n.pieceLength=e.info["piece length"],n.lastPieceLength=(o.offset+o.length)%n.pieceLength||n.pieceLength,n.pieces=function(e){const t=[];for(let n=0;n<e.length;n+=20)t.push(e.slice(n,n+20).toString("hex"));return t}(e.info.pieces),n}(e);if(e&&e.infoHash)return e.infoHash=e.infoHash.toLowerCase(),e.announce||(e.announce=[]),"string"==typeof e.announce&&(e.announce=[e.announce]),e.urlList||(e.urlList=[]),e;throw new Error("Invalid torrent identifier")}function r(e,t){return e+t.length}function i(e,t){if(!e)throw new Error(`Torrent is missing required field: ${t}`)}(Ln=n).remote=function(t,r){let i;if("function"!=typeof r)throw new Error("second argument must be a Function");try{i=n(t)}catch(_i){}function s(e){try{i=n(e)}catch(_i){return r(_i)}i&&i.infoHash?r(null,i):r(new Error("Invalid torrent identifier"))}i&&i.infoHash?e.nextTick(()=>{r(null,i)}):"undefined"!=typeof Blob&&t instanceof Blob?$t(t,(e,t)=>{if(e)return r(new Error(`Error converting Blob: ${e.message}`));s(t)}):"function"==typeof Tn&&/^https?:/.test(t)?Tn.concat({url:t,timeout:3e4,headers:{"user-agent":"WebTorrent (https://webtorrent.io)"}},(e,t,n)=>{if(e)return r(new Error(`Error downloading torrent: ${e.message}`));s(n)}):"function"==typeof wt.readFile&&"string"==typeof t?wt.readFile(t,(e,t)=>{if(e)return r(new Error("Invalid torrent identifier"));s(t)}):e.nextTick(()=>{r(new Error("Invalid torrent identifier"))})},Ln.toMagnetURI=Bn.encode,Ln.toTorrentFile=function(e){const n={info:e.info};return n["announce-list"]=(e.announce||[]).map(e=>(n.announce||(n.announce=e),[e=t.from(e,"utf8")])),n["url-list"]=e.urlList||[],void 0!==e.private&&(n.private=Number(e.private)),e.created&&(n["creation date"]=e.created.getTime()/1e3|0),e.createdBy&&(n["created by"]=e.createdBy),e.comment&&(n.comment=e.comment),Q.encode(n)},t.alloc(0)}).call(this,ue,d({}).Buffer);var Un=function(){if("undefined"==typeof window)return null;var e={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null},On={};(function(e,t){"use strict";var n=H.Buffer,r=t.crypto||t.msCrypto;On=r&&r.getRandomValues?function(t,i){if(t>4294967295)throw new RangeError("requested too many random bytes");var s=n.allocUnsafe(t);if(t>0)if(t>65536)for(var o=0;o<t;o+=65536)r.getRandomValues(s.slice(o,o+65536));else r.getRandomValues(s);return"function"==typeof i?e.nextTick(function(){i(null,s)}):s}:function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this,ue,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Mn={};(function(e){Mn=r;var t=zt("simple-peer"),n=5e3;function r(e){var t=this;if(!(t instanceof r))return new r(e);if(t._id=On(4).toString("hex").slice(0,7),t._debug("new peer %o",e),e=Object.assign({allowHalfOpen:!1},e),it.Duplex.call(t,e),t.channelName=e.initiator?e.channelName||On(20).toString("hex"):null,t.initiator=e.initiator||!1,t.channelConfig=e.channelConfig||r.channelConfig,t.config=Object.assign({},r.config,e.config),t.offerOptions=e.offerOptions||{},t.answerOptions=e.answerOptions||{},t.sdpTransform=e.sdpTransform||function(e){return e},t.streams=e.streams||(e.stream?[e.stream]:[]),t.trickle=void 0===e.trickle||e.trickle,t.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,t.iceCompleteTimeout=e.iceCompleteTimeout||n,t.destroyed=!1,t._connected=!1,t.remoteAddress=void 0,t.remoteFamily=void 0,t.remotePort=void 0,t.localAddress=void 0,t.localFamily=void 0,t.localPort=void 0,t._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:Un(),!t._wrtc)throw"undefined"==typeof window?s("No WebRTC support: Specify `opts.wrtc` option in this environment","ERR_WEBRTC_SUPPORT"):s("No WebRTC support: Not a supported browser","ERR_WEBRTC_SUPPORT");t._pcReady=!1,t._channelReady=!1,t._iceComplete=!1,t._iceCompleteTimer=null,t._channel=null,t._pendingCandidates=[],t._isNegotiating=!t.initiator,t._batchedNegotiation=!1,t._queuedNegotiation=!1,t._sendersAwaitingStable=[],t._senderMap=new Map,t._firstStable=!0,t._closingInterval=null,t._remoteTracks=[],t._remoteStreams=[],t._chunk=null,t._cb=null,t._interval=null;try{t._pc=new t._wrtc.RTCPeerConnection(t.config)}catch(_i){return void setTimeout(()=>t.destroy(_i),0)}t._isReactNativeWebrtc="number"==typeof t._pc._peerConnectionId,t._pc.oniceconnectionstatechange=function(){t._onIceStateChange()},t._pc.onicegatheringstatechange=function(){t._onIceStateChange()},t._pc.onsignalingstatechange=function(){t._onSignalingStateChange()},t._pc.onicecandidate=function(e){t._onIceCandidate(e)},t.initiator?t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)}):t._pc.ondatachannel=function(e){t._setupData(e)},t.streams&&t.streams.forEach(function(e){t.addStream(e)}),t._pc.ontrack=function(e){t._onTrack(e)},t.initiator&&t._needsNegotiation(),t._onFinishBound=function(){t._onFinish()},t.once("finish",t._onFinishBound)}function i(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}function s(e,t){var n=new Error(e);return n.code=t,n}Be(r,it.Duplex),r.WEBRTC_SUPPORT=!!Un(),r.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478?transport=udp"}],sdpSemantics:"unified-plan"},r.channelConfig={},Object.defineProperty(r.prototype,"bufferSize",{get:function(){return this._channel&&this._channel.bufferedAmount||0}}),Object.defineProperty(r.prototype,"connected",{get:function(){return this._connected&&"open"===this._channel.readyState}}),r.prototype.address=function(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}},r.prototype.signal=function(e){var t=this;if(t.destroyed)throw s("cannot signal after peer is destroyed","ERR_SIGNALING");if("string"==typeof e)try{e=JSON.parse(e)}catch(_i){e={}}t._debug("signal()"),e.renegotiate&&t.initiator&&(t._debug("got request to renegotiate"),t._needsNegotiation()),e.transceiverRequest&&t.initiator&&(t._debug("got request for transceiver"),t.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(t._pc.localDescription&&t._pc.localDescription.type&&t._pc.remoteDescription&&t._pc.remoteDescription.type?t._addIceCandidate(e.candidate):t._pendingCandidates.push(e.candidate)),e.sdp&&t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e)).then(function(){t.destroyed||(t._pendingCandidates.forEach(function(e){t._addIceCandidate(e)}),t._pendingCandidates=[],"offer"===t._pc.remoteDescription.type&&t._createAnswer())}).catch(function(e){t.destroy(s(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||t.destroy(s("signal() called with invalid signal data","ERR_SIGNALING"))},r.prototype._addIceCandidate=function(e){var t=this,n=new t._wrtc.RTCIceCandidate(e);t._pc.addIceCandidate(n).catch(function(e){!n.address||n.address.endsWith(".local")?("Ignoring unsupported ICE candidate.",console.warn("Ignoring unsupported ICE candidate.")):t.destroy(s(e,"ERR_ADD_ICE_CANDIDATE"))})},r.prototype.send=function(e){this._channel.send(e)},r.prototype.addTransceiver=function(e,t){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(_i){this.destroy(_i)}else this.emit("signal",{transceiverRequest:{kind:e,init:t}})},r.prototype.addStream=function(e){var t=this;t._debug("addStream()"),e.getTracks().forEach(function(n){t.addTrack(n,e)})},r.prototype.addTrack=function(e,t){this._debug("addTrack()");var n=this._senderMap.get(e)||new Map,r=n.get(t);r?r.removed?this.destroy(s("Track has been removed. You should enable/disable tracks that you want to re-add.","ERR_SENDER_REMOVED")):this.destroy(s("Track has already been added to that stream.","ERR_SENDER_ALREADY_ADDED")):(r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation())},r.prototype.replaceTrack=function(e,t,n){this._debug("replaceTrack()");var r=this._senderMap.get(e),i=r?r.get(n):null;i||this.destroy(s("Cannot replace track that was never added.","ERR_TRACK_NOT_ADDED")),t&&this._senderMap.set(t,r),null!=i.replaceTrack?i.replaceTrack(t):this.destroy(s("replaceTrack is not supported in this browser","ERR_UNSUPPORTED_REPLACETRACK"))},r.prototype.removeTrack=function(e,t){this._debug("removeSender()");var n=this._senderMap.get(e),r=n?n.get(t):null;r||this.destroy(s("Cannot remove track that was never added.","ERR_TRACK_NOT_ADDED"));try{r.removed=!0,this._pc.removeTrack(r)}catch(_i){"NS_ERROR_UNEXPECTED"===_i.name?this._sendersAwaitingStable.push(r):this.destroy(_i)}this._needsNegotiation()},r.prototype.removeStream=function(e){var t=this;t._debug("removeSenders()"),e.getTracks().forEach(function(n){t.removeTrack(n,e)})},r.prototype._needsNegotiation=function(){var e=this;e._debug("_needsNegotiation"),e._batchedNegotiation||(e._batchedNegotiation=!0,setTimeout(function(){e._batchedNegotiation=!1,e._debug("starting batched negotiation"),e.negotiate()},0))},r.prototype.negotiate=function(){var e=this;e.initiator?e._isNegotiating?(e._queuedNegotiation=!0,e._debug("already negotiating, queueing")):(e._debug("start negotiation"),setTimeout(()=>{e._createOffer()},0)):e._isNegotiating||(e._debug("requesting negotiation from initiator"),e.emit("signal",{renegotiate:!0})),e._isNegotiating=!0},r.prototype.destroy=function(e){this._destroy(e,function(){})},r.prototype._destroy=function(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.destroyed=!0,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t()}},r.prototype._setupData=function(e){var t=this;if(!e.channel)return t.destroy(s("Data channel event is missing `channel` property","ERR_DATA_CHANNEL"));t._channel=e.channel,t._channel.binaryType="arraybuffer","number"==typeof t._channel.bufferedAmountLowThreshold&&(t._channel.bufferedAmountLowThreshold=65536),t.channelName=t._channel.label,t._channel.onmessage=function(e){t._onChannelMessage(e)},t._channel.onbufferedamountlow=function(){t._onChannelBufferedAmountLow()},t._channel.onopen=function(){t._onChannelOpen()},t._channel.onclose=function(){t._onChannelClose()},t._channel.onerror=function(e){t.destroy(s(e,"ERR_DATA_CHANNEL"))};var n=!1;t._closingInterval=setInterval(function(){t._channel&&"closing"===t._channel.readyState?(n&&t._onChannelClose(),n=!0):n=!1},5e3)},r.prototype._read=function(){},r.prototype._write=function(e,t,n){if(this.destroyed)return n(s("cannot write after peer is destroyed","ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(_i){return this.destroy(s(_i,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>65536?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n},r.prototype._onFinish=function(){var e=this;function t(){setTimeout(function(){e.destroy()},1e3)}e.destroyed||(e._connected?t():e.once("connect",t))},r.prototype._startIceCompleteTimeout=function(){var e=this;e.destroyed||e._iceCompleteTimer||(e._debug("started iceComplete timeout"),e._iceCompleteTimer=setTimeout(function(){e._iceComplete||(e._iceComplete=!0,e._debug("iceComplete timeout completed"),e.emit("iceTimeout"),e.emit("_iceComplete"))},e.iceCompleteTimeout))},r.prototype._createOffer=function(){var e=this;e.destroyed||e._pc.createOffer(e.offerOptions).then(function(t){function n(){if(!e.destroyed){var n=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:n.type,sdp:n.sdp})}}e.destroyed||(e.trickle||e.allowHalfTrickle||(t.sdp=i(t.sdp)),t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(function(){e._debug("createOffer success"),e.destroyed||(e.trickle||e._iceComplete?n():e.once("_iceComplete",n))}).catch(function(t){e.destroy(s(t,"ERR_SET_LOCAL_DESCRIPTION"))}))}).catch(function(t){e.destroy(s(t,"ERR_CREATE_OFFER"))})},r.prototype._requestMissingTransceivers=function(){var e=this;e._pc.getTransceivers&&e._pc.getTransceivers().forEach(t=>{t.mid||!t.sender.track||t.requested||(t.requested=!0,e.addTransceiver(t.sender.track.kind))})},r.prototype._createAnswer=function(){var e=this;e.destroyed||e._pc.createAnswer(e.answerOptions).then(function(t){function n(){if(!e.destroyed){var n=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:n.type,sdp:n.sdp}),e.initiator||e._requestMissingTransceivers()}}e.destroyed||(e.trickle||e.allowHalfTrickle||(t.sdp=i(t.sdp)),t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(function(){e.destroyed||(e.trickle||e._iceComplete?n():e.once("_iceComplete",n))}).catch(function(t){e.destroy(s(t,"ERR_SET_LOCAL_DESCRIPTION"))}))}).catch(function(t){e.destroy(s(t,"ERR_CREATE_ANSWER"))})},r.prototype._onIceStateChange=function(){if(!this.destroyed){var e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(s("Ice connection failed.","ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(s("Ice connection closed.","ERR_ICE_CONNECTION_CLOSED"))}},r.prototype.getStats=function(e){var t=this;function n(e){return"[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(function(t){Object.assign(e,t)}),e}0===t._pc.getStats.length?t._pc.getStats().then(function(t){var r=[];t.forEach(function(e){r.push(n(e))}),e(null,r)},function(t){e(t)}):t._isReactNativeWebrtc?t._pc.getStats(null,function(t){var r=[];t.forEach(function(e){r.push(n(e))}),e(null,r)},function(t){e(t)}):t._pc.getStats.length>0?t._pc.getStats(function(r){if(!t.destroyed){var i=[];r.result().forEach(function(e){var t={};e.names().forEach(function(n){t[n]=e.stat(n)}),t.id=e.id,t.type=e.type,t.timestamp=e.timestamp,i.push(n(t))}),e(null,i)}},function(t){e(t)}):e(null,[])},r.prototype._maybeReady=function(){var e=this;e._debug("maybeReady pc %s channel %s",e._pcReady,e._channelReady),!e._connected&&!e._connecting&&e._pcReady&&e._channelReady&&(e._connecting=!0,function t(){e.destroyed||e.getStats(function(n,r){if(!e.destroyed){n&&(r=[]);var i={},o={},a={},h=!1;if(r.forEach(function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(o[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(a[e.id]=e)}),r.forEach(function(e){"transport"===e.type&&e.selectedCandidatePairId&&u(a[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&u(e)}),h||Object.keys(a).length&&!Object.keys(o).length){if(e._connecting=!1,e._connected=!0,e._chunk){try{e.send(e._chunk)}catch(n){return e.destroy(s(n,"ERR_DATA_CHANNEL"))}e._chunk=null,e._debug('sent chunk from "write before connect"');var c=e._cb;e._cb=null,c(null)}"number"!=typeof e._channel.bufferedAmountLowThreshold&&(e._interval=setInterval(function(){e._onInterval()},150),e._interval.unref&&e._interval.unref()),e._debug("connect"),e.emit("connect")}else setTimeout(t,100)}function u(t){h=!0;var n=o[t.localCandidateId];n&&(n.ip||n.address)?(e.localAddress=n.ip||n.address,e.localPort=Number(n.port)):n&&n.ipAddress?(e.localAddress=n.ipAddress,e.localPort=Number(n.portNumber)):"string"==typeof t.googLocalAddress&&(n=t.googLocalAddress.split(":"),e.localAddress=n[0],e.localPort=Number(n[1])),e.localAddress&&(e.localFamily=e.localAddress.includes(":")?"IPv6":"IPv4");var r=i[t.remoteCandidateId];r&&(r.ip||r.address)?(e.remoteAddress=r.ip||r.address,e.remotePort=Number(r.port)):r&&r.ipAddress?(e.remoteAddress=r.ipAddress,e.remotePort=Number(r.portNumber)):"string"==typeof t.googRemoteAddress&&(r=t.googRemoteAddress.split(":"),e.remoteAddress=r[0],e.remotePort=Number(r[1])),e.remoteAddress&&(e.remoteFamily=e.remoteAddress.includes(":")?"IPv6":"IPv4"),e._debug("connect local: %s:%s remote: %s:%s",e.localAddress,e.localPort,e.remoteAddress,e.remotePort)}})}())},r.prototype._onInterval=function(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()},r.prototype._onSignalingStateChange=function(){var e=this;e.destroyed||("stable"!==e._pc.signalingState||e._firstStable||(e._isNegotiating=!1,e._debug("flushing sender queue",e._sendersAwaitingStable),e._sendersAwaitingStable.forEach(function(t){e._pc.removeTrack(t),e._queuedNegotiation=!0}),e._sendersAwaitingStable=[],e._queuedNegotiation&&(e._debug("flushing negotiation queue"),e._queuedNegotiation=!1,e._needsNegotiation()),e._debug("negotiate"),e.emit("negotiate")),e._firstStable=!1,e._debug("signalingStateChange %s",e._pc.signalingState),e.emit("signalingStateChange",e._pc.signalingState))},r.prototype._onIceCandidate=function(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())},r.prototype._onChannelMessage=function(t){if(!this.destroyed){var n=t.data;n instanceof ArrayBuffer&&(n=e.from(n)),this.push(n)}},r.prototype._onChannelBufferedAmountLow=function(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);var e=this._cb;this._cb=null,e(null)}},r.prototype._onChannelOpen=function(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())},r.prototype._onChannelClose=function(){this.destroyed||(this._debug("on channel close"),this.destroy())},r.prototype._onTrack=function(e){var t=this;t.destroyed||e.streams.forEach(function(n){t._debug("on track"),t.emit("track",e.track,n),t._remoteTracks.push({track:e.track,stream:n}),t._remoteStreams.some(function(e){return e.id===n.id})||(t._remoteStreams.push(n),setTimeout(function(){t.emit("stream",n)},0))})},r.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],t.apply(null,e)}}).call(this,d({}).Buffer);var Pn,Nn=1,Hn=function(){Nn=Nn+1&65535},jn=function(e){Pn||(Pn=setInterval(Hn,250)).unref&&Pn.unref();var t=4*(e||5),n=[0],r=1,i=Nn-1&65535;return function(e){var s=Nn-i&65535;for(s>t&&(s=t),i=Nn;s--;)r===t&&(r=0),n[r]=n[0===r?t-1:r-1],r++;e&&(n[r-1]+=e);var o=n[r-1],a=n.length<t?0:n[r===t?0:r];return n.length<4?o:4*(o-a)/n.length}},Dn={};const qn=/^\[?([^\]]+)\]?:(\d+)$/;let Fn={},Wn=0;(Dn=function(e){if(1e5===Wn&&Dn.reset(),!Fn[e]){const t=qn.exec(e);if(!t)throw new Error(`invalid addr: ${e}`);Fn[e]=[t[1],Number(t[2])],Wn+=1}return Fn[e]}).reset=function(){Fn={},Wn=0};var zn={exports:{}};function $n(e){let t=e>>3;return e%8!=0&&t++,t}zn.exports=class{constructor(e=0,t){const n=null!=t&&t.grow;this.grow=n&&isFinite(n)&&$n(n)||n||0,this.buffer="number"==typeof e?new Uint8Array($n(e)):e}get(e){const t=e>>3;return t<this.buffer.length&&!!(this.buffer[t]&128>>e%8)}set(e,t=!0){const n=e>>3;if(t){if(this.buffer.length<n+1){const e=Math.max(n+1,Math.min(2*this.buffer.length,this.grow));if(e<=this.grow){const t=new Uint8Array(e);t.set(this.buffer),this.buffer=t}}this.buffer[n]|=128>>e%8}else n<this.buffer.length&&(this.buffer[n]&=~(128>>e%8))}},zn=zn.exports;var Vn=class extends it.Writable{constructor(e,t,n={}){if(super(n),!e||!e.put||!e.get)throw new Error("First argument must be an abstract-chunk-store compliant store");if(!(t=Number(t)))throw new Error("Second argument must be a chunk length");this._blockstream=new st(t,{zeroPadding:!1}),this._outstandingPuts=0;let r=0;this._blockstream.on("data",t=>{this.destroyed||(this._outstandingPuts+=1,e.put(r,t,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),r+=1)}).on("error",e=>{this.destroy(e)})}_write(e,t,n){this._blockstream.write(e,t,n)}_final(e){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?e(null):this._finalCb=e})}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e),this.emit("close"))}},Gn={};(function(e){Gn.DEFAULT_ANNOUNCE_PEERS=50,Gn.binaryToHex=function(t){return"string"!=typeof t&&(t=String(t)),e.from(t,"binary").toString("hex")},Gn.hexToBinary=function(t){return"string"!=typeof t&&(t=String(t)),e.from(t,"hex").toString("binary")},Object.assign(Gn,ne)}).call(this,d({}).Buffer);var Kn={};(function(e,t){const n=zt("simple-websocket"),r="function"!=typeof ne?WebSocket:ne,i=65536;class s extends it.Duplex{constructor(t={}){if("string"==typeof t&&(t={url:t}),super(t=Object.assign({allowHalfOpen:!1},t)),null==t.url&&null==t.socket)throw new Error("Missing required `url` or `socket` option");if(null!=t.url&&null!=t.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=On(4).toString("hex").slice(0,7),this._debug("new websocket: %o",t),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,t.socket)this.url=t.socket.url,this._ws=t.socket;else{this.url=t.url;try{this._ws="function"==typeof ne?new r(t.url,t):new r(t.url)}catch(_i){return void e.nextTick(()=>this.destroy(_i))}}this._ws.binaryType="arraybuffer",this._ws.onopen=(()=>{this._onOpen()}),this._ws.onmessage=(e=>{this._onMessage(e)}),this._ws.onclose=(()=>{this._onClose()}),this._ws.onerror=(()=>{this.destroy(new Error("connection error to "+this.url))}),this._onFinishBound=(()=>{this._onFinish()}),this.once("finish",this._onFinishBound)}send(e){this._ws.send(e)}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const t=this._ws,n=()=>{t.onclose=null};if(t.readyState===r.CLOSED)n();else try{t.onclose=n,t.close()}catch(e){n()}t.onopen=null,t.onmessage=null,t.onerror=(()=>{})}if(this._ws=null,e){if("undefined"!=typeof DOMException&&e instanceof DOMException){const t=e.code;(e=new Error(e.message)).code=t}this.emit("error",e)}this.emit("close"),t()}}_read(){}_write(e,t,n){if(this.destroyed)return n(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(_i){return this.destroy(_i)}"function"!=typeof ne&&this._ws.bufferedAmount>i?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?e():this.once("connect",e)}_onMessage(e){if(this.destroyed)return;let n=e.data;n instanceof ArrayBuffer&&(n=t.from(n)),this.push(n)}_onOpen(){if(!this.connected&&!this.destroyed){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(_i){return this.destroy(_i)}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"function"!=typeof ne&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(!this._cb||!this._ws||this._ws.bufferedAmount>i)return;this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],n.apply(null,e)}}s.WEBSOCKET_SUPPORT=!!r,Kn=s}).call(this,ue,d({}).Buffer);var Yn=class extends l{constructor(e,t){super(),this.client=e,this.announceUrl=t,this.interval=null,this.destroyed=!1}setInterval(e){null==e&&(e=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),e&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},e),this.interval.unref&&this.interval.unref())}},Jn={};const Xn=zt("bittorrent-tracker:websocket-tracker"),Zn={},Qn=1e4,er=18e5,tr=12e4,nr=5e4;class rr extends Yn{constructor(e,t,n){super(e,t),Xn("new websocket tracker %s",t),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(e)});const t=Object.assign({},e,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(t.trackerid=this._trackerId),"stopped"===e.event||"completed"===e.event)this._send(t);else{const n=Math.min(e.numwant,10);this._generateOffers(n,e=>{t.numwant=n,t.offers=e,this._send(t)})}}scrape(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(e)});const t={action:"scrape",info_hash:Array.isArray(e.infoHash)&&e.infoHash.length>0?e.infoHash.map(e=>e.toString("binary")):e.infoHash&&e.infoHash.toString("binary")||this.client._infoHashBinary};this._send(t)}destroy(e=ir){if(this.destroyed)return e(null);this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer);for(const i in this.peers){const e=this.peers[i];clearTimeout(e.trackerTimeout),e.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,Zn[this.announceUrl]&&(Zn[this.announceUrl].consumers-=1),Zn[this.announceUrl].consumers>0)return e();let t=Zn[this.announceUrl];if(delete Zn[this.announceUrl],t.on("error",ir),t.once("close",e),!this.expectingResponse)return r();var n=setTimeout(r,Gn.DESTROY_TIMEOUT);function r(){n&&(clearTimeout(n),n=null),t.removeListener("data",r),t.destroy(),t=null}t.once("data",r)}_openSocket(){this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=(()=>{this._onSocketConnect()}),this._onSocketErrorBound=(e=>{this._onSocketError(e)}),this._onSocketDataBound=(e=>{this._onSocketData(e)}),this._onSocketCloseBound=(()=>{this._onSocketClose()}),this.socket=Zn[this.announceUrl],this.socket?Zn[this.announceUrl].consumers+=1:(this.socket=Zn[this.announceUrl]=new Kn(this.announceUrl),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)),this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(e){if(!this.destroyed){this.expectingResponse=!1;try{e=JSON.parse(e)}catch(_i){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===e.action?this._onAnnounceResponse(e):"scrape"===e.action?this._onScrapeResponse(e):this._onSocketError(new Error(`invalid action in WS response: ${e.action}`))}}_onAnnounceResponse(e){if(e.info_hash!==this.client._infoHashBinary)return void Xn("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,Gn.binaryToHex(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;Xn("received %s from %s for %s",JSON.stringify(e),this.announceUrl,this.client.infoHash);const t=e["failure reason"];if(t)return this.client.emit("warning",new Error(t));const n=e["warning message"];n&&this.client.emit("warning",new Error(n));const r=e.interval||e["min interval"];r&&this.setInterval(1e3*r);const i=e["tracker id"];if(i&&(this._trackerId=i),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:Gn.binaryToHex(e.info_hash)});this.client.emit("update",t)}let s;if(e.offer&&e.peer_id&&(Xn("creating peer (from remote offer)"),(s=this._createPeer()).id=Gn.binaryToHex(e.peer_id),s.once("signal",t=>{const n={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:e.peer_id,answer:t,offer_id:e.offer_id};this._trackerId&&(n.trackerid=this._trackerId),this._send(n)}),s.signal(e.offer),this.client.emit("peer",s)),e.answer&&e.peer_id){const t=Gn.binaryToHex(e.offer_id);(s=this.peers[t])?(s.id=Gn.binaryToHex(e.peer_id),s.signal(e.answer),this.client.emit("peer",s),clearTimeout(s.trackerTimeout),s.trackerTimeout=null,delete this.peers[t]):Xn(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);0!==t.length?t.forEach(t=>{const n=Object.assign(e[t],{announce:this.announceUrl,infoHash:Gn.binaryToHex(t)});this.client.emit("scrape",n)}):this.client.emit("warning",new Error("invalid scrape response"))}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(e){this.destroyed||(this.destroy(),this.client.emit("warning",e),this._startReconnectTimer())}_startReconnectTimer(){const e=Math.floor(Math.random()*tr)+Math.min(Math.pow(2,this.retries)*Qn,er);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},e),this.reconnectTimer.unref&&this.reconnectTimer.unref(),Xn("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);Xn("send %s",t),this.socket.send(t)}_generateOffers(e,t){const n=this,r=[];Xn("generating %s offers",e);for(let o=0;o<e;++o)i();function i(){const e=On(20).toString("hex");Xn("creating peer (from _generateOffers)");const t=n.peers[e]=n._createPeer({initiator:!0});t.once("signal",t=>{r.push({offer:t,offer_id:Gn.hexToBinary(e)}),s()}),t.trackerTimeout=setTimeout(()=>{Xn("tracker timeout: destroying peer"),t.trackerTimeout=null,delete n.peers[e],t.destroy()},nr),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function s(){r.length===e&&(Xn("generated %s offers",e),t(r))}s()}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const n=new Mn(e);return n.once("error",r),n.once("connect",function e(){n.removeListener("error",r),n.removeListener("connect",e)}),n;function r(e){t.client.emit("warning",new Error(`Connection error: ${e.message}`)),n.destroy()}}}function ir(){}rr.prototype.DEFAULT_ANNOUNCE_INTERVAL=3e4,rr._socketPool=Zn,Jn=rr;var sr={};(function(e,t){const n=zt("bittorrent-tracker:client");class r extends l{constructor(r={}){if(super(),!r.peerId)throw new Error("Option `peerId` is required");if(!r.infoHash)throw new Error("Option `infoHash` is required");if(!r.announce)throw new Error("Option `announce` is required");if(!e.browser&&!r.port)throw new Error("Option `port` is required");this.peerId="string"==typeof r.peerId?r.peerId:r.peerId.toString("hex"),this._peerIdBuffer=t.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof r.infoHash?r.infoHash.toLowerCase():r.infoHash.toString("hex"),this._infoHashBuffer=t.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),n("new client %s",this.infoHash),this.destroyed=!1,this._port=r.port,this._getAnnounceOpts=r.getAnnounceOpts,this._rtcConfig=r.rtcConfig,this._userAgent=r.userAgent,this._wrtc="function"==typeof r.wrtc?r.wrtc():r.wrtc;let i="string"==typeof r.announce?[r.announce]:null==r.announce?[]:r.announce;i=i.map(e=>("/"===(e=e.toString())[e.length-1]&&(e=e.substring(0,e.length-1)),e)),i=Rn(i);const s=!1!==this._wrtc&&(!!this._wrtc||Mn.WEBRTC_SUPPORT),o=t=>{e.nextTick(()=>{this.emit("warning",t)})};this._trackers=i.map(e=>{let t;try{t=new URL(e)}catch(_i){return o(new Error(`Invalid tracker URL: ${e}`)),null}const n=t.port;if(n<0||n>65535)return o(new Error(`Invalid tracker port: ${e}`)),null;const r=t.protocol;return"http:"!==r&&"https:"!==r||"function"!=typeof ne?"udp:"===r&&"function"==typeof ne?new ne(this,e):"ws:"!==r&&"wss:"!==r||!s?(o(new Error(`Unsupported tracker protocol: ${e}`)),null):"ws:"===r&&"undefined"!=typeof window&&"https:"===window.location.protocol?(o(new Error(`Unsupported tracker protocol: ${e}`)),null):new Jn(this,e):new ne(this,e)}).filter(Boolean)}start(e){n("send `start`"),(e=this._defaultAnnounceOpts(e)).event="started",this._announce(e),this._trackers.forEach(e=>{e.setInterval()})}stop(e){n("send `stop`"),(e=this._defaultAnnounceOpts(e)).event="stopped",this._announce(e)}complete(e){n("send `complete`"),e||(e={}),(e=this._defaultAnnounceOpts(e)).event="completed",this._announce(e)}update(e){n("send `update`"),(e=this._defaultAnnounceOpts(e)).event&&delete e.event,this._announce(e)}_announce(e){this._trackers.forEach(t=>{t.announce(e)})}scrape(e){n("send `scrape`"),e||(e={}),this._trackers.forEach(t=>{t.scrape(e)})}setInterval(e){n("setInterval %d",e),this._trackers.forEach(t=>{t.setInterval(e)})}destroy(e){if(this.destroyed)return;this.destroyed=!0,n("destroy");const t=this._trackers.map(e=>t=>{e.destroy(t)});Ut(t,e),this._trackers=[],this._getAnnounceOpts=null}_defaultAnnounceOpts(e={}){return null==e.numwant&&(e.numwant=Gn.DEFAULT_ANNOUNCE_PEERS),null==e.uploaded&&(e.uploaded=0),null==e.downloaded&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}r.scrape=((e,n)=>{if(n=Rt(n),!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");const i=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:t.from("01234567890123456789"),port:6881}),s=new r(i);s.once("error",n),s.once("warning",n);let o=Array.isArray(e.infoHash)?e.infoHash.length:1;const a={};return s.on("scrape",e=>{if(o-=1,a[e.infoHash]=e,0===o){s.destroy();const e=Object.keys(a);1===e.length?n(null,a[e[0]]):n(null,a)}}),e.infoHash=Array.isArray(e.infoHash)?e.infoHash.map(e=>t.from(e,"hex")):t.from(e.infoHash,"hex"),s.scrape({infoHash:e.infoHash}),s}),sr=r}).call(this,ue,d({}).Buffer);var or={};(function(e){const t=zt("torrent-discovery"),n=l.EventEmitter;or=class extends n{constructor(t){if(super(),!t.peerId)throw new Error("Option `peerId` is required");if(!t.infoHash)throw new Error("Option `infoHash` is required");if(!e.browser&&!t.port)throw new Error("Option `port` is required");this.peerId="string"==typeof t.peerId?t.peerId:t.peerId.toString("hex"),this.infoHash="string"==typeof t.infoHash?t.infoHash.toLowerCase():t.infoHash.toString("hex"),this._port=t.port,this._userAgent=t.userAgent,this.destroyed=!1,this._announce=t.announce||[],this._intervalMs=t.intervalMs||9e5,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=(e=>{this.emit("warning",e)}),this._onError=(e=>{this.emit("error",e)}),this._onDHTPeer=((e,t)=>{t.toString("hex")===this.infoHash&&this.emit("peer",`${e.host}:${e.port}`,"dht")}),this._onTrackerPeer=(e=>{this.emit("peer",e,"tracker")}),this._onTrackerAnnounce=(()=>{this.emit("trackerAnnounce")});const n=(e,t)=>{const n=new ne(t);return n.on("warning",this._onWarning),n.on("error",this._onError),n.listen(e),this._internalDHT=!0,n};!1===t.tracker?this.tracker=null:t.tracker&&"object"==typeof t.tracker?(this._trackerOpts=Object.assign({},t.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),!1===t.dht||"function"!=typeof ne?this.dht=null:t.dht&&"function"==typeof t.dht.addNode?this.dht=t.dht:t.dht&&"object"==typeof t.dht?this.dht=n(t.dhtPort,t.dht):this.dht=n(t.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce())}updatePort(e){e!==this._port&&(this._port=e,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(e){this.tracker&&this.tracker.complete(e)}destroy(e){if(this.destroyed)return;this.destroyed=!0,clearTimeout(this._dhtTimeout);const t=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),t.push(e=>{this.tracker.destroy(e)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),t.push(e=>{this.dht.destroy(e)})),Ut(t,e),this.dht=null,this.tracker=null,this._announce=null}_createTracker(){const e=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),t=new sr(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onTrackerPeer),t.on("update",this._onTrackerAnnounce),t.setInterval(this._intervalMs),t.start(),t}_dhtAnnounce(){this._dhtAnnouncing||(t("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,e=>{this._dhtAnnouncing=!1,t("dht announce complete"),e&&this.emit("warning",e),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+Math.floor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}}}).call(this,ue);var ar={};(function(e){function t(e,n){if(!(this instanceof t))return new t(e,n);if(n||(n={}),this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=Number(n.length)||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1)}function n(t,n,r){e.nextTick(function(){t&&t(n,r)})}ar=t,t.prototype.put=function(e,t,r){if(this.closed)return n(r,new Error("Storage is closed"));var i=e===this.lastChunkIndex;return i&&t.length!==this.lastChunkLength?n(r,new Error("Last chunk length must be "+this.lastChunkLength)):i||t.length===this.chunkLength?(this.chunks[e]=t,void n(r,null)):n(r,new Error("Chunk length must be "+this.chunkLength))},t.prototype.get=function(e,t,r){if("function"==typeof t)return this.get(e,null,t);if(this.closed)return n(r,new Error("Storage is closed"));var i=this.chunks[e];if(!i){var s=new Error("Chunk not found");return s.notFound=!0,n(r,s)}if(!t)return n(r,null,i);var o=t.offset||0,a=t.length||i.length-o;n(r,null,i.slice(o,a+o))},t.prototype.close=t.prototype.destroy=function(e){if(this.closed)return n(e,new Error("Storage is closed"));this.closed=!0,this.chunks=null,n(e,null)}}).call(this,ue);var hr={};(function(e){hr=class{constructor(e){if(this.store=e,this.chunkLength=e.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(e,t,n){this.mem[e]=t,this.store.put(e,t,t=>{this.mem[e]=null,n&&n(t)})}get(t,n,r){if("function"==typeof n)return this.get(t,null,n);const i=n&&n.offset||0,s=n&&n.length&&i+n.length,o=this.mem[t];if(o)return function(t,n,r){e.nextTick(()=>{t&&t(null,r)})}(r,0,n?o.slice(i,s):o);this.store.get(t,n,r)}close(e){this.store.close(e)}destroy(e){this.store.destroy(e)}}}).call(this,ue);var cr={};(function(e){cr=function(t,n,r){if("number"!=typeof n)throw new Error("second argument must be a Number");var i,s,o,a,h,c=!0;function u(t){function n(){r&&r(t,i),r=null}c?e.nextTick(n):n()}function d(e,n,r){if(i[e]=r,n&&(h=!0),0==--o||n)u(n);else if(!h&&l<s){var c;a?(c=a[l],l+=1,t[c](function(e,t){d(c,e,t)})):(c=l,l+=1,t[c](function(e,t){d(c,e,t)}))}}Array.isArray(t)?(i=[],o=s=t.length):(a=Object.keys(t),i={},o=s=a.length);var l=n;o?a?a.some(function(e,r){if(t[e](function(t,n){d(e,t,n)}),r===n-1)return!0}):t.some(function(e,t){if(e(function(e,n){d(t,e,n)}),t===n-1)return!0}):u(null),c=!1}}).call(this,ue);var ur={};(function(e){const t=16384;class n{constructor(e){this.length=e,this.missing=e,this.sources=null,this._chunks=Math.ceil(e/t),this._remainder=e%t||t,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(e){return e===this._chunks-1?this._remainder:t}chunkLengthRemaining(e){return this.length-e*t}chunkOffset(e){return e*t}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations<this._chunks?this._reservations++:-1:-1}reserveRemaining(){if(!this.init())return-1;if(this._reservations<this._chunks){const e=this._reservations;return this._reservations=this._chunks,e}return-1}cancel(e){this.init()&&this._cancellations.push(e)}cancelRemaining(e){this.init()&&(this._reservations=e)}get(e){return this.init()?this._buffer[e]:null}set(e,n,r){if(!this.init())return!1;const i=n.length,s=Math.ceil(i/t);for(let o=0;o<s;o++)if(!this._buffer[e+o]){const i=o*t,s=n.slice(i,i+t);this._buffered++,this._buffer[e+o]=s,this.missing-=s.length,this.sources.includes(r)||this.sources.push(r)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const t=e.concat(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,t}init(){return!(this._flushed||!this._buffer&&(this._buffer=new Array(this._chunks),this._cancellations=[],this.sources=[],0))}}Object.defineProperty(n,"BLOCK_LENGTH",{value:t}),ur=n}).call(this,d({}).Buffer);var dr=function(){},lr=function(e,t,n){if("function"==typeof t)return lr(e,null,t);t||(t={}),n=Rt(n||dr);var r=e._writableState,i=e._readableState,s=t.readable||!1!==t.readable&&e.readable,o=t.writable||!1!==t.writable&&e.writable,a=function(){e.writable||h()},h=function(){o=!1,s||n.call(e)},c=function(){s=!1,o||n.call(e)},u=function(t){n.call(e,t?new Error("exited with error code: "+t):null)},d=function(t){n.call(e,t)},l=function(){return(!s||i&&i.ended)&&(!o||r&&r.ended)?void 0:n.call(e,new Error("premature close"))},f=function(){e.req.on("finish",h)};return function(e){return e.setHeader&&"function"==typeof e.abort}(e)?(e.on("complete",h),e.on("abort",l),e.req?f():e.on("request",f)):o&&!r&&(e.on("end",a),e.on("close",a)),function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length}(e)&&e.on("exit",u),e.on("end",c),e.on("finish",h),!1!==t.error&&e.on("error",d),e.on("close",l),function(){e.removeListener("complete",h),e.removeListener("abort",l),e.removeListener("request",f),e.req&&e.req.removeListener("finish",h),e.removeListener("end",a),e.removeListener("close",a),e.removeListener("finish",h),e.removeListener("exit",u),e.removeListener("end",c),e.removeListener("error",d),e.removeListener("close",l)}},fr=lr,pr={};(function(e){var t=function(){},n=/^v?\.0/.test(e.version),r=function(e){return"function"==typeof e},i=function(e){e()},s=function(e,t){return e.pipe(t)};pr=function(){var e,o=Array.prototype.slice.call(arguments),a=r(o[o.length-1]||t)&&o.pop()||t;if(Array.isArray(o[0])&&(o=o[0]),o.length<2)throw new Error("pump requires two streams per minimum");var h=o.map(function(s,c){var u=c<o.length-1;return function(e,i,s,o){o=Rt(o);var a=!1;e.on("close",function(){a=!0}),fr(e,{readable:i,writable:s},function(e){if(e)return o(e);a=!0,o()});var h=!1;return function(i){if(!a&&!h)return h=!0,function(e){return!!n&&!!ne&&(e instanceof(ne.ReadStream||t)||e instanceof(ne.WriteStream||t))&&r(e.close)}(e)?e.close(t):function(e){return e.setHeader&&r(e.abort)}(e)?e.abort():r(e.destroy)?e.destroy():void o(i||new Error("stream was destroyed"))}}(s,u,c>0,function(t){e||(e=t),t&&h.forEach(i),u||(h.forEach(i),a(e))})});return o.reduce(s)}}).call(this,ue);var gr={};(function(e){const{EventEmitter:t}=l,n=zt("ut_metadata"),r=1e7,i=1e3,s=16384;gr=(o=>{class a extends t{constructor(t){super(),this._wire=t,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new zn(0,{grow:i}),e.isBuffer(o)&&this.setMetadata(o)}onHandshake(e,t,n){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||r<e.metadata_size||e.metadata_size<=0?this.emit("warning",new Error("Peer gave invalid metadata size")):(this._metadataSize=e.metadata_size,this._numPieces=Math.ceil(this._metadataSize/s),this._remainingRejects=2*this._numPieces,void(this._fetching&&this._requestPieces())):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(e){let t,n;try{const r=e.toString(),i=r.indexOf("ee")+2;t=Q.decode(r.substring(0,i)),n=e.slice(i)}catch(_i){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,n,t.total_size);break;case 2:this._onReject(t.piece)}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(e){if(this._metadataComplete)return!0;n("set metadata");try{const t=Q.decode(e).info;t&&(e=Q.encode(t))}catch(_i){}return!(this._infoHash&&this._infoHash!==Nt.sync(e)||(this.cancel(),this.metadata=e,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",Q.encode({info:Q.decode(this.metadata)})),0))}_send(t,n){let r=Q.encode(t);e.isBuffer(n)&&(r=e.concat([r,n])),this._wire.extended("ut_metadata",r)}_request(e){this._send({msg_type:0,piece:e})}_data(e,t,n){const r={msg_type:1,piece:e};"number"==typeof n&&(r.total_size=n),this._send(r,t)}_reject(e){this._send({msg_type:2,piece:e})}_onRequest(e){if(!this._metadataComplete)return void this._reject(e);const t=e*s;let n=t+s;n>this._metadataSize&&(n=this._metadataSize);const r=this.metadata.slice(t,n);this._data(e,r,this._metadataSize)}_onData(e,t,n){t.length>s||(t.copy(this.metadata,e*s),this._bitfield.set(e),this._checkDone())}_onReject(e){this._remainingRejects>0&&this._fetching?(this._request(e),this._remainingRejects-=1):this.emit("warning",new Error('Peer sent "reject" too much'))}_requestPieces(){this.metadata=e.alloc(this._metadataSize);for(let e=0;e<this._numPieces;e++)this._request(e)}_checkDone(){let e=!0;for(let t=0;t<this._numPieces;t++)if(!this._bitfield.get(t)){e=!1;break}e&&(this.setMetadata(this.metadata)||this._failedMetadata())}_failedMetadata(){this._bitfield=new zn(0,{grow:i}),this._remainingRejects-=this._numPieces,this._remainingRejects>0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return a.prototype.name="ut_metadata",a})}).call(this,d({}).Buffer);var mr={parse:function(e){var t=e.split(",").map(function(e){return function(e){if(/^-?\d+$/.test(e))return parseInt(e,10);var t;if(t=e.match(/^(-?\d+)(-|\.\.\.?|\u2025|\u2026|\u22EF)(-?\d+)$/)){var n=t[1],r=t[2],i=t[3];if(n&&i){var s=[],o=(n=parseInt(n))<(i=parseInt(i))?1:-1;"-"!=r&&".."!=r&&"\u2025"!=r||(i+=o);for(var a=n;a!=i;a+=o)s.push(a);return s}}return[]}(e)});return 0===t.length?[]:1===t.length?Array.isArray(t[0])?t[0]:t:t.reduce(function(e,t){return Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]),e.concat(t)})}},_r=function(e){for(var t=0,n=e.length;t<n;++t)if(e.charCodeAt(t)>127)return!1;return!0},yr=d({}).Buffer,br=Er,wr="undefined"!=typeof window&&window.MediaSource,vr=60;function Er(e,t){var n=this;if(!(n instanceof Er))return new Er(e,t);if(!wr)throw new Error("web browser lacks MediaSource support");t||(t={}),n._debug=t.debug,n._bufferDuration=t.bufferDuration||vr,n._elem=e,n._mediaSource=new wr,n._streams=[],n.detailedError=null,n._errorHandler=function(){n._elem.removeEventListener("error",n._errorHandler),n._streams.slice().forEach(function(e){e.destroy(n._elem.error)})},n._elem.addEventListener("error",n._errorHandler),n._elem.src=window.URL.createObjectURL(n._mediaSource)}function kr(e,t){var n=this;if(it.Writable.call(n),n._wrapper=e,n._elem=e._elem,n._mediaSource=e._mediaSource,n._allStreams=e._streams,n._allStreams.push(n),n._bufferDuration=e._bufferDuration,n._sourceBuffer=null,n._debugBuffers=[],n._openHandler=function(){n._onSourceOpen()},n._flowHandler=function(){n._flow()},n._errorHandler=function(e){n.destroyed||n.emit("error",e)},"string"==typeof t)n._type=t,"open"===n._mediaSource.readyState?n._createSourceBuffer():n._mediaSource.addEventListener("sourceopen",n._openHandler);else if(null===t._sourceBuffer)t.destroy(),n._type=t._type,n._mediaSource.addEventListener("sourceopen",n._openHandler);else{if(!t._sourceBuffer)throw new Error("The argument to MediaElementWrapper.createWriteStream must be a string or a previous stream returned from that function");t.destroy(),n._type=t._type,n._sourceBuffer=t._sourceBuffer,n._debugBuffers=t._debugBuffers,n._sourceBuffer.addEventListener("updateend",n._flowHandler),n._sourceBuffer.addEventListener("error",n._errorHandler)}n._elem.addEventListener("timeupdate",n._flowHandler),n.on("error",function(e){n._wrapper.error(e)}),n.on("finish",function(){if(!n.destroyed&&(n._finished=!0,n._allStreams.every(function(e){return e._finished}))){n._wrapper._dumpDebugData();try{n._mediaSource.endOfStream()}catch(_i){}}})}Er.prototype.createWriteStream=function(e){return new kr(this,e)},Er.prototype.error=function(e){this.detailedError||(this.detailedError=e),this._dumpDebugData();try{this._mediaSource.endOfStream("decode")}catch(e){}try{window.URL.revokeObjectURL(this._elem.src)}catch(e){}},Er.prototype._dumpDebugData=function(){this._debug&&(this._debug=!1,this._streams.forEach(function(e,t){var n,r,i;n=e._debugBuffers,r="mediasource-stream-"+t,(i=document.createElement("a")).href=window.URL.createObjectURL(new window.Blob(n)),i.download=r,i.click()}))},Be(kr,it.Writable),kr.prototype._onSourceOpen=function(){this.destroyed||(this._mediaSource.removeEventListener("sourceopen",this._openHandler),this._createSourceBuffer())},kr.prototype.destroy=function(e){this.destroyed||(this.destroyed=!0,this._allStreams.splice(this._allStreams.indexOf(this),1),this._mediaSource.removeEventListener("sourceopen",this._openHandler),this._elem.removeEventListener("timeupdate",this._flowHandler),this._sourceBuffer&&(this._sourceBuffer.removeEventListener("updateend",this._flowHandler),this._sourceBuffer.removeEventListener("error",this._errorHandler),"open"===this._mediaSource.readyState&&this._sourceBuffer.abort()),e&&this.emit("error",e),this.emit("close"))},kr.prototype._createSourceBuffer=function(){if(!this.destroyed)if(wr.isTypeSupported(this._type)){if(this._sourceBuffer=this._mediaSource.addSourceBuffer(this._type),this._sourceBuffer.addEventListener("updateend",this._flowHandler),this._sourceBuffer.addEventListener("error",this._errorHandler),this._cb){var e=this._cb;this._cb=null,e()}}else this.destroy(new Error("The provided type is not supported"))},kr.prototype._write=function(e,t,n){var r=this;if(!r.destroyed)if(r._sourceBuffer){if(r._sourceBuffer.updating)return n(new Error("Cannot append buffer while source buffer updating"));var i=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(yr.isBuffer(e)){for(var t=new Uint8Array(e.length),n=e.length,r=0;r<n;r++)t[r]=e[r];return t.buffer}throw new Error("Argument must be a Buffer")}(e);r._wrapper._debug&&r._debugBuffers.push(i);try{r._sourceBuffer.appendBuffer(i)}catch(_i){return void r.destroy(_i)}r._cb=n}else r._cb=function(i){if(i)return n(i);r._write(e,t,n)}},kr.prototype._flow=function(){if(!this.destroyed&&this._sourceBuffer&&!this._sourceBuffer.updating&&!("open"===this._mediaSource.readyState&&this._getBufferDuration()>this._bufferDuration)&&this._cb){var e=this._cb;this._cb=null,e()}},kr.prototype._getBufferDuration=function(){for(var e=this._sourceBuffer.buffered,t=this._elem.currentTime,n=-1,r=0;r<e.length;r++){var i=e.start(r),s=e.end(r)+0;if(i>t)break;(n>=0||t<=s)&&(n=s)}var o=n-t;return o<0&&(o=0),o};var Sr=function e(t,n,r){if("function"==typeof n)return e(t,null,n);!function e(t,n,r){if("function"==typeof n)return e(t,null,n);r=Rt(r);var i=[];t.on("data",function(e){i.push(e)}).on("end",function(){var e=n?new Blob(i,{type:n}):new Blob(i);r(null,e)}).on("error",r)}(t,n,function(e,t){if(e)return r(e);var n=URL.createObjectURL(t);r(null,n)})},Cr={};(function(e){var t=function(){try{if(!e.isEncoding("latin1"))return!1;var t=e.alloc?e.alloc(4):new e(4);return t.fill("ab","ucs2"),"61006200"===t.toString("hex")}catch(n){return!1}}();function n(e,t,n,r){if(n<0||r>e.length)throw new RangeError("Out of range index");return n>>>=0,(r=void 0===r?e.length:r>>>0)>n&&e.fill(t,n,r),e}Cr=function(r,i,s,o,a){if(t)return r.fill(i,s,o,a);if("number"==typeof i)return n(r,i,s,o);if("string"==typeof i){if("string"==typeof s?(a=s,s=0,o=r.length):"string"==typeof o&&(a=o,o=r.length),void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("latin1"===a&&(a="binary"),"string"==typeof a&&!e.isEncoding(a))throw new TypeError("Unknown encoding: "+a);if(""===i)return n(r,0,s,o);if(function(e){return 1===e.length&&e.charCodeAt(0)<256}(i))return n(r,i.charCodeAt(0),s,o);i=new e(i,a)}return e.isBuffer(i)?function(e,t,n,r){if(n<0||r>e.length)throw new RangeError("Out of range index");if(r<=n)return e;n>>>=0,r=void 0===r?e.length:r>>>0;for(var i=n,s=t.length;i<=r-s;)t.copy(e,i),i+=s;return i!==r&&t.copy(e,i,0,r-i),e}(r,i,s,o):n(r,0,s,o)}}).call(this,d({}).Buffer);var xr={};(function(e){xr=function(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative');return e.allocUnsafe?e.allocUnsafe(t):new e(t)}}).call(this,d({}).Buffer);var Tr={};(function(e){Tr=function(t,n,r){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative');if(e.alloc)return e.alloc(t,n,r);var i=xr(t);return 0===t?i:void 0===n?Cr(i,0):("string"!=typeof r&&(r=void 0),Cr(i,n,r))}}).call(this,d({}).Buffer);var Ir={},Ar=Math.pow(2,32);Ir.encode=function(e,t,n){t||(t=Tr(8)),n||(n=0);var r=Math.floor(e/Ar),i=e-r*Ar;return t.writeUInt32BE(r,n),t.writeUInt32BE(i,n+4),t},Ir.decode=function(e,t){t||(t=0);var n=e.readUInt32BE(t),r=e.readUInt32BE(t+4);return n*Ar+r},Ir.encode.bytes=8,Ir.decode.bytes=8;var Rr={};(function(e){var t={3:"ESDescriptor",4:"DecoderConfigDescriptor",5:"DecoderSpecificInfo",6:"SLConfigDescriptor"};Rr.Descriptor={},Rr.Descriptor.decode=function(n,r,i){var s,o,a=n.readUInt8(r),h=r+1,c=0;do{c=c<<7|127&(s=n.readUInt8(h++))}while(128&s);var u=t[a];return(o=Rr[u]?Rr[u].decode(n,h,i):{buffer:e.from(n.slice(h,h+c))}).tag=a,o.tagName=u,o.length=h-r+c,o.contentsLen=c,o},Rr.DescriptorArray={},Rr.DescriptorArray.decode=function(e,n,r){for(var i=n,s={};i+2<=r;){var o=Rr.Descriptor.decode(e,i,r);i+=o.length,s[t[o.tag]||"Descriptor"+o.tag]=o}return s},Rr.ESDescriptor={},Rr.ESDescriptor.decode=function(e,t,n){var r=e.readUInt8(t+2),i=t+3;return 128&r&&(i+=2),64&r&&(i+=e.readUInt8(i)+1),32&r&&(i+=2),Rr.DescriptorArray.decode(e,i,n)},Rr.DecoderConfigDescriptor={},Rr.DecoderConfigDescriptor.decode=function(e,t,n){var r=e.readUInt8(t),i=Rr.DescriptorArray.decode(e,t+13,n);return i.oti=r,i}}).call(this,d({}).Buffer);var Br={};(function(e){var n=t({}),r=e.alloc(0);class i extends it.PassThrough{constructor(e){super(),this._parent=e,this.destroyed=!1}destroy(e){this.destroyed||(this.destroyed=!0,this._parent.destroy(e),e&&this.emit("error",e),this.emit("close"))}}Br=class extends it.Writable{constructor(e){super(e),this.destroyed=!1,this._pending=0,this._missing=0,this._ignoreEmpty=!1,this._buf=null,this._str=null,this._cb=null,this._ondrain=null,this._writeBuffer=null,this._writeCb=null,this._ondrain=null,this._kick()}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e),this.emit("close"))}_write(e,t,n){if(!this.destroyed){for(var i=!this._str||!this._str._writableState.needDrain;e.length&&!this.destroyed;){if(!this._missing&&!this._ignoreEmpty)return this._writeBuffer=e,void(this._writeCb=n);var s=e.length<this._missing?e.length:this._missing;if(this._buf?e.copy(this._buf,this._buf.length-this._missing):this._str&&(i=this._str.write(s===e.length?e:e.slice(0,s))),this._missing-=s,!this._missing){var o=this._buf,a=this._cb,h=this._str;this._buf=this._cb=this._str=this._ondrain=null,i=!0,this._ignoreEmpty=!1,h&&h.end(),a&&a(o)}e=s===e.length?r:e.slice(s)}if(this._pending&&!this._missing)return this._writeBuffer=e,void(this._writeCb=n);i?n():this._ondrain(n)}}_buffer(t,n){this._missing=t,this._buf=e.alloc(t),this._cb=n}_stream(e,t){return this._missing=e,this._str=new i(this),this._ondrain=(n=this._str,r="drain",s=null,n.on(r,function(e){if(s){var t=s;s=null,t(e)}}),function(e){s=e}),this._pending++,this._str.on("end",()=>{this._pending--,this._kick()}),this._cb=t,this._str;var n,r,s}_readBox(){const t=(r,i)=>{this._buffer(r,r=>{i=i?e.concat([i,r]):r;var s=n.readHeaders(i);"number"==typeof s?t(s-i.length,i):(this._pending++,this._headers=s,this.emit("box",s))})};t(8)}stream(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var e=this._headers;return this._headers=null,this._stream(e.contentLen,null)}decode(e){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var t=this._headers;this._headers=null,this._buffer(t.contentLen,r=>{var i=n.decodeWithoutHeaders(t,r);e(i),this._pending--,this._kick()})}ignore(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var e=this._headers;this._headers=null,this._missing=e.contentLen,0===this._missing&&(this._ignoreEmpty=!0),this._cb=(()=>{this._pending--,this._kick()})}_kick(){if(!this._pending&&(this._buf||this._str||this._readBox(),this._writeBuffer)){var e=this._writeCb,t=this._writeBuffer;this._writeBuffer=null,this._writeCb=null,this._write(t,null,e)}}}}).call(this,d({}).Buffer);var Lr={};(function(e,n){var r=t({});function i(){}class s extends it.PassThrough{constructor(e){super(),this._parent=e,this.destroyed=!1}destroy(e){this.destroyed||(this.destroyed=!0,this._parent.destroy(e),e&&this.emit("error",e),this.emit("close"))}}Lr=class extends it.Readable{constructor(e){super(e),this.destroyed=!1,this._finalized=!1,this._reading=!1,this._stream=null,this._drain=null,this._want=!1,this._onreadable=(()=>{this._want&&(this._want=!1,this._read())}),this._onend=(()=>{this._stream=null})}mdat(e,t){this.mediaData(e,t)}mediaData(e,t){var n=new s(this);return this.box({type:"mdat",contentLength:e,encodeBufferLen:8,stream:n},t),n}box(t,s){if(s||(s=i),this.destroyed)return s(new Error("Encoder is destroyed"));var o;if(t.encodeBufferLen&&(o=n.alloc(t.encodeBufferLen)),t.stream)t.buffer=null,o=r.encode(t,o),this.push(o),this._stream=t.stream,this._stream.on("readable",this._onreadable),this._stream.on("end",this._onend),this._stream.on("end",s),this._forward();else{if(o=r.encode(t,o),this.push(o))return e.nextTick(s);this._drain=s}}destroy(e){if(!this.destroyed){if(this.destroyed=!0,this._stream&&this._stream.destroy&&this._stream.destroy(),this._stream=null,this._drain){var t=this._drain;this._drain=null,t(e)}e&&this.emit("error",e),this.emit("close")}}finalize(){this._finalized=!0,this._stream||this._drain||this.push(null)}_forward(){if(this._stream)for(;!this.destroyed;){var e=this._stream.read();if(!e)return void(this._want=!!this._stream);if(!this.push(e))return}}_read(){if(!this._reading&&!this.destroyed){if(this._reading=!0,this._stream&&this._forward(),this._drain){var e=this._drain;this._drain=null,e()}this._reading=!1,this._finalized&&this.push(null)}}}}).call(this,ue,d({}).Buffer);var Ur={decode:e=>new Br(e),encode:e=>new Lr(e)};const{Writable:Or,PassThrough:Mr}=it;var Pr=class extends Or{constructor(e,t={}){super(t),this.destroyed=!1,this._queue=[],this._position=e||0,this._cb=null,this._buffer=null,this._out=null}_write(e,t,n){let r=!0;for(;;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=e,void(this._cb=n);this._buffer=null;var i=this._queue[0];const t=Math.max(i.start-this._position,0),s=i.end-this._position;if(t>=e.length)return this._position+=e.length,n(null);let o;if(s>e.length){this._position+=e.length,o=0===t?e:e.slice(t),r=i.stream.write(o)&&r;break}this._position+=s,o=0===t&&s===e.length?e:e.slice(t,s),r=i.stream.write(o)&&r,i.last&&i.stream.end(),e=e.slice(s),this._queue.shift()}r?n(null):i.stream.once("drain",n.bind(null,null))}slice(e){if(this.destroyed)return null;Array.isArray(e)||(e=[e]);const t=new Mr;return e.forEach((n,r)=>{this._queue.push({start:n.start,end:n.end,stream:t,last:r===e.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),t}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e))}},Nr={};(function(e){const n=t({});class r{constructor(e,t){this._entries=e,this._countName=t||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}Nr=class extends l{constructor(e){super(),this._tracks=[],this._file=e,this._decoder=null,this._findMoov(0)}_findMoov(e){this._decoder&&this._decoder.destroy();let t=0;this._decoder=Ur.decode();const n=this._file.createReadStream({start:e});n.pipe(this._decoder);const r=i=>{"moov"===i.type?(this._decoder.removeListener("box",r),this._decoder.decode(e=>{n.destroy();try{this._processMoov(e)}catch(_i){_i.message=`Cannot parse mp4 file: ${_i.message}`,this.emit("error",_i)}})):i.length<4096?(t+=i.length,this._decoder.ignore()):(this._decoder.removeListener("box",r),t+=i.length,n.destroy(),this._decoder.destroy(),this._findMoov(e+t))};this._decoder.on("box",r)}_processMoov(t){const i=t.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let e=0;e<i.length;e++){const n=i[e],o=n.mdia.minf.stbl,a=o.stsd.entries[0],h=n.mdia.hdlr.handlerType;let c,u;if("vide"===h&&"avc1"===a.type){if(this._hasVideo)continue;this._hasVideo=!0,c="avc1",a.avcC&&(c+=`.${a.avcC.mimeCodec}`),u=`video/mp4; codecs="${c}"`}else{if("soun"!==h||"mp4a"!==a.type)continue;if(this._hasAudio)continue;this._hasAudio=!0,c="mp4a",a.esds&&a.esds.mimeCodec&&(c+=`.${a.esds.mimeCodec}`),u=`audio/mp4; codecs="${c}"`}const d=[];let l=0,f=0,p=0,g=0,m=0,_=0;const y=new r(o.stts.entries);let b=null;o.ctts&&(b=new r(o.ctts.entries));let w=0;for(;;){var s=o.stsc.entries[m];const e=o.stsz.entries[l],t=y.value.duration,n=b?b.value.compositionOffset:0;let r=!0;o.stss&&(r=o.stss.entries[w]===l+1);const i=o.stco||o.co64;if(d.push({size:e,duration:t,dts:_,presentationOffset:n,sync:r,offset:g+i.entries[p]}),++l>=o.stsz.entries.length)break;if(g+=e,++f>=s.samplesPerChunk){f=0,g=0,p++;const e=o.stsc.entries[m+1];e&&p+1>=e.firstChunk&&m++}_+=t,y.inc(),b&&b.inc(),r&&w++}n.mdia.mdhd.duration=0,n.tkhd.duration=0;const v=s.sampleDescriptionId,E={type:"moov",mvhd:t.mvhd,traks:[{tkhd:n.tkhd,mdia:{mdhd:n.mdia.mdhd,hdlr:n.mdia.hdlr,elng:n.mdia.elng,minf:{vmhd:n.mdia.minf.vmhd,smhd:n.mdia.minf.smhd,dinf:n.mdia.minf.dinf,stbl:{stsd:o.stsd,stts:{version:0,flags:0,entries:[]},ctts:{version:0,flags:0,entries:[]},stsc:{version:0,flags:0,entries:[]},stsz:{version:0,flags:0,entries:[]},stco:{version:0,flags:0,entries:[]},stss:{version:0,flags:0,entries:[]}}}}}],mvex:{mehd:{fragmentDuration:t.mvhd.duration},trexs:[{trackId:n.tkhd.trackId,defaultSampleDescriptionIndex:v,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:n.tkhd.trackId,timeScale:n.mdia.mdhd.timeScale,samples:d,currSample:null,currTime:null,moov:E,mime:u})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));t.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const o=n.encode(this._ftyp),a=this._tracks.map(t=>{const r=n.encode(t.moov);return{mime:t.mime,init:e.concat([o,r])}});this.emit("ready",a)}seek(e){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let t=-1;if(this._tracks.map((n,r)=>{n.outStream&&n.outStream.destroy(),n.inStream&&(n.inStream.destroy(),n.inStream=null);const i=n.outStream=Ur.encode(),s=this._generateFragment(r,e);if(!s)return i.finalize();(-1===t||s.ranges[0].start<t)&&(t=s.ranges[0].start);const o=e=>{i.destroyed||i.box(e.moof,t=>{if(t)return this.emit("error",t);i.destroyed||n.inStream.slice(e.ranges).pipe(i.mediaData(e.length,e=>{if(e)return this.emit("error",e);if(i.destroyed)return;const t=this._generateFragment(r);if(!t)return i.finalize();o(t)}))})};o(s)}),t>=0){const e=this._fileStream=this._file.createReadStream({start:t});this._tracks.forEach(n=>{n.inStream=new Pr(t,{highWaterMark:1e7}),e.pipe(n.inStream)})}return this._tracks.map(e=>e.outStream)}_findSampleBefore(e,t){const n=this._tracks[e],r=Math.floor(n.timeScale*t);let i=function(e,t,n,r,i){var s,o;if(void 0===r)r=0;else if((r|=0)<0||r>=e.length)throw new RangeError("invalid lower bound");if(void 0===i)i=e.length-1;else if((i|=0)<r||i>=e.length)throw new RangeError("invalid upper bound");for(;r<=i;)if((o=+n(e[s=r+(i-r>>>1)],t,s,e))<0)r=s+1;else{if(!(o>0))return s;i=s-1}return~r}(n.samples,r,(e,t)=>e.dts+e.presentationOffset-t);for(-1===i?i=0:i<0&&(i=-i-2);!n.samples[i].sync;)i--;return i}_generateFragment(e,t){const n=this._tracks[e];let r;if((r=void 0!==t?this._findSampleBefore(e,t):n.currSample)>=n.samples.length)return null;const i=n.samples[r].dts;let s=0;const o=[];for(var a=r;a<n.samples.length;a++){const e=n.samples[a];if(e.sync&&e.dts-i>=1*n.timeScale)break;s+=e.size;const t=o.length-1;t<0||o[t].end!==e.offset?o.push({start:e.offset,end:e.offset+e.size}):o[t].end+=e.size}return n.currSample=a,{moof:this._generateMoof(e,r,a),ranges:o,length:s}}_generateMoof(e,t,r){const i=this._tracks[e],s=[];let o=0;for(let n=t;n<r;n++){const e=i.samples[n];e.presentationOffset<0&&(o=1),s.push({sampleDuration:e.duration,sampleSize:e.size,sampleFlags:e.sync?33554432:16842752,sampleCompositionTimeOffset:e.presentationOffset})}const a={type:"moof",mfhd:{sequenceNumber:i.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:i.trackId},tfdt:{baseMediaDecodeTime:i.samples[t].dts},trun:{flags:3841,dataOffset:8,entries:s,version:o}}]};return a.trafs[0].trun.dataOffset+=n.encodingLength(a),a}}}).call(this,d({}).Buffer);var Hr={};function jr(e,t,n={}){if(!(this instanceof jr))return console.warn("don't invoked VideoStream without 'new'"),new jr(e,t,n);this.detailedError=null,this._elem=t,this._elemWrapper=new br(t),this._waitingFired=!1,this._trackMeta=null,this._file=e,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=(()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()}),this._onWaiting=(()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()}),t.autoplay&&(t.preload="auto"),t.addEventListener("waiting",this._onWaiting),t.addEventListener("error",this._onError)}jr.prototype={_createMuxer(){this._muxer=new Nr(this._file),this._muxer.on("ready",e=>{this._tracks=e.map(e=>{const t=this._elemWrapper.createWriteStream(e.mime);t.on("error",e=>{this._elemWrapper.error(e)});const n={muxed:null,mediaSource:t,initFlushed:!1,onInitFlushed:null};return t.write(e.init,e=>{n.initFlushed=!0,n.onInitFlushed&&n.onInitFlushed(e)}),n}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",e=>{this._elemWrapper.error(e)})},_pump(){const e=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((t,n)=>{const r=()=>{t.muxed&&(t.muxed.destroy(),t.mediaSource=this._elemWrapper.createWriteStream(t.mediaSource),t.mediaSource.on("error",e=>{this._elemWrapper.error(e)})),t.muxed=e[n],pr(t.muxed,t.mediaSource)};t.initFlushed?r():t.onInitFlushed=(e=>{e?this._elemWrapper.error(e):r()})})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(e=>{e.muxed&&e.muxed.destroy()}),this._elem.src="")}},Hr=jr;var Dr={render:function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n||(n={}),r||(r=function(){}),Qr(e),ei(n),"string"==typeof t&&(t=document.querySelector(t)),Xr(e,function(n){if(t.nodeName!==n.toUpperCase()){var r=ut.extname(e.name).toLowerCase();throw new Error('Cannot render "'+r+'" inside a "'+t.nodeName.toLowerCase()+'" element, expected "'+n+'"')}return t},n,r)},append:function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),n||(n={}),r||(r=function(){}),Qr(e),ei(n),"string"==typeof t&&(t=document.querySelector(t)),t&&("VIDEO"===t.nodeName||"AUDIO"===t.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");function i(e){var n=document.createElement(e);return t.appendChild(n),n}Xr(e,function(e){return"video"===e||"audio"===e?function(e){var r=i(e);return n.autoplay&&(r.autoplay=!0),n.muted&&(r.muted=!0),n.controls&&(r.controls=!0),t.appendChild(r),r}(e):i(e)},n,function(e,t){e&&t&&t.remove(),r(e,t)})},mime:{".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},qr=zt("render-media"),Fr=[".m4a",".m4b",".m4p",".m4v",".mp4"],Wr=[".m4v",".mkv",".mp4",".webm"],zr=[].concat(Wr,[".m4a",".m4b",".m4p",".mp3"]),$r=[".mov",".ogv"],Vr=[".aac",".oga",".ogg",".wav",".flac"],Gr=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],Kr=[".css",".html",".js",".md",".pdf",".txt"],Yr=2e8,Jr="undefined"!=typeof window&&window.MediaSource;function Xr(e,t,n,r){var i,s=ut.extname(e.name).toLowerCase(),o=0;function a(){return!("number"==typeof e.length&&e.length>n.maxBlobLength&&(qr("File length too large for Blob URL approach: %d (max: %d)",e.length,n.maxBlobLength),l(new Error("File length too large for Blob URL approach: "+e.length+" (max: "+n.maxBlobLength+")")),1))}function h(n){a()&&(i=t(n),Zr(e,function(e,t){if(e)return l(e);i.addEventListener("error",l),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),i.src=t}))}function c(){i.removeEventListener("loadstart",c),n.autoplay&&i.play()}function u(){i.removeEventListener("canplay",u),r(null,i)}function d(){Zr(e,function(e,n){if(e)return l(e);".pdf"!==s?((i=t("iframe")).sandbox="allow-forms allow-scripts",i.src=n):((i=t("object")).setAttribute("typemustmatch",!0),i.setAttribute("type","application/pdf"),i.setAttribute("data",n)),r(null,i)})}function l(t){t.message='Error rendering file "'+e.name+'": '+t.message,qr(t.message),r(t)}zr.indexOf(s)>=0?function(){var n=Wr.indexOf(s)>=0?"video":"audio";function r(){qr("Use MediaSource API for "+e.name),f(),i.addEventListener("error",d),i.addEventListener("loadstart",c),i.addEventListener("canplay",u);var t,n=new br(i).createWriteStream((t=e.name,{".m4a":'audio/mp4; codecs="mp4a.40.5"',".m4b":'audio/mp4; codecs="mp4a.40.5"',".m4p":'audio/mp4; codecs="mp4a.40.5"',".m4v":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".mkv":'video/webm; codecs="avc1.640029, mp4a.40.5"',".mp3":"audio/mpeg",".mp4":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".webm":'video/webm; codecs="vorbis, vp8"'}[ut.extname(t).toLowerCase()]));e.createReadStream().pipe(n),o&&(i.currentTime=o)}function h(){qr("Use Blob URL for "+e.name),f(),i.addEventListener("error",l),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),Zr(e,function(e,t){if(e)return l(e);i.src=t,o&&(i.currentTime=o)})}function d(e){qr("MediaSource API error: fallback to Blob URL: %o",e.message||e),a()&&(i.removeEventListener("error",d),i.removeEventListener("canplay",u),h())}function f(){i||(i=t(n)).addEventListener("progress",function(){o=i.currentTime})}Jr?Fr.indexOf(s)>=0?(qr("Use `videostream` package for "+e.name),f(),i.addEventListener("error",function e(t){qr("videostream error: fallback to MediaSource API: %o",t.message||t),i.removeEventListener("error",e),i.removeEventListener("canplay",u),r()}),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),Hr(e,i)):r():h()}():$r.indexOf(s)>=0?h("video"):Vr.indexOf(s)>=0?h("audio"):Gr.indexOf(s)>=0?(i=t("img"),Zr(e,function(t,n){if(t)return l(t);i.src=n,i.alt=e.name,r(null,i)})):Kr.indexOf(s)>=0?d():function(){qr('Unknown file extension "%s" - will attempt to render into iframe',s);var t="";e.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",function(e){t+=e}).on("end",function(){_r(t)?(qr('File extension "%s" appears ascii, so will render.',s),d()):(qr('File extension "%s" appears non-ascii, will not render.',s),r(new Error('Unsupported file type "'+s+'": Cannot append to DOM')))}).on("error",r)}()}function Zr(e,t){var n=ut.extname(e.name).toLowerCase();Sr(e.createReadStream(),Dr.mime[n],t)}function Qr(e){if(null==e)throw new Error("file cannot be null or undefined");if("string"!=typeof e.name)throw new Error("missing or invalid file.name property");if("function"!=typeof e.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function ei(e){null==e.autoplay&&(e.autoplay=!1),null==e.muted&&(e.muted=!1),null==e.controls&&(e.controls=!0),null==e.maxBlobLength&&(e.maxBlobLength=Yr)}var ti={};(function(e){ti=function(t,n,r){r=Rt(r);var i=e.alloc(n),s=0;t.on("data",function(e){e.copy(i,s),s+=e.length}).on("end",function(){r(null,i)}).on("error",r)}}).call(this,d({}).Buffer);const ni=zt("webtorrent:file-stream");var ri=class extends it.Readable{constructor(e,t){super(t),this.destroyed=!1,this._torrent=e._torrent;const n=t&&t.start||0,r=t&&t.end&&t.end<e.length?t.end:e.length-1,i=e._torrent.pieceLength;this._startPiece=(n+e.offset)/i|0,this._endPiece=(r+e.offset)/i|0,this._piece=this._startPiece,this._offset=n+e.offset-this._startPiece*i,this._missing=r-n+1,this._reading=!1,this._notifying=!1,this._criticalLength=Math.min(1048576/i|0,2)}_read(){this._reading||(this._reading=!0,this._notify())}_notify(){if(!this._reading||0===this._missing)return;if(!this._torrent.bitfield.get(this._piece))return this._torrent.critical(this._piece,this._piece+this._criticalLength);if(this._notifying)return;if(this._notifying=!0,this._torrent.destroyed)return this._destroy(new Error("Torrent removed"));const e=this._piece;this._torrent.store.get(e,(t,n)=>{if(this._notifying=!1,!this.destroyed){if(t)return this._destroy(t);ni("read %s (length %s) (err %s)",e,n.length,t&&t.message),this._offset&&(n=n.slice(this._offset),this._offset=0),this._missing<n.length&&(n=n.slice(0,this._missing)),this._missing-=n.length,ni("pushing buffer of length %s",n.length),this._reading=!1,this.push(n),0===this._missing&&this.push(null)}}),this._piece+=1}destroy(e){this._destroy(null,e)}_destroy(e,t){this.destroyed||(this.destroyed=!0,this._torrent.destroyed||this._torrent.deselect(this._startPiece,this._endPiece,!0),e&&this.emit("error",e),this.emit("close"),t&&t())}},ii={};(function(e){const{EventEmitter:t}=l,{PassThrough:n}=it;ii=class extends t{constructor(e,t){super(),this._torrent=e,this._destroyed=!1,this.name=t.name,this.path=t.path,this.length=t.length,this.offset=t.offset,this.done=!1;const n=t.offset,r=n+t.length-1;this._startPiece=n/this._torrent.pieceLength|0,this._endPiece=r/this._torrent.pieceLength|0,0===this.length&&(this.done=!0,this.emit("done"))}get downloaded(){if(!this._torrent.bitfield)return 0;const{pieces:e,bitfield:t,pieceLength:n}=this._torrent,{_startPiece:r,_endPiece:i}=this,s=e[r];let o=t.get(r)?n-this.offset%n:Math.max(s.length-s.missing-this.offset,0);for(let a=r+1;a<=i;++a)if(t.get(a))o+=n;else{const t=e[a];o+=t.length-t.missing}return Math.min(o,this.length)}get progress(){return this.length?this.downloaded/this.length:0}select(e){0!==this.length&&this._torrent.select(this._startPiece,this._endPiece,e)}deselect(){0!==this.length&&this._torrent.deselect(this._startPiece,this._endPiece,!1)}createReadStream(t){if(0===this.length){const t=new n;return e.nextTick(()=>{t.end()}),t}const r=new ri(this,t);return this._torrent.select(r._startPiece,r._endPiece,!0,()=>{r._notify()}),fr(r,()=>{this._destroyed||this._torrent.destroyed||this._torrent.deselect(r._startPiece,r._endPiece,!0)}),r}getBuffer(e){ti(this.createReadStream(),this.length,e)}getBlob(e){if("undefined"==typeof window)throw new Error("browser-only method");(function(e,t){if(null!=t&&"string"!=typeof t)throw new Error("Invalid mimetype, expected string.");return new Promise((n,r)=>{const i=[];e.on("data",e=>i.push(e)).once("end",()=>{const e=null!=t?new Blob(i,{type:t}):new Blob(i);n(e)}).once("error",r)})})(this.createReadStream(),this._getMimeType()).then(t=>e(null,t),e)}getBlobURL(e){if("undefined"==typeof window)throw new Error("browser-only method");Sr(this.createReadStream(),this._getMimeType(),e)}appendTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");Dr.append(this,e,t,n)}renderTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");Dr.render(this,e,t,n)}_getMimeType(){return Dr.mime[ut.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}}).call(this,ue);var si=function(e,t){if(!(t>=e.length||t<0)){var n=e.pop();if(t<e.length){var r=e[t];return e[t]=n,r}return n}},oi={};(function(e){const t=zt("bittorrent-protocol"),n=e.from("\x13BitTorrent protocol"),r=e.from([0,0,0,0]),i=e.from([0,0,0,1,0]),s=e.from([0,0,0,1,1]),o=e.from([0,0,0,1,2]),a=e.from([0,0,0,1,3]),h=[0,0,0,0,0,0,0,0],c=[0,0,0,3,9,0,0];class u{constructor(e,t,n,r){this.piece=e,this.offset=t,this.length=n,this.callback=r}}oi=class extends it.Duplex{constructor(){super(),this._debugId=On(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=null,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new zn(0,{grow:4e5}),this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=jn(),this.downloadSpeed=jn(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this.on("finish",this._onFinish),this._parseHandshake()}setKeepAlive(e){this._debug("setKeepAlive %s",e),clearInterval(this._keepAliveInterval),!1!==e&&(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},55e3))}setTimeout(e,t){this._debug("setTimeout ms=%d unref=%s",e,t),this._clearTimeout(),this._timeoutMs=e,this._timeoutUnref=!!t,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...e){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...e)}use(e){const t=e.prototype.name;if(!t)throw new Error('Extension class requires a "name" property on the prototype');this._debug("use extension.name=%s",t);const n=this._nextExt,r=new e(this);function i(){}"function"!=typeof r.onHandshake&&(r.onHandshake=i),"function"!=typeof r.onExtendedHandshake&&(r.onExtendedHandshake=i),"function"!=typeof r.onMessage&&(r.onMessage=i),this.extendedMapping[n]=t,this._ext[t]=r,this[t]=r,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(r)}handshake(t,r,i){let s,o;if("string"==typeof t?(t=t.toLowerCase(),s=e.from(t,"hex")):t=(s=t).toString("hex"),"string"==typeof r?o=e.from(r,"hex"):r=(o=r).toString("hex"),20!==s.length||20!==o.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",t,r,i);const a=e.from(h);a[5]|=16,i&&i.dht&&(a[7]|=1),this._push(e.concat([n,a,s,o])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const e=Object.assign({},this.extendedHandshake);e.m={};for(const t in this.extendedMapping){const n=this.extendedMapping[t];e.m[n]=Number(t)}this.extended(0,Q.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(i)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(s))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(o))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(a))}have(e){this._debug("have %d",e),this._message(4,[e],null)}bitfield(t){this._debug("bitfield"),e.isBuffer(t)||(t=t.buffer),this._message(5,[],t)}request(e,t,n,r){return r||(r=(()=>{})),this._finished?r(new Error("wire is closed")):this.peerChoking?r(new Error("peer is choking")):(this._debug("request index=%d offset=%d length=%d",e,t,n),this.requests.push(new u(e,t,n,r)),this._updateTimeout(),void this._message(6,[e,t,n],null))}piece(e,t,n){this._debug("piece index=%d offset=%d",e,t),this.uploaded+=n.length,this.uploadSpeed(n.length),this.emit("upload",n.length),this._message(7,[e,t],n)}cancel(e,t,n){this._debug("cancel index=%d offset=%d length=%d",e,t,n),this._callback(this._pull(this.requests,e,t,n),new Error("request was cancelled"),null),this._message(8,[e,t,n],null)}port(t){this._debug("port %d",t);const n=e.from(c);n.writeUInt16BE(t,5),this._push(n)}extended(t,n){if(this._debug("extended ext=%s",t),"string"==typeof t&&this.peerExtendedMapping[t]&&(t=this.peerExtendedMapping[t]),"number"!=typeof t)throw new Error(`Unrecognized extension: ${t}`);{const r=e.from([t]),i=e.isBuffer(n)?n:Q.encode(n);this._message(20,[],e.concat([r,i]))}}_read(){}_message(t,n,r){const i=r?r.length:0,s=e.allocUnsafe(5+4*n.length);s.writeUInt32BE(s.length+i-4,0),s[4]=t;for(let e=0;e<n.length;e++)s.writeUInt32BE(n[e],5+4*e);this._push(s),r&&this._push(r)}_push(e){if(!this._finished)return this.push(e)}_onKeepAlive(){this._debug("got keep-alive"),this.emit("keep-alive")}_onHandshake(e,t,n){const r=e.toString("hex"),i=t.toString("hex");let s;for(s in this._debug("got handshake i=%s p=%s exts=%o",r,i,n),this.peerId=i,this.peerIdBuffer=t,this.peerExtensions=n,this.emit("handshake",r,i,n),this._ext)this._ext[s].onHandshake(r,i,n);n.extended&&this._handshakeSent&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_onChoke(){for(this.peerChoking=!0,this._debug("got choke"),this.emit("choke");this.requests.length;)this._callback(this.requests.pop(),new Error("peer is choking"),null)}_onUnchoke(){this.peerChoking=!1,this._debug("got unchoke"),this.emit("unchoke")}_onInterested(){this.peerInterested=!0,this._debug("got interested"),this.emit("interested")}_onUninterested(){this.peerInterested=!1,this._debug("got uninterested"),this.emit("uninterested")}_onHave(e){this.peerPieces.get(e)||(this._debug("got have %d",e),this.peerPieces.set(e,!0),this.emit("have",e))}_onBitField(e){this.peerPieces=new zn(e),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(e,t,n){if(this.amChoking)return;this._debug("got request index=%d offset=%d length=%d",e,t,n);const r=(r,s)=>{if(i===this._pull(this.peerRequests,e,t,n))return r?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,n,r.message):void this.piece(e,t,s)};var i=new u(e,t,n,r);this.peerRequests.push(i),this.emit("request",e,t,n,r)}_onPiece(e,t,n){this._debug("got piece index=%d offset=%d",e,t),this._callback(this._pull(this.requests,e,t,n.length),null,n),this.downloaded+=n.length,this.downloadSpeed(n.length),this.emit("download",n.length),this.emit("piece",e,t,n)}_onCancel(e,t,n){this._debug("got cancel index=%d offset=%d length=%d",e,t,n),this._pull(this.peerRequests,e,t,n),this.emit("cancel",e,t,n)}_onPort(e){this._debug("got port %d",e),this.emit("port",e)}_onExtended(e,t){if(0===e){let e,n;try{e=Q.decode(t)}catch(_i){this._debug("ignoring invalid extended handshake: %s",_i.message||_i)}if(!e)return;if(this.peerExtendedHandshake=e,"object"==typeof e.m)for(n in e.m)this.peerExtendedMapping[n]=Number(e.m[n].toString());for(n in this._ext)this.peerExtendedMapping[n]&&this._ext[n].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[e]&&(e=this.extendedMapping[e],this._ext[e]&&this._ext[e].onMessage(t)),this._debug("got extended message ext=%s",e),this.emit("extended",e,t)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(t,n,r){for(this._bufferSize+=t.length,this._buffer.push(t);this._bufferSize>=this._parserSize;){const t=1===this._buffer.length?this._buffer[0]:e.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[t.slice(this._parserSize)]:[],this._parser(t.slice(0,this._parserSize))}r(null)}_callback(e,t,n){e&&(this._clearTimeout(),this.peerChoking||this._finished||this._updateTimeout(),e.callback(t,n))}_clearTimeout(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_updateTimeout(){this._timeoutMs&&this.requests.length&&!this._timeout&&(this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref())}_parse(e,t){this._parserSize=e,this._parser=t}_onMessageLength(e){const t=e.readUInt32BE(0);t>0?this._parse(t,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(e){switch(this._parse(4,this._onMessageLength),e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",e)}}_parseHandshake(){this._parse(1,e=>{const t=e.readUInt8(0);this._parse(t+48,e=>{const n=e.slice(0,t);if("BitTorrent protocol"!==n.toString())return this._debug("Error: wire not speaking BitTorrent protocol (%s)",n.toString()),void this.end();e=e.slice(t),this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(1&e[7]),extended:!!(16&e[5])}),this._parse(4,this._onMessageLength)})})}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...e){e[0]=`[${this._debugId}] ${e[0]}`,t(...e)}_pull(e,t,n,r){for(let i=0;i<e.length;i++){const s=e[i];if(s.piece===t&&s.offset===n&&s.length===r)return si(e,i),s}return null}}}).call(this,d({}).Buffer);var ai="0.107.2",hi={};(function(e){const t=zt("webtorrent:webconn"),n=ai;hi=class extends oi{constructor(e,t){super(),this.url=e,this.webPeerId=Nt.sync(e),this._torrent=t,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",(e,t)=>{if(this.destroyed)return;this.handshake(e,this.webPeerId);const n=this._torrent.pieces.length,r=new zn(n);for(let i=0;i<=n;i++)r.set(i,!0);this.bitfield(r)}),this.once("interested",()=>{t("interested"),this.unchoke()}),this.on("uninterested",()=>{t("uninterested")}),this.on("choke",()=>{t("choke")}),this.on("unchoke",()=>{t("unchoke")}),this.on("bitfield",()=>{t("bitfield")}),this.on("request",(e,n,r,i)=>{t("request pieceIndex=%d offset=%d length=%d",e,n,r),this.httpRequest(e,n,r,i)})}httpRequest(r,i,s,o){const a=r*this._torrent.pieceLength+i,h=a+s-1,c=this._torrent.files;let u;if(c.length<=1)u=[{url:this.url,start:a,end:h}];else{const e=c.filter(e=>e.offset<=h&&e.offset+e.length>a);if(e.length<1)return o(new Error("Could not find file corresponnding to web seed range request"));u=e.map(e=>{const t=e.offset+e.length-1;return{url:this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path,fileOffsetInRange:Math.max(e.offset-a,0),start:Math.max(a-e.offset,0),end:Math.min(t,h-e.offset)}})}let d,l=0,f=!1;u.length>1&&(d=e.alloc(s)),u.forEach(e=>{const a=e.url,h=e.start,c=e.end;t("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",a,r,i,s,h,c);const p={url:a,method:"GET",headers:{"user-agent":`WebTorrent/${n} (https://webtorrent.io)`,range:`bytes=${h}-${c}`}};function g(n,r){if(n.statusCode<200||n.statusCode>=300)return f=!0,o(new Error(`Unexpected HTTP status code ${n.statusCode}`));t("Got data of length %d",r.length),1===u.length?o(null,r):(r.copy(d,e.fileOffsetInRange),++l===u.length&&o(null,d))}Tn.concat(p,(e,t,n)=>{if(!f)return e?"undefined"==typeof window||a.startsWith(`${window.location.origin}/`)?(f=!0,o(e)):Tn.head(a,(t,n)=>{if(!f){if(t)return f=!0,o(t);if(n.statusCode<200||n.statusCode>=300)return f=!0,o(new Error(`Unexpected HTTP status code ${n.statusCode}`));if(n.url===a)return f=!0,o(e);p.url=n.url,Tn.concat(p,(e,t,n)=>{if(!f)return e?(f=!0,o(e)):void g(t,n)})}}):void g(t,n)})})}destroy(){super.destroy(),this._torrent=null}}}).call(this,d({}).Buffer);var ci={};const ui=zt("webtorrent:peer"),di=5e3,li=25e3,fi=25e3;ci.createWebRTCPeer=((e,t)=>{const n=new pi(e.id,"webrtc");return n.conn=e,n.swarm=t,n.conn.connected?n.onConnect():(n.conn.once("connect",()=>{n.onConnect()}),n.conn.once("error",e=>{n.destroy(e)}),n.startConnectTimeout()),n}),ci.createTCPOutgoingPeer=((e,t)=>{const n=new pi(e,"tcpOutgoing");return n.addr=e,n.swarm=t,n}),ci.createWebSeedPeer=((e,t)=>{const n=new pi(e,"webSeed");return n.swarm=t,n.conn=new hi(e,t),n.onConnect(),n});class pi{constructor(e,t){this.id=e,this.type=t,ui("new %s Peer %s",t,e),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentHandshake=!1}onConnect(){if(this.destroyed)return;this.connected=!0,ui("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const e=this.conn;e.once("end",()=>{this.destroy()}),e.once("close",()=>{this.destroy()}),e.once("finish",()=>{this.destroy()}),e.once("error",e=>{this.destroy(e)});const t=this.wire=new oi;t.type=this.type,t.once("end",()=>{this.destroy()}),t.once("close",()=>{this.destroy()}),t.once("finish",()=>{this.destroy()}),t.once("error",e=>{this.destroy(e)}),t.once("handshake",(e,t)=>{this.onHandshake(e,t)}),this.startHandshakeTimeout(),e.pipe(t).pipe(e),this.swarm&&!this.sentHandshake&&this.handshake()}onHandshake(e,t){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(e!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(t===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));ui("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let n=this.addr;!n&&this.conn.remoteAddress&&this.conn.remotePort&&(n=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,n),this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout),this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},"webrtc"===this.type?li:di),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout(()=>{this.destroy(new Error("handshake timeout"))},fi),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,ui("destroy %s (error: %s)",this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,n=this.conn,r=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&r&&si(t.wires,t.wires.indexOf(r)),n&&(n.on("error",()=>{}),n.destroy()),r&&r.destroy(),t&&t.removePeer(this.id)}}var gi={};(function(e,t){const n=zt("webtorrent:torrent"),r=l.EventEmitter,i=3*ur.BLOCK_LENGTH,s=e.browser?1/0:2,o=[1e3,5e3,15e3],a=`WebTorrent/${ai} (https://webtorrent.io)`;let h;try{h=ut.join(wt.statSync("/tmp")&&"/tmp","webtorrent")}catch(_i){h=ut.join("function"==typeof ne.tmpdir?ne.tmpdir():"/","webtorrent")}function c(e,t){return 2+Math.ceil(t*e.downloadSpeed()/ur.BLOCK_LENGTH)}function u(){}gi=class extends r{constructor(e,t,n){super(),this._debugId="unknown infohash",this.client=t,this.announce=n.announce,this.urlList=n.urlList,this.path=n.path,this.skipVerify=!!n.skipVerify,this._store=n.store||ar,this._getAnnounceOpts=n.getAnnounceOpts,this.strategy=n.strategy||"sequential",this.maxWebConns=n.maxWebConns||4,this._rechokeNumSlots=!1===n.uploads||0===n.uploads?0:+n.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=!1,this.done=!1,this.metadata=null,this.store=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=jn(),this._uploadSpeed=jn(),this._servers=[],this._xsRequests=[],this._fileModtimes=n.fileModtimes,null!==e&&this._onTorrentId(e),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:(this.length-this.downloaded)/this.downloadSpeed*1e3}get downloaded(){if(!this.bitfield)return 0;let e=0;for(let t=0,n=this.pieces.length;t<n;++t)if(this.bitfield.get(t))e+=t===n-1?this.lastPieceLength:this.pieceLength;else{const n=this.pieces[t];e+=n.length-n.missing}return e}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){return this.length?this.downloaded/this.length:0}get ratio(){return this.uploaded/(this.received||1)}get numPeers(){return this.wires.length}get torrentFileBlobURL(){if("undefined"==typeof window)throw new Error("browser-only property");return this.torrentFile?URL.createObjectURL(new Blob([this.torrentFile],{type:"application/x-bittorrent"})):null}get _numQueued(){return this._queue.length+(this._peersLength-this._numConns)}get _numConns(){let e=0;for(const t in this._peers)this._peers[t].connected&&(e+=1);return e}get swarm(){return console.warn("WebTorrent: `torrent.swarm` is deprecated. Use `torrent` directly instead."),this}_onTorrentId(t){if(this.destroyed)return;let n;try{n=Ln(t)}catch(_i){}n?(this.infoHash=n.infoHash,this._debugId=n.infoHash.toString("hex").substring(0,7),e.nextTick(()=>{this.destroyed||this._onParsedTorrent(n)})):Ln.remote(t,(e,t)=>{if(!this.destroyed)return e?this._destroy(e):void this._onParsedTorrent(t)})}_onParsedTorrent(e){if(!this.destroyed){if(this._processParsedTorrent(e),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));this.path||(this.path=ut.join(h,this.infoHash)),this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),this.destroyed||(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(e){this._debugId=e.infoHash.toString("hex").substring(0,7),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&t.WEBTORRENT_ANNOUNCE&&!this.private&&(e.announce=e.announce.concat(t.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),Rn(e.announce),Rn(e.urlList),Object.assign(this,e),this.magnetURI=Ln.toMagnetURI(e),this.torrentFile=Ln.toTorrentFile(e)}_onListening(){if(this.discovery||this.destroyed)return;let e=this.client.tracker;e&&(e=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const e={uploaded:this.uploaded,downloaded:this.downloaded,left:Math.max(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(e,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(e,this._getAnnounceOpts()),e}})),this.discovery=new or({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:a}),this.discovery.on("error",e=>{this._destroy(e)}),this.discovery.on("peer",e=>{"string"==typeof e&&this.done||this.addPeer(e)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",e=>{this.emit("warning",e)}),this.info?this._onMetadata(this):this.xs&&this._getMetadataFromServer()}_getMetadataFromServer(){const e=this,t=(Array.isArray(this.xs)?this.xs:[this.xs]).map(t=>n=>{!function(t,n){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),n(null);const r={url:t,method:"GET",headers:{"user-agent":a}};let i;try{i=Tn.concat(r,function(r,i,s){if(e.destroyed)return n(null);if(e.metadata)return n(null);if(r)return e.emit("warning",new Error(`http error from xs param: ${t}`)),n(null);if(200!==i.statusCode)return e.emit("warning",new Error(`non-200 status code ${i.statusCode} from xs param: ${t}`)),n(null);let o;try{o=Ln(s)}catch(r){}return o?o.infoHash!==e.infoHash?(e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),n(null)):(e._onMetadata(o),void n(null)):(e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),n(null))})}catch(_i){return e.emit("warning",new Error(`skipping invalid url xs param: ${t}`)),n(null)}e._xsRequests.push(i)}(t,n)});Ut(t)}_onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequests.forEach(e=>{e.abort()}),this._xsRequests=[],e&&e.infoHash)t=e;else try{t=Ln(e)}catch(_i){return this._destroy(_i)}if(this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(e=>{this.addWebSeed(e)}),this._rarityMap=new class{constructor(e){this._torrent=e,this._numPieces=e.pieces.length,this._pieces=new Array(this._numPieces),this._onWire=(e=>{this.recalculate(),this._initWire(e)}),this._onWireHave=(e=>{this._pieces[e]+=1}),this._onWireBitfield=(()=>{this.recalculate()}),this._torrent.wires.forEach(e=>{this._initWire(e)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(e){let t=[],n=1/0;for(let r=0;r<this._numPieces;++r){if(e&&!e(r))continue;const i=this._pieces[r];i===n?t.push(r):i<n&&(t=[r],n=i)}return t.length?t[Math.random()*t.length|0]:-1}destroy(){this._torrent.removeListener("wire",this._onWire),this._torrent.wires.forEach(e=>{this._cleanupWireEvents(e)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(e){e._onClose=(()=>{this._cleanupWireEvents(e);for(let t=0;t<this._numPieces;++t)this._pieces[t]-=e.peerPieces.get(t)}),e.on("have",this._onWireHave),e.on("bitfield",this._onWireBitfield),e.once("close",e._onClose)}recalculate(){this._pieces.fill(0);for(const e of this._torrent.wires)for(let t=0;t<this._numPieces;++t)this._pieces[t]+=e.peerPieces.get(t)}_cleanupWireEvents(e){e.removeListener("have",this._onWireHave),e.removeListener("bitfield",this._onWireBitfield),e._onClose&&e.removeListener("close",e._onClose),e._onClose=null}}(this),this.store=new hr(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map(e=>({path:ut.join(this.path,e.path),length:e.length,offset:e.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(e=>new ii(this,e)),this.so){const e=mr.parse(this.so);this.files.forEach((t,n)=>{e.includes(n)&&this.files[n].select(!0)})}else 0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1);if(this._hashes=this.pieces,this.pieces=this.pieces.map((e,t)=>{const n=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new ur(n)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new zn(this.pieces.length),this.wires.forEach(e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)}),this.skipVerify)this._markAllVerified(),this._onStore();else{const e=e=>{if(e)return this._destroy(e);this._debug("done verifying"),this._onStore()};this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===ar?this.getFileModtimes((t,n)=>{if(t)return this._destroy(t);this.files.map((e,t)=>n[t]===this._fileModtimes[t]).every(e=>e)?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)}):this._verifyPieces(e)}this.emit("metadata")}getFileModtimes(e){const t=[];cr(this.files.map((e,n)=>r=>{wt.stat(ut.join(this.path,e.path),(e,i)=>{if(e&&"ENOENT"!==e.code)return r(e);t[n]=i&&i.mtime.getTime(),r(null)})}),s,n=>{this._debug("done getting file modtimes"),e(n,t)})}_verifyPieces(t){cr(this.pieces.map((t,n)=>t=>{if(this.destroyed)return t(new Error("torrent is destroyed"));this.store.get(n,(r,i)=>this.destroyed?t(new Error("torrent is destroyed")):r?e.nextTick(t,null):void Nt(i,e=>{if(this.destroyed)return t(new Error("torrent is destroyed"));if(e===this._hashes[n]){if(!this.pieces[n])return t(null);this._debug("piece verified %s",n),this._markVerified(n)}else this._debug("piece invalid %s",n);t(null)}))}),s,t)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=u),this._verifyPieces(t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)})}_markAllVerified(){for(let e=0;e<this.pieces.length;e++)this._markVerified(e)}_markVerified(e){this.pieces[e]=null,this._reservations[e]=null,this.bitfield.set(e,!0)}_onStore(){this.destroyed||(this._debug("on store"),this.ready=!0,this.emit("ready"),this._checkDone(),this._updateSelections())}destroy(e){this._destroy(null,e)}_destroy(e,t){if(this.destroyed)return;this.destroyed=!0,this._debug("destroy"),this.client._remove(this),clearInterval(this._rechokeIntervalId),this._xsRequests.forEach(e=>{e.abort()}),this._rarityMap&&this._rarityMap.destroy();for(const r in this._peers)this.removePeer(r);this.files.forEach(e=>{e instanceof ii&&e._destroy()});const n=this._servers.map(e=>t=>{e.destroy(t)});this.discovery&&n.push(e=>{this.discovery.destroy(e)}),this.store&&n.push(e=>{this.store.close(e)}),Ut(n,t),e&&(0===this.listenerCount("error")?this.client.emit("error",e):this.emit("error",e)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}addPeer(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let t;if("string"==typeof e){let r;try{r=Dn(e)}catch(n){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}t=r[0]}else"string"==typeof e.remoteAddress&&(t=e.remoteAddress);if(t&&this.client.blocked.contains(t))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const t=!!this._addPeer(e);return t?this.emit("peer",e):this.emit("invalidPeer",e),t}_addPeer(e){if(this.destroyed)return"string"!=typeof e&&e.destroy(),null;if("string"==typeof e&&!this._validAddr(e))return this._debug("ignoring peer: invalid %s",e),null;const t=e&&e.id||e;if(this._peers[t])return this._debug("ignoring peer: duplicate (%s)",t),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let n;return this._debug("add peer %s",t),n="string"==typeof e?ci.createTCPOutgoingPeer(e,this):ci.createWebRTCPeer(e,this),this._peers[n.id]=n,this._peersLength+=1,"string"==typeof e&&(this._queue.push(n),this._drain()),n}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(e))return this.emit("warning",new Error(`ignoring invalid web seed: ${e}`)),void this.emit("invalidPeer",e);if(this._peers[e])return this.emit("warning",new Error(`ignoring duplicate web seed: ${e}`)),void this.emit("invalidPeer",e);this._debug("add web seed %s",e);const t=ci.createWebSeedPeer(e,this);this._peers[t.id]=t,this._peersLength+=1,this.emit("peer",e)}_addIncomingPeer(e){return this.destroyed?e.destroy(new Error("torrent is destroyed")):this.paused?e.destroy(new Error("torrent is paused")):(this._debug("add incoming peer %s",e.id),this._peers[e.id]=e,void(this._peersLength+=1))}removePeer(e){const t=e&&e.id||e;(e=this._peers[t])&&(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,e.destroy(),this._drain())}select(e,t,n,r){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||t<e||this.pieces.length<=t)throw new Error(`invalid selection ${e} : ${t}`);n=Number(n)||0,this._debug("select %s-%s (priority %s)",e,t,n),this._selections.push({from:e,to:t,offset:0,priority:n,notify:r||u}),this._selections.sort((e,t)=>t.priority-e.priority),this._updateSelections()}deselect(e,t,n){if(this.destroyed)throw new Error("torrent is destroyed");n=Number(n)||0,this._debug("deselect %s-%s (priority %s)",e,t,n);for(let r=0;r<this._selections.length;++r){const i=this._selections[r];if(i.from===e&&i.to===t&&i.priority===n){this._selections.splice(r,1);break}}this._updateSelections()}critical(e,t){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("critical %s-%s",e,t);for(let n=e;n<=t;++n)this._critical[n]=!0;this._updateSelections()}_onWire(t,n){if(this._debug("got wire %s (%s)",t._debugId,n||"Unknown"),t.on("download",e=>{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.client.emit("download",e))}),t.on("upload",e=>{this.destroyed||(this.uploaded+=e,this._uploadSpeed(e),this.client._uploadSpeed(e),this.emit("upload",e),this.client.emit("upload",e))}),this.wires.push(t),n){const e=Dn(n);t.remoteAddress=e[0],t.remotePort=e[1]}this.client.dht&&this.client.dht.listening&&t.on("port",e=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!t.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===e||e>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",e,n),this.client.dht.addNode({host:t.remoteAddress,port:e})}}),t.on("timeout",()=>{this._debug("wire timeout (%s)",n),t.destroy()}),t.setTimeout(3e4,!0),t.setKeepAlive(!0),t.use(gr(this.metadata)),t.ut_metadata.on("warning",e=>{this._debug("ut_metadata warning: %s",e.message)}),this.metadata||(t.ut_metadata.on("metadata",e=>{this._debug("got metadata via ut_metadata"),this._onMetadata(e)}),t.ut_metadata.fetch()),"function"!=typeof ne||this.private||(t.use(ne()),t.ut_pex.on("peer",e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,n),this.addPeer(e))}),t.ut_pex.on("dropped",e=>{const t=this._peers[e];t&&!t.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,n),this.removePeer(e))}),t.once("close",()=>{t.ut_pex.reset()})),this.emit("wire",t,n),this.metadata&&e.nextTick(()=>{this._onWireWithMetadata(t)})}_onWireWithMetadata(e){let t=null;const n=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(n,5e3)).unref&&t.unref())};let r;const i=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(r=0;r<this.pieces.length;++r)if(!e.peerPieces.get(r))return;e.isSeeder=!0,e.choke()}};e.on("bitfield",()=>{i(),this._update()}),e.on("have",()=>{i(),this._update()}),e.once("interested",()=>{e.unchoke()}),e.once("close",()=>{clearTimeout(t)}),e.on("choke",()=>{clearTimeout(t),(t=setTimeout(n,5e3)).unref&&t.unref()}),e.on("unchoke",()=>{clearTimeout(t),this._update()}),e.on("request",(t,n,r,i)=>{if(r>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:n,length:r},i)}),e.bitfield(this.bitfield),e.uninterested(),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(n,5e3)).unref&&t.unref(),e.isSeeder=!1,i()}_updateSelections(){this.ready&&!this.destroyed&&(e.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;e<this._selections.length;++e){const t=this._selections[e],n=t.offset;for(;this.bitfield.get(t.from+t.offset)&&t.from+t.offset<t.to;)t.offset+=1;n!==t.offset&&t.notify(),t.to===t.from+t.offset&&this.bitfield.get(t.from+t.offset)&&(this._selections.splice(e,1),e-=1,t.notify(),this._updateInterest())}this._selections.length||this.emit("idle")}_updateInterest(){const e=this._amInterested;this._amInterested=!!this._selections.length,this.wires.forEach(e=>{let t=!1;for(let n=0;n<this.pieces.length;++n)if(this.pieces[n]&&e.peerPieces.get(n)){t=!0;break}t?e.interested():e.uninterested()}),e!==this._amInterested&&(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_update(){if(this.destroyed)return;const e=(t=this.wires,n=0,function(){if(n===t.length)return null;var e=t.length-n,r=Math.random()*e|0,i=t[n+r],s=t[n];return t[n]=i,t[n+r]=s,n++,i});var t,n;let r;for(;r=e();)this._updateWireWrapper(r)}_updateWireWrapper(e){const t=this;"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?window.requestIdleCallback(function(){t._updateWire(e)}):t._updateWire(e)}_updateWire(e){const t=this;if(e.peerChoking)return;if(!e.downloaded)return function(){if(e.requests.length)return;let n=t._selections.length;for(;n--;){const r=t._selections[n];let i;if("rarest"===t.strategy){const n=r.from+r.offset,o=r.to,a=o-n+1,h={};let c=0;const u=s(n,o,h);for(;c<a&&!((i=t._rarityMap.getRarestPiece(u))<0);){if(t._request(e,i,!1))return;h[i]=!0,c+=1}}else for(i=r.to;i>=r.from+r.offset;--i)if(e.peerPieces.get(i)&&t._request(e,i,!1))return}}();const n=c(e,.5);if(e.requests.length>=n)return;const r=c(e,1);function s(t,n,r,i){return s=>s>=t&&s<=n&&!(s in r)&&e.peerPieces.get(s)&&(!i||i(s))}function o(e){let n=e;for(let i=e;i<t._selections.length&&t._selections[i].priority;i++)n=i;const r=t._selections[e];t._selections[e]=t._selections[n],t._selections[n]=r}function a(n){if(e.requests.length>=r)return!0;const a=function(){const n=e.downloadSpeed()||1;if(n>i)return()=>!0;const r=Math.max(1,e.requests.length)*ur.BLOCK_LENGTH/n;let s=10,o=0;return e=>{if(!s||t.bitfield.get(e))return!0;let a=t.pieces[e].missing;for(;o<t.wires.length;o++){const h=t.wires[o],c=h.downloadSpeed();if(!(c<i)&&!(c<=n)&&h.peerPieces.get(e)&&!((a-=c*r)>0))return s--,!1}return!0}}();for(let i=0;i<t._selections.length;i++){const h=t._selections[i];let c;if("rarest"===t.strategy){const u=h.from+h.offset,d=h.to,l=d-u+1,f={};let p=0;const g=s(u,d,f,a);for(;p<l&&!((c=t._rarityMap.getRarestPiece(g))<0);){for(;t._request(e,c,t._critical[c]||n););if(!(e.requests.length<r))return h.priority&&o(i),!0;f[c]=!0,p++}}else for(c=h.from+h.offset;c<=h.to;c++)if(e.peerPieces.get(c)&&a(c)){for(;t._request(e,c,t._critical[c]||n););if(!(e.requests.length<r))return h.priority&&o(i),!0}}return!1}a(!1)||a(!0)}_rechoke(){if(!this.ready)return;this._rechokeOptimisticTime>0?this._rechokeOptimisticTime-=1:this._rechokeOptimisticWire=null;const e=[];this.wires.forEach(t=>{t.isSeeder||t===this._rechokeOptimisticWire||e.push({wire:t,downloadSpeed:t.downloadSpeed(),uploadSpeed:t.uploadSpeed(),salt:Math.random(),isChoked:!0})}),e.sort(function(e,t){return e.downloadSpeed!==t.downloadSpeed?t.downloadSpeed-e.downloadSpeed:e.uploadSpeed!==t.uploadSpeed?t.uploadSpeed-e.uploadSpeed:e.wire.amChoking!==t.wire.amChoking?e.wire.amChoking?1:-1:e.salt-t.salt});let t=0,n=0;for(;n<e.length&&t<this._rechokeNumSlots;++n)e[n].isChoked=!1,e[n].wire.peerInterested&&(t+=1);if(!this._rechokeOptimisticWire&&n<e.length&&this._rechokeNumSlots){const t=e.slice(n).filter(e=>e.wire.peerInterested),i=t[(r=t.length,Math.random()*r|0)];i&&(i.isChoked=!1,this._rechokeOptimisticWire=i.wire,this._rechokeOptimisticTime=2)}var r;e.forEach(e=>{e.wire.amChoking!==e.isChoked&&(e.isChoked?e.wire.choke():e.wire.unchoke())})}_hotswap(e,t){const n=e.downloadSpeed();if(n<ur.BLOCK_LENGTH)return!1;if(!this._reservations[t])return!1;const r=this._reservations[t];if(!r)return!1;let s,o,a=1/0;for(o=0;o<r.length;o++){const t=r[o];if(!t||t===e)continue;const h=t.downloadSpeed();h>=i||2*h>n||h>a||(s=t,a=h)}if(!s)return!1;for(o=0;o<r.length;o++)r[o]===s&&(r[o]=null);for(o=0;o<s.requests.length;o++){const e=s.requests[o];e.piece===t&&this.pieces[t].cancel(e.offset/ur.BLOCK_LENGTH|0)}return this.emit("hotswap",s,e,t),!0}_request(t,n,r){const i=this,s=t.requests.length,o="webSeed"===t.type;if(i.bitfield.get(n))return!1;if(s>=(o?Math.min(function(e,t,n){return 1+Math.ceil(1*e.downloadSpeed()/n)}(t,0,i.pieceLength),i.maxWebConns):c(t,1)))return!1;const a=i.pieces[n];let h=o?a.reserveRemaining():a.reserve();if(-1===h&&r&&i._hotswap(t,n)&&(h=o?a.reserveRemaining():a.reserve()),-1===h)return!1;let u=i._reservations[n];u||(u=i._reservations[n]=[]);let d=u.indexOf(null);-1===d&&(d=u.length),u[d]=t;const l=a.chunkOffset(h),f=o?a.chunkLengthRemaining(h):a.chunkLength(h);function p(){e.nextTick(()=>{i._update()})}return t.request(n,l,f,function e(r,s){if(i.destroyed)return;if(!i.ready)return i.once("ready",()=>{e(r,s)});if(u[d]===t&&(u[d]=null),a!==i.pieces[n])return p();if(r)return i._debug("error getting piece %s (offset: %s length: %s) from %s: %s",n,l,f,`${t.remoteAddress}:${t.remotePort}`,r.message),o?a.cancelRemaining(h):a.cancel(h),void p();if(i._debug("got piece %s (offset: %s length: %s) from %s",n,l,f,`${t.remoteAddress}:${t.remotePort}`),!a.set(h,s,t))return p();const c=a.flush();Nt(c,e=>{if(!i.destroyed){if(e===i._hashes[n]){if(!i.pieces[n])return;i._debug("piece verified %s",n),i.pieces[n]=null,i._reservations[n]=null,i.bitfield.set(n,!0),i.store.put(n,c),i.wires.forEach(e=>{e.have(n)}),i._checkDone()&&!i.destroyed&&i.discovery.complete()}else i.pieces[n]=new ur(a.length),i.emit("warning",new Error(`Piece ${n} failed verification`));p()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(e=>{if(!e.done){for(let t=e._startPiece;t<=e._endPiece;++t)if(!this.bitfield.get(t))return;e.done=!0,e.emit("done"),this._debug(`file done: ${e.name}`)}});let e=!0;for(let t=0;t<this._selections.length;t++){const n=this._selections[t];for(let t=n.from;t<=n.to;t++)if(!this.bitfield.get(t)){e=!1;break}if(!e)break}return!this.done&&e&&(this.done=!0,this._debug(`torrent done: ${this.infoHash}`),this.emit("done")),this._gcSelections(),e}load(e,t){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.ready)return this.once("ready",()=>{this.load(e,t)});Array.isArray(e)||(e=[e]),t||(t=u);const n=new St(e),r=new Vn(this.store,this.pieceLength);pr(n,r,e=>{if(e)return t(e);this._markAllVerified(),this._checkDone(),t(null)})}createServer(e){if("function"!=typeof ne)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const t=new ne(this,e);return this._servers.push(t),t}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const e=[].slice.call(arguments);e[0]=`[${this.client._debugId}] [${this._debugId}] ${e[0]}`,n(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof ne.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const e=this._queue.shift();if(!e)return;this._debug("tcp connect attempt to %s",e.addr);const t=Dn(e.addr),n={host:t[0],port:t[1]},r=e.conn=ne.connect(n);r.once("connect",()=>{e.onConnect()}),r.once("error",t=>{e.destroy(t)}),e.startConnectTimeout(),r.on("close",()=>{if(this.destroyed)return;if(e.retries>=o.length)return void this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,o.length);const t=o[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const n=setTimeout(()=>{const t=this._addPeer(e.addr);t&&(t.retries=e.retries+1)},t);n.unref&&n.unref()})}_validAddr(e){let t;try{t=Dn(e)}catch(i){return!1}const n=t[0],r=t[1];return r>0&&r<65535&&!("127.0.0.1"===n&&r===this.client.torrentPort)}}}).call(this,ue,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var mi={};return function(e,t,n){const{EventEmitter:r}=l,i=zt("webtorrent"),s=ai,o=s.replace(/\d*./g,e=>`0${e%100}`.slice(-2)).slice(0,4),a=`-WW${o}-`;class h extends r{constructor(r={}){super(),"string"==typeof r.peerId?this.peerId=r.peerId:n.isBuffer(r.peerId)?this.peerId=r.peerId.toString("hex"):this.peerId=n.from(a+On(9).toString("base64")).toString("hex"),this.peerIdBuffer=n.from(this.peerId,"hex"),"string"==typeof r.nodeId?this.nodeId=r.nodeId:n.isBuffer(r.nodeId)?this.nodeId=r.nodeId.toString("hex"):this.nodeId=On(20).toString("hex"),this.nodeIdBuffer=n.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=r.torrentPort||0,this.dhtPort=r.dhtPort||0,this.tracker=void 0!==r.tracker?r.tracker:{},this.torrents=[],this.maxConns=Number(r.maxConns)||55,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),r.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=r.rtcConfig),r.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=r.wrtc),t.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=t.WRTC)),"function"==typeof ne?this._tcpPool=new ne(this):e.nextTick(()=>{this._onListening()}),this._downloadSpeed=jn(),this._uploadSpeed=jn(),!1!==r.dht&&"function"==typeof ne?(this.dht=new ne(Object.assign({},{nodeId:this.nodeId},r.dht)),this.dht.once("error",e=>{this._destroy(e)}),this.dht.once("listening",()=>{const e=this.dht.address();e&&(this.dhtPort=e.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==r.webSeeds;const i=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof ne&&null!=r.blocklist?ne(r.blocklist,{headers:{"user-agent":`WebTorrent/${s} (https://webtorrent.io)`}},(e,t)=>{if(e)return this.error(`Failed to load blocklist: ${e.message}`);this.blocked=t,i()}):e.nextTick(i)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const e=this.torrents.filter(e=>1!==e.progress);return e.reduce((e,t)=>e+t.downloaded,0)/(e.reduce((e,t)=>e+(t.length||0),0)||1)}get ratio(){return this.torrents.reduce((e,t)=>e+t.uploaded,0)/(this.torrents.reduce((e,t)=>e+t.received,0)||1)}get(e){if(e instanceof gi){if(this.torrents.includes(e))return e}else{let t;try{t=Ln(e)}catch(_i){}if(!t)return null;if(!t.infoHash)throw new Error("Invalid torrent identifier");for(const e of this.torrents)if(e.infoHash===t.infoHash)return e}return null}download(e,t,n){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(e,t,n)}add(e,t={},n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]);const r=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===s.infoHash&&e!==s)return void s._destroy(new Error(`Cannot add duplicate torrent ${s.infoHash}`))},i=()=>{this.destroyed||("function"==typeof n&&n(s),this.emit("torrent",s))};this._debug("add"),t=t?Object.assign({},t):{};const s=new gi(e,this,t);return this.torrents.push(s),s.once("_infoHash",r),s.once("ready",i),s.once("close",function e(){s.removeListener("_infoHash",r),s.removeListener("ready",i),s.removeListener("close",e)}),s}seed(e,t,n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const r="string"==typeof e;r&&(t.path=ut.dirname(e)),t.createdBy||(t.createdBy=`WebTorrent/${o}`);const i=e=>{this._debug("on seed"),"function"==typeof n&&n(e),e.emit("seed"),this.emit("seed",e)},s=this.add(null,t,e=>{const t=[t=>{if(r)return t();e.load(a,t)}];this.dht&&t.push(t=>{e.once("dhtAnnounce",t)}),Ut(t,t=>{if(!this.destroyed)return t?e._destroy(t):void i(e)})});let a;return"undefined"!=typeof FileList&&e instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),Ut(e.map(e=>t=>{!function(t){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}()?t(null,e):N(e,t)}),(e,n)=>{if(!this.destroyed)return e?s._destroy(e):void Wt.parseInput(n,t,(e,r)=>{if(!this.destroyed){if(e)return s._destroy(e);a=r.map(e=>e.getStream),Wt(n,t,(e,t)=>{if(this.destroyed)return;if(e)return s._destroy(e);const n=this.get(t);n?s._destroy(new Error(`Cannot add duplicate torrent ${n.infoHash}`)):s._onTorrentId(t)})}})}),s}remove(e,t){if(this._debug("remove"),!this.get(e))throw new Error(`No torrent with id ${e}`);this._remove(e,t)}_remove(e,t){const n=this.get(e);n&&(this.torrents.splice(this.torrents.indexOf(n),1),n.destroy(t))}address(){return this.listening?this._tcpPool?this._tcpPool.server.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(e){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,e)}_destroy(e,t){this._debug("client destroy"),this.destroyed=!0;const n=this.torrents.map(e=>t=>{e.destroy(t)});this._tcpPool&&n.push(e=>{this._tcpPool.destroy(e)}),this.dht&&n.push(e=>{this.dht.destroy(e)}),Ut(n,t),e&&this.emit("error",e),this.torrents=[],this._tcpPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._tcpPool){const e=this._tcpPool.server.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,i(...e)}}h.WEBRTC_SUPPORT=Mn.WEBRTC_SUPPORT,h.VERSION=s,mi=h}.call(this,ue,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},d({}).Buffer),mi});
\ No newline at end of file +(function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,g.WebTorrent=f()}})(function(){var _Mathabs=Math.abs,_Mathpow=Math.pow,_Mathfloor=Math.floor,_StringfromCharCode=String.fromCharCode,_Mathceil=Math.ceil,_Mathmax=Math.max,_Mathmin=Math.min,define;return 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<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module){const debug=require("debug")("webtorrent:file-stream"),stream=require("readable-stream");class FileStream extends stream.Readable{constructor(file,opts){super(opts),this.destroyed=!1,this._torrent=file._torrent;const start=opts&&opts.start||0,end=opts&&opts.end&&opts.end<file.length?opts.end:file.length-1,pieceLength=file._torrent.pieceLength;this._startPiece=0|(start+file.offset)/pieceLength,this._endPiece=0|(end+file.offset)/pieceLength,this._piece=this._startPiece,this._offset=start+file.offset-this._startPiece*pieceLength,this._missing=end-start+1,this._reading=!1,this._notifying=!1,this._criticalLength=_Mathmin(0|1048576/pieceLength,2)}_read(){this._reading||(this._reading=!0,this._notify())}_notify(){if(!this._reading||0===this._missing)return;if(!this._torrent.bitfield.get(this._piece))return this._torrent.critical(this._piece,this._piece+this._criticalLength);if(this._notifying)return;if(this._notifying=!0,this._torrent.destroyed)return this._destroy(new Error("Torrent removed"));const p=this._piece;this._torrent.store.get(p,(err,buffer)=>{if(this._notifying=!1,!this.destroyed)return debug("read %s (length %s) (err %s)",p,buffer.length,err&&err.message),err?this._destroy(err):void(this._offset&&(buffer=buffer.slice(this._offset),this._offset=0),this._missing<buffer.length&&(buffer=buffer.slice(0,this._missing)),this._missing-=buffer.length,debug("pushing buffer of length %s",buffer.length),this._reading=!1,this.push(buffer),0===this._missing&&this.push(null))}),this._piece+=1}destroy(onclose){this._destroy(null,onclose)}_destroy(err,onclose){this.destroyed||(this.destroyed=!0,!this._torrent.destroyed&&this._torrent.deselect(this._startPiece,this._endPiece,!0),err&&this.emit("error",err),this.emit("close"),onclose&&onclose())}}module.exports=FileStream},{debug:30,"readable-stream":85}],2:[function(require,module){(function(process){const{EventEmitter}=require("events"),{PassThrough}=require("readable-stream"),eos=require("end-of-stream"),path=require("path"),render=require("render-media"),streamToBlob=require("stream-to-blob"),streamToBlobURL=require("stream-to-blob-url"),streamToBuffer=require("stream-with-known-length-to-buffer"),FileStream=require("./file-stream");class File extends EventEmitter{constructor(torrent,file){super(),this._torrent=torrent,this._destroyed=!1,this.name=file.name,this.path=file.path,this.length=file.length,this.offset=file.offset,this.done=!1;const start=file.offset,end=start+file.length-1;this._startPiece=0|start/this._torrent.pieceLength,this._endPiece=0|end/this._torrent.pieceLength,0===this.length&&(this.done=!0,this.emit("done"))}get downloaded(){if(!this._torrent.bitfield)return 0;const{pieces,bitfield,pieceLength}=this._torrent,{_startPiece:start,_endPiece:end}=this,piece=pieces[start],irrelevantFirstPieceBytes=this.offset%pieceLength;let downloaded=bitfield.get(start)?pieceLength-irrelevantFirstPieceBytes:_Mathmax(pieceLength-irrelevantFirstPieceBytes-piece.missing,0);for(let index=start+1;index<=end;++index)if(bitfield.get(index))downloaded+=pieceLength;else{const piece=pieces[index];downloaded+=pieceLength-piece.missing}return _Mathmin(downloaded,this.length)}get progress(){return this.length?this.downloaded/this.length:0}select(priority){0===this.length||this._torrent.select(this._startPiece,this._endPiece,priority)}deselect(){0===this.length||this._torrent.deselect(this._startPiece,this._endPiece,!1)}createReadStream(opts){if(0===this.length){const empty=new PassThrough;return process.nextTick(()=>{empty.end()}),empty}const fileStream=new FileStream(this,opts);return this._torrent.select(fileStream._startPiece,fileStream._endPiece,!0,()=>{fileStream._notify()}),eos(fileStream,()=>{this._destroyed||!this._torrent.destroyed&&this._torrent.deselect(fileStream._startPiece,fileStream._endPiece,!0)}),fileStream}getBuffer(cb){streamToBuffer(this.createReadStream(),this.length,cb)}getBlob(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlob(this.createReadStream(),this._getMimeType()).then(blob=>cb(null,blob),err=>cb(err))}getBlobURL(cb){if("undefined"==typeof window)throw new Error("browser-only method");streamToBlobURL(this.createReadStream(),this._getMimeType()).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}appendTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.append(this,elem,opts,cb)}renderTo(elem,opts,cb){if("undefined"==typeof window)throw new Error("browser-only method");render.render(this,elem,opts,cb)}_getMimeType(){return render.mime[path.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}module.exports=File}).call(this,require("_process"))},{"./file-stream":1,_process:61,"end-of-stream":32,events:33,path:59,"readable-stream":85,"render-media":86,"stream-to-blob":104,"stream-to-blob-url":103,"stream-with-known-length-to-buffer":105}],3:[function(require,module,exports){const arrayRemove=require("unordered-array-remove"),debug=require("debug")("webtorrent:peer"),Wire=require("bittorrent-protocol"),WebConn=require("./webconn");exports.createWebRTCPeer=(conn,swarm)=>{const peer=new Peer(conn.id,"webrtc");return peer.conn=conn,peer.swarm=swarm,peer.conn.connected?peer.onConnect():(peer.conn.once("connect",()=>{peer.onConnect()}),peer.conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout()),peer},exports.createTCPIncomingPeer=conn=>{const addr=`${conn.remoteAddress}:${conn.remotePort}`,peer=new Peer(addr,"tcpIncoming");return peer.conn=conn,peer.addr=addr,peer.onConnect(),peer},exports.createTCPOutgoingPeer=(addr,swarm)=>{const peer=new Peer(addr,"tcpOutgoing");return peer.addr=addr,peer.swarm=swarm,peer},exports.createWebSeedPeer=(url,swarm)=>{const peer=new Peer(url,"webSeed");return peer.swarm=swarm,peer.conn=new WebConn(url,swarm),peer.onConnect(),peer};class Peer{constructor(id,type){this.id=id,this.type=type,debug("new %s Peer %s",type,id),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentHandshake=!1}onConnect(){if(!this.destroyed){this.connected=!0,debug("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const conn=this.conn;conn.once("end",()=>{this.destroy()}),conn.once("close",()=>{this.destroy()}),conn.once("finish",()=>{this.destroy()}),conn.once("error",err=>{this.destroy(err)});const wire=this.wire=new Wire;wire.type=this.type,wire.once("end",()=>{this.destroy()}),wire.once("close",()=>{this.destroy()}),wire.once("finish",()=>{this.destroy()}),wire.once("error",err=>{this.destroy(err)}),wire.once("handshake",(infoHash,peerId)=>{this.onHandshake(infoHash,peerId)}),this.startHandshakeTimeout(),conn.pipe(wire).pipe(conn),this.swarm&&!this.sentHandshake&&this.handshake()}}onHandshake(infoHash,peerId){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(infoHash!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(peerId===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));debug("Peer %s got handshake %s",this.id,infoHash),clearTimeout(this.handshakeTimeout),this.retries=0;let addr=this.addr;!addr&&this.conn.remoteAddress&&this.conn.remotePort&&(addr=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,addr);this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const opts={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,opts),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout),this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},"webrtc"===this.type?25e3:5e3),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout(()=>{this.destroy(new Error("handshake timeout"))},25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(err){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,debug("destroy %s (error: %s)",this.id,err&&(err.message||err)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const swarm=this.swarm,conn=this.conn,wire=this.wire;this.swarm=null,this.conn=null,this.wire=null,swarm&&wire&&arrayRemove(swarm.wires,swarm.wires.indexOf(wire)),conn&&(conn.on("error",()=>{}),conn.destroy()),wire&&wire.destroy(),swarm&&swarm.removePeer(this.id)}}},{"./webconn":6,"bittorrent-protocol":14,debug:30,"unordered-array-remove":115}],4:[function(require,module){module.exports=class{constructor(torrent){this._torrent=torrent,this._numPieces=torrent.pieces.length,this._pieces=Array(this._numPieces),this._onWire=wire=>{this.recalculate(),this._initWire(wire)},this._onWireHave=index=>{this._pieces[index]+=1},this._onWireBitfield=()=>{this.recalculate()},this._torrent.wires.forEach(wire=>{this._initWire(wire)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(pieceFilterFunc){let candidates=[],min=1/0;for(let i=0;i<this._numPieces;++i){if(pieceFilterFunc&&!pieceFilterFunc(i))continue;const availability=this._pieces[i];availability===min?candidates.push(i):availability<min&&(candidates=[i],min=availability)}return candidates.length?candidates[0|Math.random()*candidates.length]:-1}destroy(){this._torrent.removeListener("wire",this._onWire),this._torrent.wires.forEach(wire=>{this._cleanupWireEvents(wire)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(wire){wire._onClose=()=>{this._cleanupWireEvents(wire);for(let i=0;i<this._numPieces;++i)this._pieces[i]-=wire.peerPieces.get(i)},wire.on("have",this._onWireHave),wire.on("bitfield",this._onWireBitfield),wire.once("close",wire._onClose)}recalculate(){this._pieces.fill(0);for(const wire of this._torrent.wires)for(let i=0;i<this._numPieces;++i)this._pieces[i]+=wire.peerPieces.get(i)}_cleanupWireEvents(wire){wire.removeListener("have",this._onWireHave),wire.removeListener("bitfield",this._onWireBitfield),wire._onClose&&wire.removeListener("close",wire._onClose),wire._onClose=null}}},{}],5:[function(require,module){(function(process,global){function getBlockPipelineLength(wire,duration){return 2+_Mathceil(duration*wire.downloadSpeed()/Piece.BLOCK_LENGTH)}function getPiecePipelineLength(wire,duration,pieceLength){return 1+_Mathceil(duration*wire.downloadSpeed()/pieceLength)}function randomInt(high){return 0|Math.random()*high}function noop(){}const addrToIPPort=require("addr-to-ip-port"),BitField=require("bitfield"),ChunkStoreWriteStream=require("chunk-store-stream/write"),debug=require("debug")("webtorrent:torrent"),Discovery=require("torrent-discovery"),EventEmitter=require("events").EventEmitter,fs=require("fs"),FSChunkStore=require("fs-chunk-store"),get=require("simple-get"),ImmediateChunkStore=require("immediate-chunk-store"),MultiStream=require("multistream"),net=require("net"),os=require("os"),parallel=require("run-parallel"),parallelLimit=require("run-parallel-limit"),parseTorrent=require("parse-torrent"),path=require("path"),Piece=require("torrent-piece"),pump=require("pump"),randomIterate=require("random-iterate"),sha1=require("simple-sha1"),speedometer=require("speedometer"),utMetadata=require("ut_metadata"),utPex=require("ut_pex"),parseRange=require("parse-numeric-range"),File=require("./file"),Peer=require("./peer"),RarityMap=require("./rarity-map"),Server=require("./server"),CHOKE_TIMEOUT=5e3,SPEED_THRESHOLD=3*Piece.BLOCK_LENGTH,PIPELINE_MAX_DURATION=1,FILESYSTEM_CONCURRENCY=process.browser?1/0:2,RECONNECT_WAIT=[1e3,5e3,15e3],VERSION=require("../package.json").version,USER_AGENT=`WebTorrent/${VERSION} (https://webtorrent.io)`;let TMP;try{TMP=path.join(fs.statSync("/tmp")&&"/tmp","webtorrent")}catch(err){TMP=path.join("function"==typeof os.tmpdir?os.tmpdir():"/","webtorrent")}class Torrent extends EventEmitter{constructor(torrentId,client,opts){super(),this._debugId="unknown infohash",this.client=client,this.announce=opts.announce,this.urlList=opts.urlList,this.path=opts.path,this.skipVerify=!!opts.skipVerify,this._store=opts.store||FSChunkStore,this._getAnnounceOpts=opts.getAnnounceOpts,"boolean"==typeof opts.private&&(this.private=opts.private),this.strategy=opts.strategy||"sequential",this.maxWebConns=opts.maxWebConns||4,this._rechokeNumSlots=!1===opts.uploads||0===opts.uploads?0:+opts.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=!1,this.done=!1,this.metadata=null,this.store=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=speedometer(),this._uploadSpeed=speedometer(),this._servers=[],this._xsRequests=[],this._fileModtimes=opts.fileModtimes,null!==torrentId&&this._onTorrentId(torrentId),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:1e3*((this.length-this.downloaded)/this.downloadSpeed)}get downloaded(){if(!this.bitfield)return 0;let downloaded=0;for(let index=0,len=this.pieces.length;index<len;++index)if(this.bitfield.get(index))downloaded+=index===len-1?this.lastPieceLength:this.pieceLength;else{const piece=this.pieces[index];downloaded+=piece.length-piece.missing}return downloaded}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){return this.length?this.downloaded/this.length:0}get ratio(){return this.uploaded/(this.received||this.length)}get numPeers(){return this.wires.length}get torrentFileBlobURL(){if("undefined"==typeof window)throw new Error("browser-only property");return this.torrentFile?URL.createObjectURL(new Blob([this.torrentFile],{type:"application/x-bittorrent"})):null}get _numQueued(){return this._queue.length+(this._peersLength-this._numConns)}get _numConns(){let numConns=0;for(const id in this._peers)this._peers[id].connected&&(numConns+=1);return numConns}get swarm(){return console.warn("WebTorrent: `torrent.swarm` is deprecated. Use `torrent` directly instead."),this}_onTorrentId(torrentId){if(this.destroyed)return;let parsedTorrent;try{parsedTorrent=parseTorrent(torrentId)}catch(err){}parsedTorrent?(this.infoHash=parsedTorrent.infoHash,this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),process.nextTick(()=>{this.destroyed||this._onParsedTorrent(parsedTorrent)})):parseTorrent.remote(torrentId,(err,parsedTorrent)=>this.destroyed?void 0:err?this._destroy(err):void this._onParsedTorrent(parsedTorrent))}_onParsedTorrent(parsedTorrent){if(!this.destroyed){if(this._processParsedTorrent(parsedTorrent),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));(this.path||(this.path=path.join(TMP,this.infoHash)),this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),!this.destroyed)&&(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(parsedTorrent){this._debugId=parsedTorrent.infoHash.toString("hex").substring(0,7),"undefined"!=typeof this.private&&(parsedTorrent.private=this.private),this.announce&&(parsedTorrent.announce=parsedTorrent.announce.concat(this.announce)),this.client.tracker&&global.WEBTORRENT_ANNOUNCE&&!parsedTorrent.private&&(parsedTorrent.announce=parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)),this.urlList&&(parsedTorrent.urlList=parsedTorrent.urlList.concat(this.urlList)),parsedTorrent.announce=Array.from(new Set(parsedTorrent.announce)),parsedTorrent.urlList=Array.from(new Set(parsedTorrent.urlList)),Object.assign(this,parsedTorrent),this.magnetURI=parseTorrent.toMagnetURI(parsedTorrent),this.torrentFile=parseTorrent.toTorrentFile(parsedTorrent)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let trackerOpts=this.client.tracker;trackerOpts&&(trackerOpts=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const opts={uploaded:this.uploaded,downloaded:this.downloaded,left:_Mathmax(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(opts,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(opts,this._getAnnounceOpts()),opts}})),this.discovery=new Discovery({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:trackerOpts,port:this.client.torrentPort,userAgent:USER_AGENT}),this.discovery.on("error",err=>{this._destroy(err)}),this.discovery.on("peer",peer=>{"string"==typeof peer&&this.done||this.addPeer(peer)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",err=>{this.emit("warning",err)})}_getMetadataFromServer(){function getMetadataFromURL(url,cb){function onResponse(err,res,torrent){if(self.destroyed)return cb(null);if(self.metadata)return cb(null);if(err)return self.emit("warning",new Error(`http error from xs param: ${url}`)),cb(null);if(200!==res.statusCode)return self.emit("warning",new Error(`non-200 status code ${res.statusCode} from xs param: ${url}`)),cb(null);let parsedTorrent;try{parsedTorrent=parseTorrent(torrent)}catch(err){}return parsedTorrent?parsedTorrent.infoHash===self.infoHash?void(self._onMetadata(parsedTorrent),cb(null)):(self.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${url}`)),cb(null)):(self.emit("warning",new Error(`got invalid torrent file from xs param: ${url}`)),cb(null))}if(0!==url.indexOf("http://")&&0!==url.indexOf("https://"))return self.emit("warning",new Error(`skipping non-http xs param: ${url}`)),cb(null);let req;try{req=get.concat({url,method:"GET",headers:{"user-agent":USER_AGENT}},onResponse)}catch(err){return self.emit("warning",new Error(`skipping invalid url xs param: ${url}`)),cb(null)}self._xsRequests.push(req)}const self=this,urls=Array.isArray(this.xs)?this.xs:[this.xs],tasks=urls.map(url=>cb=>{getMetadataFromURL(url,cb)});parallel(tasks)}_onMetadata(metadata){if(this.metadata||this.destroyed)return;this._debug("got metadata"),this._xsRequests.forEach(req=>{req.abort()}),this._xsRequests=[];let parsedTorrent;if(metadata&&metadata.infoHash)parsedTorrent=metadata;else try{parsedTorrent=parseTorrent(metadata)}catch(err){return this._destroy(err)}if(this._processParsedTorrent(parsedTorrent),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(url=>{this.addWebSeed(url)}),this._rarityMap=new RarityMap(this),this.store=new ImmediateChunkStore(new this._store(this.pieceLength,{torrent:{infoHash:this.infoHash},files:this.files.map(file=>({path:path.join(this.path,file.path),length:file.length,offset:file.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(file=>new File(this,file)),this.so){const selectOnlyFiles=parseRange.parse(this.so);this.files.forEach((v,i)=>{selectOnlyFiles.includes(i)&&this.files[i].select(!0)})}else 0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1);if(this._hashes=this.pieces,this.pieces=this.pieces.map((hash,i)=>{const pieceLength=i===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new Piece(pieceLength)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new BitField(this.pieces.length),this.wires.forEach(wire=>{wire.ut_metadata&&wire.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(wire)}),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const onPiecesVerified=err=>err?this._destroy(err):void(this._debug("done verifying"),this._onStore());this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===FSChunkStore?this.getFileModtimes((err,fileModtimes)=>{if(err)return this._destroy(err);const unchanged=this.files.map((_,index)=>fileModtimes[index]===this._fileModtimes[index]).every(x=>x);unchanged?(this._markAllVerified(),this._onStore()):this._verifyPieces(onPiecesVerified)}):this._verifyPieces(onPiecesVerified)}}getFileModtimes(cb){const ret=[];parallelLimit(this.files.map((file,index)=>cb=>{fs.stat(path.join(this.path,file.path),(err,stat)=>err&&"ENOENT"!==err.code?cb(err):void(ret[index]=stat&&stat.mtime.getTime(),cb(null)))}),FILESYSTEM_CONCURRENCY,err=>{this._debug("done getting file modtimes"),cb(err,ret)})}_verifyPieces(cb){parallelLimit(this.pieces.map((piece,index)=>cb=>this.destroyed?cb(new Error("torrent is destroyed")):void this.store.get(index,(err,buf)=>this.destroyed?cb(new Error("torrent is destroyed")):err?process.nextTick(cb,null):void sha1(buf,hash=>{if(this.destroyed)return cb(new Error("torrent is destroyed"));if(hash===this._hashes[index]){if(!this.pieces[index])return cb(null);this._debug("piece verified %s",index),this._markVerified(index)}else this._debug("piece invalid %s",index);cb(null)}))),FILESYSTEM_CONCURRENCY,cb)}rescanFiles(cb){if(this.destroyed)throw new Error("torrent is destroyed");cb||(cb=noop),this._verifyPieces(err=>err?(this._destroy(err),cb(err)):void(this._checkDone(),cb(null)))}_markAllVerified(){for(let index=0;index<this.pieces.length;index++)this._markVerified(index)}_markVerified(index){this.pieces[index]=null,this._reservations[index]=null,this.bitfield.set(index,!0)}_onStore(){this.destroyed||(this._debug("on store"),this._startDiscovery(),this.ready=!0,this.emit("ready"),this._checkDone(),this._updateSelections())}destroy(cb){this._destroy(null,cb)}_destroy(err,cb){if(!this.destroyed){for(const id in this.destroyed=!0,this._debug("destroy"),this.client._remove(this),clearInterval(this._rechokeIntervalId),this._xsRequests.forEach(req=>{req.abort()}),this._rarityMap&&this._rarityMap.destroy(),this._peers)this.removePeer(id);this.files.forEach(file=>{file instanceof File&&file._destroy()});const tasks=this._servers.map(server=>cb=>{server.destroy(cb)});this.discovery&&tasks.push(cb=>{this.discovery.destroy(cb)}),this.store&&tasks.push(cb=>{this.store.close(cb)}),parallel(tasks,cb),err&&(0===this.listenerCount("error")?this.client.emit("error",err):this.emit("error",err)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}}addPeer(peer){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let host;if("string"==typeof peer){let parts;try{parts=addrToIPPort(peer)}catch(e){return this._debug("ignoring peer: invalid %s",peer),this.emit("invalidPeer",peer),!1}host=parts[0]}else"string"==typeof peer.remoteAddress&&(host=peer.remoteAddress);if(host&&this.client.blocked.contains(host))return this._debug("ignoring peer: blocked %s",peer),"string"!=typeof peer&&peer.destroy(),this.emit("blockedPeer",peer),!1}const wasAdded=!!this._addPeer(peer);return wasAdded?this.emit("peer",peer):this.emit("invalidPeer",peer),wasAdded}_addPeer(peer){if(this.destroyed)return"string"!=typeof peer&&peer.destroy(),null;if("string"==typeof peer&&!this._validAddr(peer))return this._debug("ignoring peer: invalid %s",peer),null;const id=peer&&peer.id||peer;if(this._peers[id])return this._debug("ignoring peer: duplicate (%s)",id),"string"!=typeof peer&&peer.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof peer&&peer.destroy(),null;this._debug("add peer %s",id);let newPeer;return newPeer="string"==typeof peer?Peer.createTCPOutgoingPeer(peer,this):Peer.createWebRTCPeer(peer,this),this._peers[newPeer.id]=newPeer,this._peersLength+=1,"string"==typeof peer&&(this._queue.push(newPeer),this._drain()),newPeer}addWebSeed(url){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(url))return this.emit("warning",new Error(`ignoring invalid web seed: ${url}`)),void this.emit("invalidPeer",url);if(this._peers[url])return this.emit("warning",new Error(`ignoring duplicate web seed: ${url}`)),void this.emit("invalidPeer",url);this._debug("add web seed %s",url);const newPeer=Peer.createWebSeedPeer(url,this);this._peers[newPeer.id]=newPeer,this._peersLength+=1,this.emit("peer",url)}_addIncomingPeer(peer){return this.destroyed?peer.destroy(new Error("torrent is destroyed")):this.paused?peer.destroy(new Error("torrent is paused")):void(this._debug("add incoming peer %s",peer.id),this._peers[peer.id]=peer,this._peersLength+=1)}removePeer(peer){const id=peer&&peer.id||peer;peer=this._peers[id];peer&&(this._debug("removePeer %s",id),delete this._peers[id],this._peersLength-=1,peer.destroy(),this._drain())}select(start,end,priority,notify){if(this.destroyed)throw new Error("torrent is destroyed");if(0>start||end<start||this.pieces.length<=end)throw new Error(`invalid selection ${start} : ${end}`);priority=+priority||0,this._debug("select %s-%s (priority %s)",start,end,priority),this._selections.push({from:start,to:end,offset:0,priority,notify:notify||noop}),this._selections.sort((a,b)=>b.priority-a.priority),this._updateSelections()}deselect(start,end,priority){if(this.destroyed)throw new Error("torrent is destroyed");priority=+priority||0,this._debug("deselect %s-%s (priority %s)",start,end,priority);for(let i=0;i<this._selections.length;++i){const s=this._selections[i];if(s.from===start&&s.to===end&&s.priority===priority){this._selections.splice(i,1);break}}this._updateSelections()}critical(start,end){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("critical %s-%s",start,end);for(let i=start;i<=end;++i)this._critical[i]=!0;this._updateSelections()}_onWire(wire,addr){if(this._debug("got wire %s (%s)",wire._debugId,addr||"Unknown"),wire.on("download",downloaded=>{this.destroyed||(this.received+=downloaded,this._downloadSpeed(downloaded),this.client._downloadSpeed(downloaded),this.emit("download",downloaded),this.client.emit("download",downloaded))}),wire.on("upload",uploaded=>{this.destroyed||(this.uploaded+=uploaded,this._uploadSpeed(uploaded),this.client._uploadSpeed(uploaded),this.emit("upload",uploaded),this.client.emit("upload",uploaded))}),this.wires.push(wire),addr){const parts=addrToIPPort(addr);wire.remoteAddress=parts[0],wire.remotePort=parts[1]}this.client.dht&&this.client.dht.listening&&wire.on("port",port=>this.destroyed||this.client.dht.destroyed?void 0:wire.remoteAddress?0===port||65536<port?this._debug("ignoring invalid PORT from peer"):void(this._debug("port: %s (from %s)",port,addr),this.client.dht.addNode({host:wire.remoteAddress,port})):this._debug("ignoring PORT from peer with no address")),wire.on("timeout",()=>{this._debug("wire timeout (%s)",addr),wire.destroy()}),wire.setTimeout(3e4,!0),wire.setKeepAlive(!0),wire.use(utMetadata(this.metadata)),wire.ut_metadata.on("warning",err=>{this._debug("ut_metadata warning: %s",err.message)}),this.metadata||(wire.ut_metadata.on("metadata",metadata=>{this._debug("got metadata via ut_metadata"),this._onMetadata(metadata)}),wire.ut_metadata.fetch()),"function"!=typeof utPex||this.private||(wire.use(utPex()),wire.ut_pex.on("peer",peer=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",peer,addr),this.addPeer(peer))}),wire.ut_pex.on("dropped",peer=>{const peerObj=this._peers[peer];peerObj&&!peerObj.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",peer,addr),this.removePeer(peer))}),wire.once("close",()=>{wire.ut_pex.reset()})),this.emit("wire",wire,addr),this.metadata&&process.nextTick(()=>{this._onWireWithMetadata(wire)})}_onWireWithMetadata(wire){let timeoutId=null;const onChokeTimeout=()=>{this.destroyed||wire.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&wire.amInterested?wire.destroy():(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()))};let i;const updateSeedStatus=()=>{if(wire.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i<this.pieces.length;++i)if(!wire.peerPieces.get(i))return;wire.isSeeder=!0,wire.choke()}};wire.on("bitfield",()=>{updateSeedStatus(),this._update()}),wire.on("have",()=>{updateSeedStatus(),this._update()}),wire.once("interested",()=>{wire.unchoke()}),wire.once("close",()=>{clearTimeout(timeoutId)}),wire.on("choke",()=>{clearTimeout(timeoutId),timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()}),wire.on("unchoke",()=>{clearTimeout(timeoutId),this._update()}),wire.on("request",(index,offset,length,cb)=>length>131072?wire.destroy():void(this.pieces[index]||this.store.get(index,{offset,length},cb))),wire.bitfield(this.bitfield),wire.uninterested(),wire.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&wire.port(this.client.dht.address().port),"webSeed"!==wire.type&&(timeoutId=setTimeout(onChokeTimeout,CHOKE_TIMEOUT),timeoutId.unref&&timeoutId.unref()),wire.isSeeder=!1,updateSeedStatus()}_updateSelections(){!this.ready||this.destroyed||(process.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let i=0;i<this._selections.length;++i){const s=this._selections[i],oldOffset=s.offset;for(;this.bitfield.get(s.from+s.offset)&&s.from+s.offset<s.to;)s.offset+=1;oldOffset!==s.offset&&s.notify(),s.to===s.from+s.offset&&this.bitfield.get(s.from+s.offset)&&(this._selections.splice(i,1),i-=1,s.notify(),this._updateInterest())}this._selections.length||this.emit("idle")}_updateInterest(){const prev=this._amInterested;this._amInterested=!!this._selections.length,this.wires.forEach(wire=>{let interested=!1;for(let index=0;index<this.pieces.length;++index)if(this.pieces[index]&&wire.peerPieces.get(index)){interested=!0;break}interested?wire.interested():wire.uninterested()});prev===this._amInterested||(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_update(){if(!this.destroyed){const ite=randomIterate(this.wires);for(let wire;wire=ite();)this._updateWireWrapper(wire)}}_updateWireWrapper(wire){const self=this;"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?window.requestIdleCallback(function(){self._updateWire(wire)},{timeout:250}):self._updateWire(wire)}_updateWire(wire){function genPieceFilterFunc(start,end,tried,rank){return i=>i>=start&&i<=end&&!(i in tried)&&wire.peerPieces.get(i)&&(!rank||rank(i))}function speedRanker(){const speed=wire.downloadSpeed()||1;if(speed>SPEED_THRESHOLD)return()=>!0;const secs=_Mathmax(1,wire.requests.length)*Piece.BLOCK_LENGTH/speed;let tries=10,ptr=0;return index=>{if(!tries||self.bitfield.get(index))return!0;for(let missing=self.pieces[index].missing;ptr<self.wires.length;ptr++){const otherWire=self.wires[ptr],otherSpeed=otherWire.downloadSpeed();if(!(otherSpeed<SPEED_THRESHOLD)&&!(otherSpeed<=speed)&&otherWire.peerPieces.get(index)&&!(0<(missing-=otherSpeed*secs)))return tries--,!1}return!0}}function shufflePriority(i){let last=i;for(let j=i;j<self._selections.length&&self._selections[j].priority;j++)last=j;const tmp=self._selections[i];self._selections[i]=self._selections[last],self._selections[last]=tmp}function trySelectWire(hotswap){if(wire.requests.length>=maxOutstandingRequests)return!0;const rank=speedRanker();for(let i=0;i<self._selections.length;i++){const next=self._selections[i];let piece;if("rarest"===self.strategy){const start=next.from+next.offset,end=next.to,tried={};let tries=0;for(const filter=genPieceFilterFunc(start,end,tried,rank);tries<end-start+1&&(piece=self._rarityMap.getRarestPiece(filter),!(0>piece));){for(;self._request(wire,piece,self._critical[piece]||hotswap););if(wire.requests.length<maxOutstandingRequests){tried[piece]=!0,tries++;continue}return next.priority&&shufflePriority(i),!0}}else for(piece=next.from+next.offset;piece<=next.to;piece++)if(wire.peerPieces.get(piece)&&rank(piece)){for(;self._request(wire,piece,self._critical[piece]||hotswap););if(!(wire.requests.length<maxOutstandingRequests))return next.priority&&shufflePriority(i),!0}}return!1}const self=this;if(wire.peerChoking)return;if(!wire.downloaded)return function(){if(!wire.requests.length)for(let i=self._selections.length;i--;){const next=self._selections[i];let piece;if("rarest"===self.strategy){const start=next.from+next.offset,end=next.to,tried={};let tries=0;for(const filter=genPieceFilterFunc(start,end,tried);tries<end-start+1&&(piece=self._rarityMap.getRarestPiece(filter),!(0>piece));){if(self._request(wire,piece,!1))return;tried[piece]=!0,tries+=1}}else for(piece=next.to;piece>=next.from+next.offset;--piece)if(wire.peerPieces.get(piece)&&self._request(wire,piece,!1))return}}();const minOutstandingRequests=getBlockPipelineLength(wire,.5);if(wire.requests.length>=minOutstandingRequests)return;const maxOutstandingRequests=getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);trySelectWire(!1)||trySelectWire(!0)}_rechoke(){if(!this.ready)return;0<this._rechokeOptimisticTime?this._rechokeOptimisticTime-=1:this._rechokeOptimisticWire=null;const peers=[];this.wires.forEach(wire=>{wire.isSeeder||wire===this._rechokeOptimisticWire||peers.push({wire,downloadSpeed:wire.downloadSpeed(),uploadSpeed:wire.uploadSpeed(),salt:Math.random(),isChoked:!0})}),peers.sort(function(peerA,peerB){return peerA.downloadSpeed===peerB.downloadSpeed?peerA.uploadSpeed===peerB.uploadSpeed?peerA.wire.amChoking===peerB.wire.amChoking?peerA.salt-peerB.salt:peerA.wire.amChoking?1:-1:peerB.uploadSpeed-peerA.uploadSpeed:peerB.downloadSpeed-peerA.downloadSpeed});let unchokeInterested=0,i=0;for(;i<peers.length&&unchokeInterested<this._rechokeNumSlots;++i)peers[i].isChoked=!1,peers[i].wire.peerInterested&&(unchokeInterested+=1);if(!this._rechokeOptimisticWire&&i<peers.length&&this._rechokeNumSlots){const candidates=peers.slice(i).filter(peer=>peer.wire.peerInterested),optimistic=candidates[randomInt(candidates.length)];optimistic&&(optimistic.isChoked=!1,this._rechokeOptimisticWire=optimistic.wire,this._rechokeOptimisticTime=2)}peers.forEach(peer=>{peer.wire.amChoking!==peer.isChoked&&(peer.isChoked?peer.wire.choke():peer.wire.unchoke())})}_hotswap(wire,index){const speed=wire.downloadSpeed();if(speed<Piece.BLOCK_LENGTH)return!1;if(!this._reservations[index])return!1;const r=this._reservations[index];if(!r)return!1;let minSpeed=1/0,minWire,i;for(i=0;i<r.length;i++){const otherWire=r[i];if(!otherWire||otherWire===wire)continue;const otherSpeed=otherWire.downloadSpeed();otherSpeed>=SPEED_THRESHOLD||2*otherSpeed>speed||otherSpeed>minSpeed||(minWire=otherWire,minSpeed=otherSpeed)}if(!minWire)return!1;for(i=0;i<r.length;i++)r[i]===minWire&&(r[i]=null);for(i=0;i<minWire.requests.length;i++){const req=minWire.requests[i];req.piece===index&&this.pieces[index].cancel(0|req.offset/Piece.BLOCK_LENGTH)}return this.emit("hotswap",minWire,wire,index),!0}_request(wire,index,hotswap){function onUpdateTick(){process.nextTick(()=>{self._update()})}const self=this,numRequests=wire.requests.length,isWebSeed="webSeed"===wire.type;if(self.bitfield.get(index))return!1;const maxOutstandingRequests=isWebSeed?_Mathmin(getPiecePipelineLength(wire,PIPELINE_MAX_DURATION,self.pieceLength),self.maxWebConns):getBlockPipelineLength(wire,PIPELINE_MAX_DURATION);if(numRequests>=maxOutstandingRequests)return!1;const piece=self.pieces[index];let reservation=isWebSeed?piece.reserveRemaining():piece.reserve();if(-1===reservation&&hotswap&&self._hotswap(wire,index)&&(reservation=isWebSeed?piece.reserveRemaining():piece.reserve()),-1===reservation)return!1;let r=self._reservations[index];r||(r=self._reservations[index]=[]);let i=r.indexOf(null);-1===i&&(i=r.length),r[i]=wire;const chunkOffset=piece.chunkOffset(reservation),chunkLength=isWebSeed?piece.chunkLengthRemaining(reservation):piece.chunkLength(reservation);return wire.request(index,chunkOffset,chunkLength,function onChunk(err,chunk){if(self.destroyed)return;if(!self.ready)return self.once("ready",()=>{onChunk(err,chunk)});if(r[i]===wire&&(r[i]=null),piece!==self.pieces[index])return onUpdateTick();if(err)return self._debug("error getting piece %s (offset: %s length: %s) from %s: %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`,err.message),isWebSeed?piece.cancelRemaining(reservation):piece.cancel(reservation),void onUpdateTick();if(self._debug("got piece %s (offset: %s length: %s) from %s",index,chunkOffset,chunkLength,`${wire.remoteAddress}:${wire.remotePort}`),!piece.set(reservation,chunk,wire))return onUpdateTick();const buf=piece.flush();sha1(buf,hash=>{if(!self.destroyed){if(hash===self._hashes[index]){if(!self.pieces[index])return;self._debug("piece verified %s",index),self.pieces[index]=null,self._reservations[index]=null,self.bitfield.set(index,!0),self.store.put(index,buf),self.wires.forEach(wire=>{wire.have(index)}),self._checkDone()&&!self.destroyed&&self.discovery.complete()}else self.pieces[index]=new Piece(piece.length),self.emit("warning",new Error(`Piece ${index} failed verification`));onUpdateTick()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(file=>{if(!file.done){for(let i=file._startPiece;i<=file._endPiece;++i)if(!this.bitfield.get(i))return;file.done=!0,file.emit("done"),this._debug(`file done: ${file.name}`)}});let done=!0;for(let i=0;i<this._selections.length;i++){const selection=this._selections[i];for(let piece=selection.from;piece<=selection.to;piece++)if(!this.bitfield.get(piece)){done=!1;break}if(!done)break}return!this.done&&done&&(this.done=!0,this._debug(`torrent done: ${this.infoHash}`),this.emit("done")),this._gcSelections(),done}load(streams,cb){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.ready)return this.once("ready",()=>{this.load(streams,cb)});Array.isArray(streams)||(streams=[streams]),cb||(cb=noop);const readable=new MultiStream(streams),writable=new ChunkStoreWriteStream(this.store,this.pieceLength);pump(readable,writable,err=>err?cb(err):void(this._markAllVerified(),this._checkDone(),cb(null)))}createServer(requestListener){if("function"!=typeof Server)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const server=new Server(this,requestListener);return this._servers.push(server),server}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const args=[].slice.call(arguments);args[0]=`[${this.client?this.client._debugId:"No Client"}] [${this._debugId}] ${args[0]}`,debug(...args)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof net.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const peer=this._queue.shift();if(!peer)return;this._debug("tcp connect attempt to %s",peer.addr);const parts=addrToIPPort(peer.addr),opts={host:parts[0],port:parts[1]},conn=peer.conn=net.connect(opts);conn.once("connect",()=>{peer.onConnect()}),conn.once("error",err=>{peer.destroy(err)}),peer.startConnectTimeout(),conn.on("close",()=>{if(!this.destroyed){if(peer.retries>=RECONNECT_WAIT.length)return void this._debug("conn %s closed: will not re-add (max %s attempts)",peer.addr,RECONNECT_WAIT.length);const ms=RECONNECT_WAIT[peer.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",peer.addr,ms,peer.retries+1);const reconnectTimeout=setTimeout(()=>{const newPeer=this._addPeer(peer.addr);newPeer&&(newPeer.retries=peer.retries+1)},ms);reconnectTimeout.unref&&reconnectTimeout.unref()}})}_validAddr(addr){let parts;try{parts=addrToIPPort(addr)}catch(e){return!1}const host=parts[0],port=parts[1];return 0<port&&65535>port&&("127.0.0.1"!==host||port!==this.client.torrentPort)}}module.exports=Torrent}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../package.json":124,"./file":2,"./peer":3,"./rarity-map":4,"./server":21,_process:61,"addr-to-ip-port":7,bitfield:13,"chunk-store-stream/write":28,debug:30,events:33,fs:22,"fs-chunk-store":46,"immediate-chunk-store":38,multistream:54,net:21,os:21,"parse-numeric-range":57,"parse-torrent":58,path:59,pump:62,"random-iterate":68,"run-parallel":89,"run-parallel-limit":88,"simple-get":93,"simple-sha1":95,speedometer:98,"torrent-discovery":110,"torrent-piece":111,ut_metadata:118,ut_pex:21}],6:[function(require,module){(function(Buffer){const BitField=require("bitfield"),debug=require("debug")("webtorrent:webconn"),get=require("simple-get"),sha1=require("simple-sha1"),Wire=require("bittorrent-protocol"),VERSION=require("../package.json").version;module.exports=class extends Wire{constructor(url,torrent){super(),this.url=url,this.webPeerId=sha1.sync(url),this._torrent=torrent,this._init()}_init(){this.setKeepAlive(!0),this.once("handshake",infoHash=>{if(this.destroyed)return;this.handshake(infoHash,this.webPeerId);const numPieces=this._torrent.pieces.length,bitfield=new BitField(numPieces);for(let i=0;i<=numPieces;i++)bitfield.set(i,!0);this.bitfield(bitfield)}),this.once("interested",()=>{debug("interested"),this.unchoke()}),this.on("uninterested",()=>{debug("uninterested")}),this.on("choke",()=>{debug("choke")}),this.on("unchoke",()=>{debug("unchoke")}),this.on("bitfield",()=>{debug("bitfield")}),this.on("request",(pieceIndex,offset,length,callback)=>{debug("request pieceIndex=%d offset=%d length=%d",pieceIndex,offset,length),this.httpRequest(pieceIndex,offset,length,callback)})}httpRequest(pieceIndex,offset,length,cb){const pieceOffset=pieceIndex*this._torrent.pieceLength,rangeStart=pieceOffset+offset,rangeEnd=rangeStart+length-1,files=this._torrent.files;let requests;if(1>=files.length)requests=[{url:this.url,start:rangeStart,end:rangeEnd}];else{const requestedFiles=files.filter(file=>file.offset<=rangeEnd&&file.offset+file.length>rangeStart);if(1>requestedFiles.length)return cb(new Error("Could not find file corresponnding to web seed range request"));requests=requestedFiles.map(requestedFile=>{const fileEnd=requestedFile.offset+requestedFile.length-1,url=this.url+("/"===this.url[this.url.length-1]?"":"/")+requestedFile.path;return{url,fileOffsetInRange:_Mathmax(requestedFile.offset-rangeStart,0),start:_Mathmax(rangeStart-requestedFile.offset,0),end:_Mathmin(fileEnd,rangeEnd-requestedFile.offset)}})}let numRequestsSucceeded=0,hasError=!1,ret;1<requests.length&&(ret=Buffer.alloc(length)),requests.forEach(request=>{function onResponse(res,data){return 200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):void(debug("Got data of length %d",data.length),1===requests.length?cb(null,data):(data.copy(ret,request.fileOffsetInRange),++numRequestsSucceeded===requests.length&&cb(null,ret)))}const url=request.url,start=request.start,end=request.end;debug("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",url,pieceIndex,offset,length,start,end);const opts={url,method:"GET",headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`,range:`bytes=${start}-${end}`}};get.concat(opts,(err,res,data)=>hasError?void 0:err?"undefined"==typeof window||url.startsWith(`${window.location.origin}/`)?(hasError=!0,cb(err)):get.head(url,(errHead,res)=>hasError?void 0:errHead?(hasError=!0,cb(errHead)):200>res.statusCode||300<=res.statusCode?(hasError=!0,cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))):res.url===url?(hasError=!0,cb(err)):void(opts.url=res.url,get.concat(opts,(err,res,data)=>hasError?void 0:err?(hasError=!0,cb(err)):void onResponse(res,data)))):void onResponse(res,data))})}destroy(){super.destroy(),this._torrent=null}}}).call(this,require("buffer").Buffer)},{"../package.json":124,bitfield:13,"bittorrent-protocol":14,buffer:26,debug:30,"simple-get":93,"simple-sha1":95}],7:[function(require,module){let cache={},size=0;module.exports=function(addr){if(1e5===size&&module.exports.reset(),!cache[addr]){const m=/^\[?([^\]]+)\]?:(\d+)$/.exec(addr);if(!m)throw new Error(`invalid addr: ${addr}`);cache[addr]=[m[1],+m[2]],size+=1}return cache[addr]},module.exports.reset=function(){cache={},size=0}},{}],8:[function(require,module,exports){'use strict';function getLens(b64){var len=b64.length;if(0<len%4)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");-1===validLen&&(validLen=len);var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=0<placeHoldersLen?validLen-4:validLen,tmp,i;for(i=0;i<len;i+=4)tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)],arr[curByte++]=255&tmp>>16,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=255&tmp>>8,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[63&num>>18]+lookup[63&num>>12]+lookup[63&num>>6]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var output=[],i=start,tmp;i<end;i+=3)tmp=(16711680&uint8[i]<<16)+(65280&uint8[i+1]<<8)+(255&uint8[i+2]),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var len=uint8.length,extraBytes=len%3,parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes,tmp;i<len2;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[63&tmp<<4]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[63&tmp>>4]+lookup[63&tmp<<2]+"=")),parts.join("")}exports.byteLength=function(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen},exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"==typeof Uint8Array?Array:Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup[45]=62,revLookup[95]=63},{}],9:[function(require,module){function getIntFromBuffer(buffer,start,end){for(var sum=0,sign=1,i=start,num;i<end;i++){if(num=buffer[i],58>num&&48<=num){sum=10*sum+(num-48);continue}if(i!==start||43!==num){if(i===start&&45===num){sign=-1;continue}if(46===num)break;throw new Error("not a number: buffer["+i+"] = "+num)}}return sum*sign}function decode(data,start,end,encoding){return null==data||0===data.length?null:("number"!=typeof start&&null==encoding&&(encoding=start,start=void 0),"number"!=typeof end&&null==encoding&&(encoding=end,end=void 0),decode.position=0,decode.encoding=encoding||null,decode.data=Buffer.isBuffer(data)?data.slice(start,end):Buffer.from(data),decode.bytes=decode.data.length,decode.next())}var Buffer=require("safe-buffer").Buffer;const END_OF_TYPE=101;decode.bytes=0,decode.position=0,decode.data=null,decode.encoding=null,decode.next=function(){switch(decode.data[decode.position]){case 100:return decode.dictionary();case 108:return decode.list();case 105:return decode.integer();default:return decode.buffer();}},decode.find=function(chr){for(var i=decode.position,c=decode.data.length,d=decode.data;i<c;){if(d[i]===chr)return i;i++}throw new Error("Invalid data: Missing delimiter \""+_StringfromCharCode(chr)+"\" [0x"+chr.toString(16)+"]")},decode.dictionary=function(){decode.position++;for(var dict={};decode.data[decode.position]!==END_OF_TYPE;)dict[decode.buffer()]=decode.next();return decode.position++,dict},decode.list=function(){decode.position++;for(var lst=[];decode.data[decode.position]!==END_OF_TYPE;)lst.push(decode.next());return decode.position++,lst},decode.integer=function(){var end=decode.find(END_OF_TYPE),number=getIntFromBuffer(decode.data,decode.position+1,end);return decode.position+=end+1-decode.position,number},decode.buffer=function(){var sep=decode.find(58),length=getIntFromBuffer(decode.data,decode.position,sep),end=++sep+length;return decode.position=end,decode.encoding?decode.data.toString(decode.encoding,sep,end):decode.data.slice(sep,end)},module.exports=decode},{"safe-buffer":91}],10:[function(require,module){function encode(data,buffer,offset){var buffers=[],result=null;return encode._encode(buffers,data),result=Buffer.concat(buffers),encode.bytes=result.length,Buffer.isBuffer(buffer)?(result.copy(buffer,offset),buffer):result}var Buffer=require("safe-buffer").Buffer;encode.bytes=-1,encode._floatConversionDetected=!1,encode.getType=function(value){return Buffer.isBuffer(value)?"buffer":Array.isArray(value)?"array":ArrayBuffer.isView(value)?"arraybufferview":value instanceof Number?"number":value instanceof Boolean?"boolean":value instanceof ArrayBuffer?"arraybuffer":typeof value},encode._encode=function(buffers,data){if(null!=data)switch(encode.getType(data)){case"buffer":encode.buffer(buffers,data);break;case"object":encode.dict(buffers,data);break;case"array":encode.list(buffers,data);break;case"string":encode.string(buffers,data);break;case"number":encode.number(buffers,data);break;case"boolean":encode.number(buffers,data);break;case"arraybufferview":encode.buffer(buffers,Buffer.from(data.buffer,data.byteOffset,data.byteLength));break;case"arraybuffer":encode.buffer(buffers,Buffer.from(data));}};var buffE=Buffer.from("e"),buffD=Buffer.from("d"),buffL=Buffer.from("l");encode.buffer=function(buffers,data){buffers.push(Buffer.from(data.length+":"),data)},encode.string=function(buffers,data){buffers.push(Buffer.from(Buffer.byteLength(data)+":"+data))},encode.number=function(buffers,data){var val=(data/2147483648<<0)*2147483648+(data%2147483648<<0);buffers.push(Buffer.from("i"+val+"e")),val===data||encode._floatConversionDetected||(encode._floatConversionDetected=!0,console.warn("WARNING: Possible data corruption detected with value \""+data+"\":","Bencoding only defines support for integers, value was converted to \""+val+"\""),console.trace())},encode.dict=function(buffers,data){buffers.push(buffD);for(var j=0,keys=Object.keys(data).sort(),kl=keys.length,k;j<kl;j++)k=keys[j],null==data[k]||(encode.string(buffers,k),encode._encode(buffers,data[k]));buffers.push(buffE)},encode.list=function(buffers,data){var i=0,c=data.length;for(buffers.push(buffL);i<c;i++)null!=data[i]&&encode._encode(buffers,data[i]);buffers.push(buffE)},module.exports=encode},{"safe-buffer":91}],11:[function(require,module){var bencode=module.exports;bencode.encode=require("./encode"),bencode.decode=require("./decode"),bencode.byteLength=bencode.encodingLength=function(value){return bencode.encode(value).length}},{"./decode":9,"./encode":10}],12:[function(require,module){module.exports=function(haystack,needle,comparator,low,high){var mid,cmp;if(void 0===low)low=0;else if(low|=0,0>low||low>=haystack.length)throw new RangeError("invalid lower bound");if(void 0===high)high=haystack.length-1;else if(high|=0,high<low||high>=haystack.length)throw new RangeError("invalid upper bound");for(;low<=high;)if(mid=low+(high-low>>>1),cmp=+comparator(haystack[mid],needle,mid,haystack),0>cmp)low=mid+1;else if(0<cmp)high=mid-1;else return mid;return~low}},{}],13:[function(require,module){function getByteSize(num){let out=num>>3;return 0!=num%8&&out++,out}"undefined"!=typeof module&&(module.exports=class{constructor(data=0,opts){const grow=null!=opts&&opts.grow;this.grow=grow&&isFinite(grow)&&getByteSize(grow)||grow||0,this.buffer="number"==typeof data?new Uint8Array(getByteSize(data)):data}get(i){const j=i>>3;return j<this.buffer.length&&!!(this.buffer[j]&128>>i%8)}set(i,b=!0){const j=i>>3;if(b){if(this.buffer.length<j+1){const length=_Mathmax(j+1,_Mathmin(2*this.buffer.length,this.grow));if(length<=this.grow){const newBuffer=new Uint8Array(length);newBuffer.set(this.buffer),this.buffer=newBuffer}}this.buffer[j]|=128>>i%8}else j<this.buffer.length&&(this.buffer[j]&=~(128>>i%8))}})},{}],14:[function(require,module){(function(Buffer){const arrayRemove=require("unordered-array-remove"),bencode=require("bencode"),BitField=require("bitfield"),debug=require("debug")("bittorrent-protocol"),randombytes=require("randombytes"),speedometer=require("speedometer"),stream=require("readable-stream"),MESSAGE_PROTOCOL=Buffer.from("\x13BitTorrent protocol"),MESSAGE_KEEP_ALIVE=Buffer.from([0,0,0,0]),MESSAGE_CHOKE=Buffer.from([0,0,0,1,0]),MESSAGE_UNCHOKE=Buffer.from([0,0,0,1,1]),MESSAGE_INTERESTED=Buffer.from([0,0,0,1,2]),MESSAGE_UNINTERESTED=Buffer.from([0,0,0,1,3]),MESSAGE_RESERVED=[0,0,0,0,0,0,0,0],MESSAGE_PORT=[0,0,0,3,9,0,0];class Request{constructor(piece,offset,length,callback){this.piece=piece,this.offset=offset,this.length=length,this.callback=callback}}class Wire extends stream.Duplex{constructor(){super(),this._debugId=randombytes(4).toString("hex"),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=null,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new BitField(0,{grow:4e5}),this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=speedometer(),this.downloadSpeed=speedometer(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this.destroyed=!1,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this.once("finish",()=>this._onFinish()),this._parseHandshake()}setKeepAlive(enable){this._debug("setKeepAlive %s",enable),clearInterval(this._keepAliveInterval);!1===enable||(this._keepAliveInterval=setInterval(()=>{this.keepAlive()},55e3))}setTimeout(ms,unref){this._debug("setTimeout ms=%d unref=%s",ms,unref),this._clearTimeout(),this._timeoutMs=ms,this._timeoutUnref=!!unref,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...args){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...args)}use(Extension){function noop(){}const name=Extension.prototype.name;if(!name)throw new Error("Extension class requires a \"name\" property on the prototype");this._debug("use extension.name=%s",name);const ext=this._nextExt,handler=new Extension(this);"function"!=typeof handler.onHandshake&&(handler.onHandshake=noop),"function"!=typeof handler.onExtendedHandshake&&(handler.onExtendedHandshake=noop),"function"!=typeof handler.onMessage&&(handler.onMessage=noop),this.extendedMapping[ext]=name,this._ext[name]=handler,this[name]=handler,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(MESSAGE_KEEP_ALIVE)}handshake(infoHash,peerId,extensions){let infoHashBuffer,peerIdBuffer;if("string"==typeof infoHash?(infoHash=infoHash.toLowerCase(),infoHashBuffer=Buffer.from(infoHash,"hex")):(infoHashBuffer=infoHash,infoHash=infoHashBuffer.toString("hex")),"string"==typeof peerId?peerIdBuffer=Buffer.from(peerId,"hex"):(peerIdBuffer=peerId,peerId=peerIdBuffer.toString("hex")),20!==infoHashBuffer.length||20!==peerIdBuffer.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",infoHash,peerId,extensions);const reserved=Buffer.from(MESSAGE_RESERVED);reserved[5]|=16,extensions&&extensions.dht&&(reserved[7]|=1),this._push(Buffer.concat([MESSAGE_PROTOCOL,reserved,infoHashBuffer,peerIdBuffer])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const msg=Object.assign({},this.extendedHandshake);for(const ext in msg.m={},this.extendedMapping){const name=this.extendedMapping[ext];msg.m[name]=+ext}this.extended(0,bencode.encode(msg)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(MESSAGE_CHOKE)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(MESSAGE_UNCHOKE))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(MESSAGE_INTERESTED))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(MESSAGE_UNINTERESTED))}have(index){this._debug("have %d",index),this._message(4,[index],null)}bitfield(bitfield){this._debug("bitfield"),Buffer.isBuffer(bitfield)||(bitfield=bitfield.buffer),this._message(5,[],bitfield)}request(index,offset,length,cb){return cb||(cb=()=>{}),this._finished?cb(new Error("wire is closed")):this.peerChoking?cb(new Error("peer is choking")):void(this._debug("request index=%d offset=%d length=%d",index,offset,length),this.requests.push(new Request(index,offset,length,cb)),this._updateTimeout(),this._message(6,[index,offset,length],null))}piece(index,offset,buffer){this._debug("piece index=%d offset=%d",index,offset),this.uploaded+=buffer.length,this.uploadSpeed(buffer.length),this.emit("upload",buffer.length),this._message(7,[index,offset],buffer)}cancel(index,offset,length){this._debug("cancel index=%d offset=%d length=%d",index,offset,length),this._callback(this._pull(this.requests,index,offset,length),new Error("request was cancelled"),null),this._message(8,[index,offset,length],null)}port(port){this._debug("port %d",port);const message=Buffer.from(MESSAGE_PORT);message.writeUInt16BE(port,5),this._push(message)}extended(ext,obj){if(this._debug("extended ext=%s",ext),"string"==typeof ext&&this.peerExtendedMapping[ext]&&(ext=this.peerExtendedMapping[ext]),"number"==typeof ext){const extId=Buffer.from([ext]),buf=Buffer.isBuffer(obj)?obj:bencode.encode(obj);this._message(20,[],Buffer.concat([extId,buf]))}else throw new Error(`Unrecognized extension: ${ext}`)}_read(){}_message(id,numbers,data){const dataLength=data?data.length:0,buffer=Buffer.allocUnsafe(5+4*numbers.length);buffer.writeUInt32BE(buffer.length+dataLength-4,0),buffer[4]=id;for(let i=0;i<numbers.length;i++)buffer.writeUInt32BE(numbers[i],5+4*i);this._push(buffer),data&&this._push(data)}_push(data){return this._finished?void 0:this.push(data)}_onKeepAlive(){this._debug("got keep-alive"),this.emit("keep-alive")}_onHandshake(infoHashBuffer,peerIdBuffer,extensions){const infoHash=infoHashBuffer.toString("hex"),peerId=peerIdBuffer.toString("hex");this._debug("got handshake i=%s p=%s exts=%o",infoHash,peerId,extensions),this.peerId=peerId,this.peerIdBuffer=peerIdBuffer,this.peerExtensions=extensions,this.emit("handshake",infoHash,peerId,extensions);for(var name in this._ext)this._ext[name].onHandshake(infoHash,peerId,extensions);extensions.extended&&this._handshakeSent&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_onChoke(){for(this.peerChoking=!0,this._debug("got choke"),this.emit("choke");this.requests.length;)this._callback(this.requests.pop(),new Error("peer is choking"),null)}_onUnchoke(){this.peerChoking=!1,this._debug("got unchoke"),this.emit("unchoke")}_onInterested(){this.peerInterested=!0,this._debug("got interested"),this.emit("interested")}_onUninterested(){this.peerInterested=!1,this._debug("got uninterested"),this.emit("uninterested")}_onHave(index){this.peerPieces.get(index)||(this._debug("got have %d",index),this.peerPieces.set(index,!0),this.emit("have",index))}_onBitField(buffer){this.peerPieces=new BitField(buffer),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(index,offset,length){if(!this.amChoking){this._debug("got request index=%d offset=%d length=%d",index,offset,length);const respond=(err,buffer)=>request===this._pull(this.peerRequests,index,offset,length)?err?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",index,offset,length,err.message):void this.piece(index,offset,buffer):void 0;var request=new Request(index,offset,length,respond);this.peerRequests.push(request),this.emit("request",index,offset,length,respond)}}_onPiece(index,offset,buffer){this._debug("got piece index=%d offset=%d",index,offset),this._callback(this._pull(this.requests,index,offset,buffer.length),null,buffer),this.downloaded+=buffer.length,this.downloadSpeed(buffer.length),this.emit("download",buffer.length),this.emit("piece",index,offset,buffer)}_onCancel(index,offset,length){this._debug("got cancel index=%d offset=%d length=%d",index,offset,length),this._pull(this.peerRequests,index,offset,length),this.emit("cancel",index,offset,length)}_onPort(port){this._debug("got port %d",port),this.emit("port",port)}_onExtended(ext,buf){if(0===ext){let info;try{info=bencode.decode(buf)}catch(err){this._debug("ignoring invalid extended handshake: %s",err.message||err)}if(!info)return;this.peerExtendedHandshake=info;if("object"==typeof info.m)for(var name in info.m)this.peerExtendedMapping[name]=+info.m[name].toString();for(name in this._ext)this.peerExtendedMapping[name]&&this._ext[name].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[ext]&&(ext=this.extendedMapping[ext],this._ext[ext]&&this._ext[ext].onMessage(buf)),this._debug("got extended message ext=%s",ext),this.emit("extended",ext,buf)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(data,encoding,cb){for(this._bufferSize+=data.length,this._buffer.push(data);this._bufferSize>=this._parserSize;){const buffer=1===this._buffer.length?this._buffer[0]:Buffer.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[buffer.slice(this._parserSize)]:[],this._parser(buffer.slice(0,this._parserSize))}cb(null)}_callback(request,err,buffer){request&&(this._clearTimeout(),!this.peerChoking&&!this._finished&&this._updateTimeout(),request.callback(err,buffer))}_clearTimeout(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_updateTimeout(){this._timeoutMs&&this.requests.length&&!this._timeout&&(this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref())}_parse(size,parser){this._parserSize=size,this._parser=parser}_onMessageLength(buffer){const length=buffer.readUInt32BE(0);0<length?this._parse(length,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(buffer){switch(this._parse(4,this._onMessageLength),buffer[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(buffer.readUInt32BE(1));case 5:return this._onBitField(buffer.slice(1));case 6:return this._onRequest(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 7:return this._onPiece(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.slice(9));case 8:return this._onCancel(buffer.readUInt32BE(1),buffer.readUInt32BE(5),buffer.readUInt32BE(9));case 9:return this._onPort(buffer.readUInt16BE(1));case 20:return this._onExtended(buffer.readUInt8(1),buffer.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",buffer);}}_parseHandshake(){this._parse(1,buffer=>{const pstrlen=buffer.readUInt8(0);this._parse(pstrlen+48,handshake=>{const protocol=handshake.slice(0,pstrlen);return"BitTorrent protocol"===protocol.toString()?void(handshake=handshake.slice(pstrlen),this._onHandshake(handshake.slice(8,28),handshake.slice(28,48),{dht:!!(1&handshake[7]),extended:!!(16&handshake[5])}),this._parse(4,this._onMessageLength)):(this._debug("Error: wire not speaking BitTorrent protocol (%s)",protocol.toString()),void this.end())})})}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...args){args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}_pull(requests,piece,offset,length){for(let i=0;i<requests.length;i++){const req=requests[i];if(req.piece===piece&&req.offset===offset&&req.length===length)return arrayRemove(requests,i),req}return null}}module.exports=Wire}).call(this,require("buffer").Buffer)},{bencode:11,bitfield:13,buffer:26,debug:30,randombytes:69,"readable-stream":85,speedometer:98,"unordered-array-remove":115}],15:[function(require,module){(function(process,Buffer){const debug=require("debug")("bittorrent-tracker:client"),EventEmitter=require("events"),once=require("once"),parallel=require("run-parallel"),Peer=require("simple-peer"),common=require("./lib/common"),HTTPTracker=require("./lib/client/http-tracker"),UDPTracker=require("./lib/client/udp-tracker"),WebSocketTracker=require("./lib/client/websocket-tracker");class Client extends EventEmitter{constructor(opts={}){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this._peerIdBuffer=Buffer.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._infoHashBuffer=Buffer.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),debug("new client %s",this.infoHash),this.destroyed=!1,this._port=opts.port,this._getAnnounceOpts=opts.getAnnounceOpts,this._rtcConfig=opts.rtcConfig,this._userAgent=opts.userAgent,this._wrtc="function"==typeof opts.wrtc?opts.wrtc():opts.wrtc;let announce="string"==typeof opts.announce?[opts.announce]:null==opts.announce?[]:opts.announce;announce=announce.map(announceUrl=>(announceUrl=announceUrl.toString(),"/"===announceUrl[announceUrl.length-1]&&(announceUrl=announceUrl.substring(0,announceUrl.length-1)),announceUrl)),announce=Array.from(new Set(announce));const webrtcSupport=!1!==this._wrtc&&(!!this._wrtc||Peer.WEBRTC_SUPPORT),nextTickWarn=err=>{process.nextTick(()=>{this.emit("warning",err)})};this._trackers=announce.map(announceUrl=>{let parsedUrl;try{parsedUrl=new URL(announceUrl)}catch(err){return nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`)),null}const port=parsedUrl.port;if(0>port||65535<port)return nextTickWarn(new Error(`Invalid tracker port: ${announceUrl}`)),null;const protocol=parsedUrl.protocol;return("http:"===protocol||"https:"===protocol)&&"function"==typeof HTTPTracker?new HTTPTracker(this,announceUrl):"udp:"===protocol&&"function"==typeof UDPTracker?new UDPTracker(this,announceUrl):("ws:"===protocol||"wss:"===protocol)&&webrtcSupport?"ws:"===protocol&&"undefined"!=typeof window&&"https:"===window.location.protocol?(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null):new WebSocketTracker(this,announceUrl):(nextTickWarn(new Error(`Unsupported tracker protocol: ${announceUrl}`)),null)}).filter(Boolean)}start(opts){opts=this._defaultAnnounceOpts(opts),opts.event="started",debug("send `start` %o",opts),this._announce(opts),this._trackers.forEach(tracker=>{tracker.setInterval()})}stop(opts){opts=this._defaultAnnounceOpts(opts),opts.event="stopped",debug("send `stop` %o",opts),this._announce(opts)}complete(opts){opts||(opts={}),opts=this._defaultAnnounceOpts(opts),opts.event="completed",debug("send `complete` %o",opts),this._announce(opts)}update(opts){opts=this._defaultAnnounceOpts(opts),opts.event&&delete opts.event,debug("send `update` %o",opts),this._announce(opts)}_announce(opts){this._trackers.forEach(tracker=>{tracker.announce(opts)})}scrape(opts){debug("send `scrape`"),opts||(opts={}),this._trackers.forEach(tracker=>{tracker.scrape(opts)})}setInterval(intervalMs){debug("setInterval %d",intervalMs),this._trackers.forEach(tracker=>{tracker.setInterval(intervalMs)})}destroy(cb){if(!this.destroyed){this.destroyed=!0,debug("destroy");const tasks=this._trackers.map(tracker=>cb=>{tracker.destroy(cb)});parallel(tasks,cb),this._trackers=[],this._getAnnounceOpts=null}}_defaultAnnounceOpts(opts={}){return null==opts.numwant&&(opts.numwant=common.DEFAULT_ANNOUNCE_PEERS),null==opts.uploaded&&(opts.uploaded=0),null==opts.downloaded&&(opts.downloaded=0),this._getAnnounceOpts&&(opts=Object.assign({},opts,this._getAnnounceOpts())),opts}}Client.scrape=(opts,cb)=>{if(cb=once(cb),!opts.infoHash)throw new Error("Option `infoHash` is required");if(!opts.announce)throw new Error("Option `announce` is required");const clientOpts=Object.assign({},opts,{infoHash:Array.isArray(opts.infoHash)?opts.infoHash[0]:opts.infoHash,peerId:Buffer.from("01234567890123456789"),port:6881}),client=new Client(clientOpts);client.once("error",cb),client.once("warning",cb);let len=Array.isArray(opts.infoHash)?opts.infoHash.length:1;const results={};return client.on("scrape",data=>{if(len-=1,results[data.infoHash]=data,0===len){client.destroy();const keys=Object.keys(results);1===keys.length?cb(null,results[keys[0]]):cb(null,results)}}),opts.infoHash=Array.isArray(opts.infoHash)?opts.infoHash.map(infoHash=>Buffer.from(infoHash,"hex")):Buffer.from(opts.infoHash,"hex"),client.scrape({infoHash:opts.infoHash}),client},module.exports=Client}).call(this,require("_process"),require("buffer").Buffer)},{"./lib/client/http-tracker":21,"./lib/client/udp-tracker":21,"./lib/client/websocket-tracker":17,"./lib/common":18,_process:61,buffer:26,debug:30,events:33,once:56,"run-parallel":89,"simple-peer":94}],16:[function(require,module){const EventEmitter=require("events");module.exports=class extends EventEmitter{constructor(client,announceUrl){super(),this.client=client,this.announceUrl=announceUrl,this.interval=null,this.destroyed=!1}setInterval(intervalMs){null==intervalMs&&(intervalMs=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),intervalMs&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},intervalMs),this.interval.unref&&this.interval.unref())}}},{events:33}],17:[function(require,module){function noop(){}const debug=require("debug")("bittorrent-tracker:websocket-tracker"),Peer=require("simple-peer"),randombytes=require("randombytes"),Socket=require("simple-websocket"),common=require("../common"),Tracker=require("./tracker"),socketPool={};class WebSocketTracker extends Tracker{constructor(client,announceUrl){super(client,announceUrl),debug("new websocket tracker %s",announceUrl),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(opts)});const params=Object.assign({},opts,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(params.trackerid=this._trackerId),"stopped"===opts.event||"completed"===opts.event)this._send(params);else{const numwant=_Mathmin(opts.numwant,10);this._generateOffers(numwant,offers=>{params.numwant=numwant,params.offers=offers,this._send(params)})}}scrape(opts){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(opts)});const infoHashes=Array.isArray(opts.infoHash)&&0<opts.infoHash.length?opts.infoHash.map(infoHash=>infoHash.toString("binary")):opts.infoHash&&opts.infoHash.toString("binary")||this.client._infoHashBinary;this._send({action:"scrape",info_hash:infoHashes})}destroy(cb=noop){function destroyCleanup(){timeout&&(clearTimeout(timeout),timeout=null),socket.removeListener("data",destroyCleanup),socket.destroy(),socket=null}if(this.destroyed)return cb(null);for(const peerId in this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer),this.peers){const peer=this.peers[peerId];clearTimeout(peer.trackerTimeout),peer.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,socketPool[this.announceUrl]&&(socketPool[this.announceUrl].consumers-=1),0<socketPool[this.announceUrl].consumers)return cb();let socket=socketPool[this.announceUrl];if(delete socketPool[this.announceUrl],socket.on("error",noop),socket.once("close",cb),!this.expectingResponse)return destroyCleanup();var timeout=setTimeout(destroyCleanup,common.DESTROY_TIMEOUT);socket.once("data",destroyCleanup)}_openSocket(){this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=()=>{this._onSocketConnect()},this._onSocketErrorBound=err=>{this._onSocketError(err)},this._onSocketDataBound=data=>{this._onSocketData(data)},this._onSocketCloseBound=()=>{this._onSocketClose()},this.socket=socketPool[this.announceUrl],this.socket?(socketPool[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound()):(this.socket=socketPool[this.announceUrl]=new Socket(this.announceUrl),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)),this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(data){if(!this.destroyed){this.expectingResponse=!1;try{data=JSON.parse(data)}catch(err){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===data.action?this._onAnnounceResponse(data):"scrape"===data.action?this._onScrapeResponse(data):this._onSocketError(new Error(`invalid action in WS response: ${data.action}`))}}_onAnnounceResponse(data){if(data.info_hash!==this.client._infoHashBinary)return void debug("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,common.binaryToHex(data.info_hash),this.client.infoHash);if(data.peer_id&&data.peer_id===this.client._peerIdBinary)return;debug("received %s from %s for %s",JSON.stringify(data),this.announceUrl,this.client.infoHash);const failure=data["failure reason"];if(failure)return this.client.emit("warning",new Error(failure));const warning=data["warning message"];warning&&this.client.emit("warning",new Error(warning));const interval=data.interval||data["min interval"];interval&&this.setInterval(1e3*interval);const trackerId=data["tracker id"];if(trackerId&&(this._trackerId=trackerId),null!=data.complete){const response=Object.assign({},data,{announce:this.announceUrl,infoHash:common.binaryToHex(data.info_hash)});this.client.emit("update",response)}let peer;if(data.offer&&data.peer_id&&(debug("creating peer (from remote offer)"),peer=this._createPeer(),peer.id=common.binaryToHex(data.peer_id),peer.once("signal",answer=>{const params={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:data.peer_id,answer,offer_id:data.offer_id};this._trackerId&&(params.trackerid=this._trackerId),this._send(params)}),peer.signal(data.offer),this.client.emit("peer",peer)),data.answer&&data.peer_id){const offerId=common.binaryToHex(data.offer_id);peer=this.peers[offerId],peer?(peer.id=common.binaryToHex(data.peer_id),peer.signal(data.answer),this.client.emit("peer",peer),clearTimeout(peer.trackerTimeout),peer.trackerTimeout=null,delete this.peers[offerId]):debug(`got unexpected answer: ${JSON.stringify(data.answer)}`)}}_onScrapeResponse(data){data=data.files||{};const keys=Object.keys(data);return 0===keys.length?void this.client.emit("warning",new Error("invalid scrape response")):void keys.forEach(infoHash=>{const response=Object.assign(data[infoHash],{announce:this.announceUrl,infoHash:common.binaryToHex(infoHash)});this.client.emit("scrape",response)})}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(err){this.destroyed||(this.destroy(),this.client.emit("warning",err),this._startReconnectTimer())}_startReconnectTimer(){const ms=_Mathfloor(Math.random()*300000)+_Mathmin(_Mathpow(2,this.retries)*10000,3600000);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},ms),this.reconnectTimer.unref&&this.reconnectTimer.unref(),debug("reconnecting socket in %s ms",ms)}_send(params){if(!this.destroyed){this.expectingResponse=!0;const message=JSON.stringify(params);debug("send %s",message),this.socket.send(message)}}_generateOffers(numwant,cb){function generateOffer(){const offerId=randombytes(20).toString("hex");debug("creating peer (from _generateOffers)");const peer=self.peers[offerId]=self._createPeer({initiator:!0});peer.once("signal",offer=>{offers.push({offer,offer_id:common.hexToBinary(offerId)}),checkDone()}),peer.trackerTimeout=setTimeout(()=>{debug("tracker timeout: destroying peer"),peer.trackerTimeout=null,delete self.peers[offerId],peer.destroy()},50000),peer.trackerTimeout.unref&&peer.trackerTimeout.unref()}function checkDone(){offers.length===numwant&&(debug("generated %s offers",numwant),cb(offers))}const self=this,offers=[];debug("generating %s offers",numwant);for(let i=0;i<numwant;++i)generateOffer();checkDone()}_createPeer(opts){function onError(err){self.client.emit("warning",new Error(`Connection error: ${err.message}`)),peer.destroy()}function onConnect(){peer.removeListener("error",onError),peer.removeListener("connect",onConnect)}const self=this;opts=Object.assign({trickle:!1,config:self.client._rtcConfig,wrtc:self.client._wrtc},opts);const peer=new Peer(opts);return peer.once("error",onError),peer.once("connect",onConnect),peer}}WebSocketTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL=30000,WebSocketTracker._socketPool=socketPool,module.exports=WebSocketTracker},{"../common":18,"./tracker":16,debug:30,randombytes:69,"simple-peer":94,"simple-websocket":97}],18:[function(require,module,exports){(function(Buffer){exports.DEFAULT_ANNOUNCE_PEERS=50,exports.MAX_ANNOUNCE_PEERS=82,exports.binaryToHex=function(str){return"string"!=typeof str&&(str+=""),Buffer.from(str,"binary").toString("hex")},exports.hexToBinary=function(str){return"string"!=typeof str&&(str+=""),Buffer.from(str,"hex").toString("binary")};var config=require("./common-node");Object.assign(exports,config)}).call(this,require("buffer").Buffer)},{"./common-node":21,buffer:26}],19:[function(require,module){(function(Buffer){module.exports=function(blob,cb){function onLoadEnd(e){reader.removeEventListener("loadend",onLoadEnd,!1),e.error?cb(e.error):cb(null,Buffer.from(reader.result))}if("undefined"==typeof Blob||!(blob instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof cb)throw new Error("second argument must be a function");var reader=new FileReader;reader.addEventListener("loadend",onLoadEnd,!1),reader.readAsArrayBuffer(blob)}}).call(this,require("buffer").Buffer)},{buffer:26}],20:[function(require,module){(function(Buffer){const{Transform}=require("readable-stream");module.exports=class extends Transform{constructor(size,opts={}){super(opts),"object"==typeof size&&(opts=size,size=opts.size),this.size=size||512;const{nopad,zeroPadding=!0}=opts;this._zeroPadding=!nopad&&!!zeroPadding,this._buffered=[],this._bufferedBytes=0}_transform(buf,enc,next){for(this._bufferedBytes+=buf.length,this._buffered.push(buf);this._bufferedBytes>=this.size;){const b=Buffer.concat(this._buffered);this._bufferedBytes-=this.size,this.push(b.slice(0,this.size)),this._buffered=[b.slice(this.size,b.length)]}next()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const zeroes=Buffer.alloc(this.size-this._bufferedBytes);this._buffered.push(zeroes),this.push(Buffer.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(Buffer.concat(this._buffered)),this._buffered=null);this.push(null)}}}).call(this,require("buffer").Buffer)},{buffer:26,"readable-stream":85}],21:[function(){},{}],22:[function(require,module,exports){arguments[4][21][0].apply(exports,arguments)},{dup:21}],23:[function(require,module){(function(Buffer){module.exports=function(size){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");return Buffer.allocUnsafe?Buffer.allocUnsafe(size):new Buffer(size)}}).call(this,require("buffer").Buffer)},{buffer:26}],24:[function(require,module){(function(Buffer){var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("\"size\" argument must be a number");if(0>size)throw new RangeError("\"size\" argument must not be negative");if(Buffer.alloc)return Buffer.alloc(size,fill,encoding);var buffer=allocUnsafe(size);return 0===size?buffer:void 0===fill?bufferFill(buffer,0):("string"!=typeof encoding&&(encoding=void 0),bufferFill(buffer,fill,encoding))}}).call(this,require("buffer").Buffer)},{buffer:26,"buffer-alloc-unsafe":23,"buffer-fill":25}],25:[function(require,module){(function(Buffer){function isSingleByte(val){return 1===val.length&&256>val.charCodeAt(0)}function fillWithNumber(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");return start>>>=0,end=void 0===end?buffer.length:end>>>0,end>start&&buffer.fill(val,start,end),buffer}function fillWithBuffer(buffer,val,start,end){if(0>start||end>buffer.length)throw new RangeError("Out of range index");if(end<=start)return buffer;start>>>=0,end=void 0===end?buffer.length:end>>>0;for(var pos=start,len=val.length;pos<=end-len;)val.copy(buffer,pos),pos+=len;return pos!==end&&val.copy(buffer,pos,0,end-pos),buffer}var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var buf=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return buf.fill("ab","ucs2"),"61006200"===buf.toString("hex")}catch(_){return!1}}();module.exports=function(buffer,val,start,end,encoding){if(hasFullSupport)return buffer.fill(val,start,end,encoding);if("number"==typeof val)return fillWithNumber(buffer,val,start,end);if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=buffer.length):"string"==typeof end&&(encoding=end,end=buffer.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("latin1"===encoding&&(encoding="binary"),"string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(""===val)return fillWithNumber(buffer,0,start,end);if(isSingleByte(val))return fillWithNumber(buffer,val.charCodeAt(0),start,end);val=new Buffer(val,encoding)}return Buffer.isBuffer(val)?fillWithBuffer(buffer,val,start,end):fillWithNumber(buffer,0,start,end)}}).call(this,require("buffer").Buffer)},{buffer:26}],26:[function(require,module,exports){(function(Buffer){/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh <https://feross.org> + * @license MIT + */'use strict';function createBuffer(length){if(2147483647<length)throw new RangeError("The value \""+length+"\" is invalid for option \"size\"");var buf=new Uint8Array(length);return buf.__proto__=Buffer.prototype,buf}function Buffer(arg,encodingOrOffset,length){if("number"==typeof arg){if("string"==typeof encodingOrOffset)throw new TypeError("The \"string\" argument must be of type string. Received type number");return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}function from(value,encodingOrOffset,length){if("string"==typeof value)return fromString(value,encodingOrOffset);if(ArrayBuffer.isView(value))return fromArrayLike(value);if(null==value)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return fromArrayBuffer(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError("The \"value\" argument must not be of type number. Received type number");var valueOf=value.valueOf&&value.valueOf();if(null!=valueOf&&valueOf!==value)return Buffer.from(valueOf,encodingOrOffset,length);var b=fromObject(value);if(b)return b;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof value[Symbol.toPrimitive])return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value)}function assertSize(size){if("number"!=typeof size)throw new TypeError("\"size\" argument must be of type number");else if(0>size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"")}function alloc(size,fill,encoding){return assertSize(size),0>=size?createBuffer(size):void 0===fill?createBuffer(size):"string"==typeof encoding?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}function allocUnsafe(size){return assertSize(size),createBuffer(0>size?0:0|checked(size))}function fromString(string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),actual=buf.write(string,encoding);return actual!==length&&(buf=buf.slice(0,actual)),buf}function fromArrayLike(array){for(var length=0>array.length?0:0|checked(array.length),buf=createBuffer(length),i=0;i<length;i+=1)buf[i]=255&array[i];return buf}function fromArrayBuffer(array,byteOffset,length){if(0>byteOffset||array.byteLength<byteOffset)throw new RangeError("\"offset\" is outside of buffer bounds");if(array.byteLength<byteOffset+(length||0))throw new RangeError("\"length\" is outside of buffer bounds");var buf;return buf=void 0===byteOffset&&void 0===length?new Uint8Array(array):void 0===length?new Uint8Array(array,byteOffset):new Uint8Array(array,byteOffset,length),buf.__proto__=Buffer.prototype,buf}function fromObject(obj){if(Buffer.isBuffer(obj)){var len=0|checked(obj.length),buf=createBuffer(len);return 0===buf.length?buf:(obj.copy(buf,0,0,len),buf)}return void 0===obj.length?"Buffer"===obj.type&&Array.isArray(obj.data)?fromArrayLike(obj.data):void 0:"number"!=typeof obj.length||numberIsNaN(obj.length)?createBuffer(0):fromArrayLike(obj)}function checked(length){if(length>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type "+typeof string);var len=string.length,mustMatch=2<arguments.length&&!0===arguments[2];if(!mustMatch&&0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0;}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||0>start)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),0>=end)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0;}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):2147483647<byteOffset?byteOffset=2147483647:-2147483648>byteOffset&&(byteOffset=-2147483648),byteOffset=+byteOffset,numberIsNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),0>byteOffset&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(0>byteOffset)if(dir)byteOffset=0;else return-1;if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=(encoding+"").toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(2>arr.length||2>val.length)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++)if(read(arr,i)!==read(val,-1===foundIndex?0:i-foundIndex))-1!==foundIndex&&(i-=i-foundIndex),foundIndex=-1;else if(-1===foundIndex&&(foundIndex=i),i-foundIndex+1===valLength)return foundIndex*indexSize}else for(byteOffset+valLength>arrLength&&(byteOffset=arrLength-valLength),i=byteOffset;0<=i;i--){for(var found=!0,j=0;j<valLength;j++)if(read(arr,i+j)!==read(val,j)){found=!1;break}if(found)return i}return-1}function hexWrite(buf,string,offset,length){offset=+offset||0;var remaining=buf.length-offset;length?(length=+length,length>remaining&&(length=remaining)):length=remaining;var strLen=string.length;length>strLen/2&&(length=strLen/2);for(var i=0,parsed;i<length;++i){if(parsed=parseInt(string.substr(2*i,2),16),numberIsNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}function base64Slice(buf,start,end){return 0===start&&end===buf.length?base64.fromByteArray(buf):base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=_Mathmin(buf.length,end);for(var res=[],i=start;i<end;){var firstByte=buf[i],codePoint=null,bytesPerSequence=239<firstByte?4:223<firstByte?3:191<firstByte?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;1===bytesPerSequence?128>firstByte&&(codePoint=firstByte):2===bytesPerSequence?(secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,127<tempCodePoint&&(codePoint=tempCodePoint))):3===bytesPerSequence?(secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,2047<tempCodePoint&&(55296>tempCodePoint||57343<tempCodePoint)&&(codePoint=tempCodePoint))):4===bytesPerSequence?(secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,65535<tempCodePoint&&1114112>tempCodePoint&&(codePoint=tempCodePoint))):void 0}null===codePoint?(codePoint=65533,bytesPerSequence=1):65535<codePoint&&(codePoint-=65536,res.push(55296|1023&codePoint>>>10),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=4096)return _StringfromCharCode.apply(String,codePoints);for(var res="",i=0;i<len;)res+=_StringfromCharCode.apply(String,codePoints.slice(i,i+=4096));return res}function asciiSlice(buf,start,end){var ret="";end=_Mathmin(buf.length,end);for(var i=start;i<end;++i)ret+=_StringfromCharCode(127&buf[i]);return ret}function latin1Slice(buf,start,end){var ret="";end=_Mathmin(buf.length,end);for(var i=start;i<end;++i)ret+=_StringfromCharCode(buf[i]);return ret}function hexSlice(buf,start,end){var len=buf.length;(!start||0>start)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;i<end;++i)out+=toHex(buf[i]);return out}function utf16leSlice(buf,start,end){for(var bytes=buf.slice(start,end),res="",i=0;i<bytes.length;i+=2)res+=_StringfromCharCode(bytes[i]+256*bytes[i+1]);return res}function checkOffset(offset,ext,length){if(0!=offset%1||0>offset)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("\"buffer\" argument must be a Buffer instance");if(value>max||value<min)throw new RangeError("\"value\" argument is out of bounds");if(offset+ext>buf.length)throw new RangeError("Index out of range")}function checkIEEE754(buf,value,offset,ext){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(0>offset)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=str.split("=")[0],str=str.trim().replace(INVALID_BASE64_RE,""),2>str.length)return"";for(;0!=str.length%4;)str+="=";return str}function toHex(n){return 16>n?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var length=string.length,leadSurrogate=null,bytes=[],i=0,codePoint;i<length;++i){if(codePoint=string.charCodeAt(i),55295<codePoint&&57344>codePoint){if(!leadSurrogate){if(56319<codePoint){-1<(units-=3)&&bytes.push(239,191,189);continue}else if(i+1===length){-1<(units-=3)&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(56320>codePoint){-1<(units-=3)&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&-1<(units-=3)&&bytes.push(239,191,189);if(leadSurrogate=null,128>codePoint){if(0>(units-=1))break;bytes.push(codePoint)}else if(2048>codePoint){if(0>(units-=2))break;bytes.push(192|codePoint>>6,128|63&codePoint)}else if(65536>codePoint){if(0>(units-=3))break;bytes.push(224|codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else if(1114112>codePoint){if(0>(units-=4))break;bytes.push(240|codePoint>>18,128|63&codePoint>>12,128|63&codePoint>>6,128|63&codePoint)}else throw new Error("Invalid code point")}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i<str.length;++i)byteArray.push(255&str.charCodeAt(i));return byteArray}function utf16leToBytes(str,units){for(var byteArray=[],i=0,c,hi,lo;i<str.length&&!(0>(units-=2));++i)c=str.charCodeAt(i),hi=c>>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length&&!(i+offset>=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}var base64=require("base64-js"),ieee754=require("ieee754");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50;exports.kMaxLength=2147483647,Buffer.TYPED_ARRAY_SUPPORT=function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()}catch(e){return!1}}(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){return Buffer.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),Buffer.poolSize=8192,Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)},Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)},Buffer.isBuffer=function(b){return null!=b&&!0===b._isBuffer&&b!==Buffer.prototype},Buffer.compare=function(a,b){if(isInstance(a,Uint8Array)&&(a=Buffer.from(a,a.offset,a.byteLength)),isInstance(b,Uint8Array)&&(b=Buffer.from(b,b.offset,b.byteLength)),!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=_Mathmin(x,y);i<len;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return x<y?-1:y<x?1:0},Buffer.isEncoding=function(encoding){switch((encoding+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1;}},Buffer.concat=function(list,length){if(!Array.isArray(list))throw new TypeError("\"list\" argument must be an Array of Buffers");if(0===list.length)return Buffer.alloc(0);var i;if(length===void 0)for(length=0,i=0;i<list.length;++i)length+=list[i].length;var buffer=Buffer.allocUnsafe(length),pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(isInstance(buf,Uint8Array)&&(buf=Buffer.from(buf)),!Buffer.isBuffer(buf))throw new TypeError("\"list\" argument must be an Array of Buffers");buf.copy(buffer,pos),pos+=buf.length}return buffer},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function(){var len=this.length;if(0!=len%2)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var i=0;i<len;i+=2)swap(this,i,i+1);return this},Buffer.prototype.swap32=function(){var len=this.length;if(0!=len%4)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var i=0;i<len;i+=4)swap(this,i,i+3),swap(this,i+1,i+2);return this},Buffer.prototype.swap64=function(){var len=this.length;if(0!=len%8)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;i<len;i+=8)swap(this,i,i+7),swap(this,i+1,i+6),swap(this,i+2,i+5),swap(this,i+3,i+4);return this},Buffer.prototype.toString=function(){var length=this.length;return 0===length?"":0===arguments.length?utf8Slice(this,0,length):slowToString.apply(this,arguments)},Buffer.prototype.toLocaleString=Buffer.prototype.toString,Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return this===b||0===Buffer.compare(this,b)},Buffer.prototype.inspect=function(){var str="",max=exports.INSPECT_MAX_BYTES;return str=this.toString("hex",0,max).replace(/(.{2})/g,"$1 ").trim(),this.length>max&&(str+=" ... "),"<Buffer "+str+">"},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. Received type "+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),0>start||end>target.length||0>thisStart||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=_Mathmin(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i<len;++i)if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i],y=targetCopy[i];break}return x<y?-1:y<x?1:0},Buffer.prototype.includes=function(val,byteOffset,encoding){return-1!==this.indexOf(val,byteOffset,encoding)},Buffer.prototype.indexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!0)},Buffer.prototype.lastIndexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!1)},Buffer.prototype.write=function(string,offset,length,encoding){if(void 0===offset)encoding="utf8",length=this.length,offset=0;else if(void 0===length&&"string"==typeof offset)encoding=offset,length=this.length,offset=0;else if(isFinite(offset))offset>>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),0<string.length&&(0>length||0>offset)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0;}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),end<start&&(end=start);var newBuf=this.subarray(start,end);return newBuf.__proto__=Buffer.prototype,newBuf},Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i<byteLength&&(mul*=256);)val+=this[offset+i]*mul;return val},Buffer.prototype.readUIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;0<byteLength&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i<byteLength&&(mul*=256);)val+=this[offset+i]*mul;return mul*=128,val>=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];0<i&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=_Mathpow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i<byteLength&&(mul*=256);)this[offset+i]=255&value/mul;return offset+byteLength},Buffer.prototype.writeUIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,byteLength>>>=0,!noAssert){var maxBytes=_Mathpow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1,mul=1;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)this[offset+i]=255&value/mul;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i<byteLength&&(mul*=256);)0>value&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=_Mathpow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;0<=--i&&(mul*=256);)0>value&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=255&(value/mul>>0)-sub;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),0<end&&end<start&&(end=start),end===start)return 0;if(0===target.length||0===this.length)return 0;if(0>targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("Index out of range");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart<end-start&&(end=target.length-targetStart+start);var len=end-start;if(this===target&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(targetStart,start,end);else if(this===target&&start<targetStart&&targetStart<end)for(var i=len-1;0<=i;--i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart);return len},Buffer.prototype.fill=function(val,start,end,encoding){if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=this.length):"string"==typeof end&&(encoding=end,end=this.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(1===val.length){var code=val.charCodeAt(0);("utf8"===encoding&&128>code||"latin1"===encoding)&&(val=code)}}else"number"==typeof val&&(val&=255);if(0>start||this.length<start||this.length<end)throw new RangeError("Out of range index");if(end<=start)return this;start>>>=0,end=end===void 0?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i<end;++i)this[i]=val;else{var bytes=Buffer.isBuffer(val)?val:Buffer.from(val,encoding),len=bytes.length;if(0===len)throw new TypeError("The value \""+val+"\" is invalid for argument \"value\"");for(i=0;i<end-start;++i)this[i+start]=bytes[i%len]}return this};var INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g}).call(this,require("buffer").Buffer)},{"base64-js":8,buffer:26,ieee754:37}],27:[function(require,module){module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],28:[function(require,module){const BlockStream=require("block-stream2"),stream=require("readable-stream");class ChunkStoreWriteStream extends stream.Writable{constructor(store,chunkLength,opts={}){if(super(opts),!store||!store.put||!store.get)throw new Error("First argument must be an abstract-chunk-store compliant store");if(chunkLength=+chunkLength,!chunkLength)throw new Error("Second argument must be a chunk length");this._blockstream=new BlockStream(chunkLength,{zeroPadding:!1}),this._outstandingPuts=0;let index=0;const onData=chunk=>{this.destroyed||(this._outstandingPuts+=1,store.put(index,chunk,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),index+=1)};this._blockstream.on("data",onData).on("error",err=>{this.destroy(err)})}_write(chunk,encoding,callback){this._blockstream.write(chunk,encoding,callback)}_final(cb){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?cb(null):this._finalCb=cb})}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err),this.emit("close"))}}module.exports=ChunkStoreWriteStream},{"block-stream2":20,"readable-stream":85}],29:[function(require,module){(function(process,global,Buffer){function flat(arr1){return arr1.reduce((acc,val)=>Array.isArray(val)?acc.concat(flat(val)):acc.concat(val),[])}function _parseInput(input,opts,cb){function processInput(){parallel(input.map(item=>cb=>{const file={};if(isBlob(item))file.getStream=getBlobStream(item),file.length=item.size;else if(Buffer.isBuffer(item))file.getStream=getBufferStream(item),file.length=item.length;else if(isReadable(item))file.getStream=getStreamStream(item,file),file.length=0;else{if("string"==typeof item){if("function"!=typeof fs.stat)throw new Error("filesystem paths do not work in the browser");const keepRoot=1<numPaths||isSingleFileTorrent;return void getFiles(item,keepRoot,cb)}throw new Error("invalid input type")}file.path=item.path,cb(null,file)}),(err,files)=>err?cb(err):void(files=flat(files),cb(null,files,isSingleFileTorrent)))}if(isFileList(input)&&(input=Array.from(input)),Array.isArray(input)||(input=[input]),0===input.length)throw new Error("invalid input type");input.forEach(item=>{if(null==item)throw new Error(`invalid input type: ${item}`)}),input=input.map(item=>isBlob(item)&&"string"==typeof item.path&&"function"==typeof fs.stat?item.path:item),1!==input.length||"string"==typeof input[0]||input[0].name||(input[0].name=opts.name);let commonPrefix=null;input.forEach((item,i)=>{if("string"==typeof item)return;let path=item.fullPath||item.name;path||(path=`Unknown File ${i+1}`,item.unknownName=!0),item.path=path.split("/"),item.path[0]||item.path.shift(),2>item.path.length?commonPrefix=null:0===i&&1<input.length?commonPrefix=item.path[0]:item.path[0]!==commonPrefix&&(commonPrefix=null)}),input=input.filter(item=>{if("string"==typeof item)return!0;const filename=item.path[item.path.length-1];return notHidden(filename)&&junk.not(filename)}),commonPrefix&&input.forEach(item=>{const pathless=(Buffer.isBuffer(item)||isReadable(item))&&!item.path;"string"==typeof item||pathless||item.path.shift()}),!opts.name&&commonPrefix&&(opts.name=commonPrefix),opts.name||input.some(item=>"string"==typeof item?(opts.name=corePath.basename(item),!0):item.unknownName?void 0:(opts.name=item.path[item.path.length-1],!0)),opts.name||(opts.name=`Unnamed Torrent ${Date.now()}`);const numPaths=input.reduce((sum,item)=>sum+ +("string"==typeof item),0);let isSingleFileTorrent=1===input.length;if(1===input.length&&"string"==typeof input[0]){if("function"!=typeof fs.stat)throw new Error("filesystem paths do not work in the browser");isFile(input[0],(err,pathIsFile)=>err?cb(err):void(isSingleFileTorrent=pathIsFile,processInput()))}else process.nextTick(()=>{processInput()})}function getFiles(path,keepRoot,cb){traversePath(path,getFileInfo,(err,files)=>err?cb(err):void(files=Array.isArray(files)?flat(files):[files],path=corePath.normalize(path),keepRoot&&(path=path.slice(0,path.lastIndexOf(corePath.sep)+1)),path[path.length-1]!==corePath.sep&&(path+=corePath.sep),files.forEach(file=>{file.getStream=getFilePathStream(file.path),file.path=file.path.replace(path,"").split(corePath.sep)}),cb(null,files)))}function getFileInfo(path,cb){cb=once(cb),fs.stat(path,(err,stat)=>{if(err)return cb(err);const info={length:stat.size,path};cb(null,info)})}function traversePath(path,fn,cb){fs.stat(path,(err,stats)=>err?cb(err):void(stats.isDirectory()?fs.readdir(path,(err,entries)=>err?cb(err):void parallel(entries.filter(notHidden).filter(junk.not).map(entry=>cb=>{traversePath(corePath.join(path,entry),fn,cb)}),cb)):stats.isFile()&&fn(path,cb)))}function notHidden(file){return"."!==file[0]}function getPieceList(files,pieceLength,cb){function onData(chunk){length+=chunk.length;const i=pieceNum;sha1(chunk,hash=>{pieces[i]=hash,remainingHashes-=1,maybeDone()}),remainingHashes+=1,pieceNum+=1}function onEnd(){ended=!0,maybeDone()}function onError(err){cleanup(),cb(err)}function cleanup(){multistream.removeListener("error",onError),blockstream.removeListener("data",onData),blockstream.removeListener("end",onEnd),blockstream.removeListener("error",onError)}function maybeDone(){ended&&0===remainingHashes&&(cleanup(),cb(null,Buffer.from(pieces.join(""),"hex"),length))}cb=once(cb);const pieces=[];let length=0;const streams=files.map(file=>file.getStream);let remainingHashes=0,pieceNum=0,ended=!1;const multistream=new MultiStream(streams),blockstream=new BlockStream(pieceLength,{zeroPadding:!1});multistream.on("error",onError),multistream.pipe(blockstream).on("data",onData).on("end",onEnd).on("error",onError)}function onFiles(files,opts,cb){let announceList=opts.announceList;announceList||("string"==typeof opts.announce?announceList=[[opts.announce]]:Array.isArray(opts.announce)&&(announceList=opts.announce.map(u=>[u]))),announceList||(announceList=[]),global.WEBTORRENT_ANNOUNCE&&("string"==typeof global.WEBTORRENT_ANNOUNCE?announceList.push([[global.WEBTORRENT_ANNOUNCE]]):Array.isArray(global.WEBTORRENT_ANNOUNCE)&&(announceList=announceList.concat(global.WEBTORRENT_ANNOUNCE.map(u=>[u])))),opts.announce===void 0&&opts.announceList===void 0&&(announceList=announceList.concat(module.exports.announceList)),"string"==typeof opts.urlList&&(opts.urlList=[opts.urlList]);const torrent={info:{name:opts.name},"creation date":_Mathceil((+opts.creationDate||Date.now())/1e3),encoding:"UTF-8"};0!==announceList.length&&(torrent.announce=announceList[0][0],torrent["announce-list"]=announceList),opts.comment!==void 0&&(torrent.comment=opts.comment),opts.createdBy!==void 0&&(torrent["created by"]=opts.createdBy),opts.private!==void 0&&(torrent.info.private=+opts.private),opts.info!==void 0&&Object.assign(torrent.info,opts.info),opts.sslCert!==void 0&&(torrent.info["ssl-cert"]=opts.sslCert),opts.urlList!==void 0&&(torrent["url-list"]=opts.urlList);const pieceLength=opts.pieceLength||calcPieceLength(files.reduce(sumLength,0));torrent.info["piece length"]=pieceLength,getPieceList(files,pieceLength,(err,pieces,torrentLength)=>err?cb(err):void(torrent.info.pieces=pieces,files.forEach(file=>{delete file.getStream}),opts.singleFileTorrent?torrent.info.length=torrentLength:torrent.info.files=files,cb(null,bencode.encode(torrent))))}function sumLength(sum,file){return sum+file.length}function isBlob(obj){return"undefined"!=typeof Blob&&obj instanceof Blob}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function getBlobStream(file){return()=>new FileReadStream(file)}function getBufferStream(buffer){return()=>{const s=new stream.PassThrough;return s.end(buffer),s}}function getFilePathStream(path){return()=>fs.createReadStream(path)}function getStreamStream(readable,file){return()=>{const counter=new stream.Transform;return counter._transform=function(buf,enc,done){file.length+=buf.length,this.push(buf),done()},readable.pipe(counter),counter}}const bencode=require("bencode"),BlockStream=require("block-stream2"),calcPieceLength=require("piece-length"),corePath=require("path"),FileReadStream=require("filestream/read"),fs=require("fs"),isFile=require("is-file"),junk=require("junk"),MultiStream=require("multistream"),once=require("once"),parallel=require("run-parallel"),sha1=require("simple-sha1"),stream=require("readable-stream");module.exports=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,(err,files,singleFileTorrent)=>err?cb(err):void(opts.singleFileTorrent=singleFileTorrent,onFiles(files,opts,cb)))},module.exports.parseInput=function(input,opts,cb){"function"==typeof opts&&([opts,cb]=[cb,opts]),opts=opts?Object.assign({},opts):{},_parseInput(input,opts,cb)},module.exports.announceList=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"],["wss://tracker.fastcast.nz"]]}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{_process:61,bencode:11,"block-stream2":20,buffer:26,"filestream/read":34,fs:22,"is-file":41,junk:43,multistream:54,once:56,path:59,"piece-length":60,"readable-stream":85,"run-parallel":89,"simple-sha1":95}],30:[function(require,module,exports){(function(process){function load(){let r;try{r=exports.storage.getItem("debug")}catch(error){}return!r&&"undefined"!=typeof process&&"env"in process&&(r=process.env.DEBUG),r}exports.log=function(...args){return"object"==typeof console&&console.log&&console.log(...args)},exports.formatArgs=function(args){if(args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match=>{"%%"===match||(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)},exports.save=function(namespaces){try{namespaces?exports.storage.setItem("debug",namespaces):exports.storage.removeItem("debug")}catch(error){}},exports.load=load,exports.useColors=function(){return!!("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},exports.storage=function(){try{return localStorage}catch(error){}}(),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"],module.exports=require("./common")(exports);const{formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this,require("_process"))},{"./common":31,_process:61}],31:[function(require,module){module.exports=function(env){function selectColor(namespace){let hash=0;for(let i=0;i<namespace.length;i++)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return createDebug.colors[_Mathabs(hash)%createDebug.colors.length]}function createDebug(namespace){function debug(...args){if(!debug.enabled)return;const self=debug,curr=+new Date,ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match,format)=>{if("%%"===match)return match;index++;const formatter=createDebug.formatters[format];if("function"==typeof formatter){const val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),createDebug.formatArgs.call(self,args);const logFn=self.log||createDebug.log;logFn.apply(self,args)}let prevTime;return debug.namespace=namespace,debug.enabled=createDebug.enabled(namespace),debug.useColors=createDebug.useColors(),debug.color=selectColor(namespace),debug.destroy=destroy,debug.extend=extend,"function"==typeof createDebug.init&&createDebug.init(debug),createDebug.instances.push(debug),debug}function destroy(){const index=createDebug.instances.indexOf(this);return-1!==index&&(createDebug.instances.splice(index,1),!0)}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+("undefined"==typeof delimiter?":":delimiter)+namespace);return newDebug.log=this.log,newDebug}function toNamespace(regexp){return regexp.toString().substring(2,regexp.toString().length-2).replace(/\.\*\?$/,"*")}return createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=function(val){return val instanceof Error?val.stack||val.message:val},createDebug.disable=function(){const namespaces=[...createDebug.names.map(toNamespace),...createDebug.skips.map(toNamespace).map(namespace=>"-"+namespace)].join(",");return createDebug.enable(""),namespaces},createDebug.enable=function(namespaces){createDebug.save(namespaces),createDebug.names=[],createDebug.skips=[];let i;const split=("string"==typeof namespaces?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i<len;i++)split[i]&&(namespaces=split[i].replace(/\*/g,".*?"),"-"===namespaces[0]?createDebug.skips.push(new RegExp("^"+namespaces.substr(1)+"$")):createDebug.names.push(new RegExp("^"+namespaces+"$")));for(i=0;i<createDebug.instances.length;i++){const instance=createDebug.instances[i];instance.enabled=createDebug.enabled(instance.namespace)}},createDebug.enabled=function(name){if("*"===name[name.length-1])return!0;let i,len;for(i=0,len=createDebug.skips.length;i<len;i++)if(createDebug.skips[i].test(name))return!1;for(i=0,len=createDebug.names.length;i<len;i++)if(createDebug.names[i].test(name))return!0;return!1},createDebug.humanize=require("ms"),Object.keys(env).forEach(key=>{createDebug[key]=env[key]}),createDebug.instances=[],createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=selectColor,createDebug.enable(createDebug.load()),createDebug}},{ms:53}],32:[function(require,module){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onerror=function(err){callback.call(stream,err)},onclose=function(){return readable&&!(rs&&rs.ended)?callback.call(stream,new Error("premature close")):writable&&!(ws&&ws.ended)?callback.call(stream,new Error("premature close")):void 0},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}};module.exports=eos},{once:56}],33:[function(require,module){function EventEmitter(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=objectCreate(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}function $getMaxListeners(that){return void 0===that._maxListeners?EventEmitter.defaultMaxListeners:that._maxListeners}function emitNone(handler,isFn,self){if(isFn)handler.call(self);else for(var len=handler.length,listeners=arrayClone(handler,len),i=0;i<len;++i)listeners[i].call(self)}function emitOne(handler,isFn,self,arg1){if(isFn)handler.call(self,arg1);else for(var len=handler.length,listeners=arrayClone(handler,len),i=0;i<len;++i)listeners[i].call(self,arg1)}function emitTwo(handler,isFn,self,arg1,arg2){if(isFn)handler.call(self,arg1,arg2);else for(var len=handler.length,listeners=arrayClone(handler,len),i=0;i<len;++i)listeners[i].call(self,arg1,arg2)}function emitThree(handler,isFn,self,arg1,arg2,arg3){if(isFn)handler.call(self,arg1,arg2,arg3);else for(var len=handler.length,listeners=arrayClone(handler,len),i=0;i<len;++i)listeners[i].call(self,arg1,arg2,arg3)}function emitMany(handler,isFn,self,args){if(isFn)handler.apply(self,args);else for(var len=handler.length,listeners=arrayClone(handler,len),i=0;i<len;++i)listeners[i].apply(self,args)}function _addListener(target,type,listener,prepend){var m,events,existing;if("function"!=typeof listener)throw new TypeError("\"listener\" argument must be a function");if(events=target._events,events?(events.newListener&&(target.emit("newListener",type,listener.listener?listener.listener:listener),events=target._events),existing=events[type]):(events=target._events=objectCreate(null),target._eventsCount=0),!existing)existing=events[type]=listener,++target._eventsCount;else if("function"==typeof existing?existing=events[type]=prepend?[listener,existing]:[existing,listener]:prepend?existing.unshift(listener):existing.push(listener),!existing.warned&&(m=$getMaxListeners(target),m&&0<m&&existing.length>m)){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" \""+(type+"\" listeners added. Use emitter.setMaxListeners() to increase limit."));w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",w.name,w.message)}return target}function onceWrapper(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var args=Array(arguments.length),i=0;i<args.length;++i)args[i]=arguments[i];this.listener.apply(this.target,args);}}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target:target,type:type,listener:listener},wrapped=bind.call(onceWrapper,state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(!events)return[];var evlistener=events[type];return evlistener?"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length):[]}function listenerCount(type){var events=this._events;if(events){var evlistener=events[type];if("function"==typeof evlistener)return 1;if(evlistener)return evlistener.length}return 0}function spliceOne(list,index){for(var i=index,k=i+1,n=list.length;k<n;i+=1,k+=1)list[i]=list[k];list.pop()}function arrayClone(arr,n){for(var copy=Array(n),i=0;i<n;++i)copy[i]=arr[i];return copy}function unwrapListeners(arr){for(var ret=Array(arr.length),i=0;i<ret.length;++i)ret[i]=arr[i].listener||arr[i];return ret}var objectCreate=Object.create||function(proto){var F=function(){};return F.prototype=proto,new F},objectKeys=Object.keys||function(obj){var keys=[];for(var k in obj)Object.prototype.hasOwnProperty.call(obj,k)&&keys.push(k);return k},bind=Function.prototype.bind||function(context){var fn=this;return function(){return fn.apply(context,arguments)}};module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10,hasDefineProperty;try{var o={};Object.defineProperty&&Object.defineProperty(o,"x",{value:0}),hasDefineProperty=0===o.x}catch(err){hasDefineProperty=!1}hasDefineProperty?Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(arg){if("number"!=typeof arg||0>arg||arg!==arg)throw new TypeError("\"defaultMaxListeners\" must be a positive number");defaultMaxListeners=arg}}):EventEmitter.defaultMaxListeners=defaultMaxListeners,EventEmitter.prototype.setMaxListeners=function(n){if("number"!=typeof n||0>n||isNaN(n))throw new TypeError("\"n\" argument must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.getMaxListeners=function(){return $getMaxListeners(this)},EventEmitter.prototype.emit=function(type){var doError="error"===type,er,handler,len,args,i,events;if(events=this._events,events)doError=doError&&null==events.error;else if(!doError)return!1;if(doError){if(1<arguments.length&&(er=arguments[1]),er instanceof Error)throw er;else{var err=new Error("Unhandled \"error\" event. ("+er+")");throw err.context=er,err}return!1}if(handler=events[type],!handler)return!1;var isFn="function"==typeof handler;switch(len=arguments.length,len){case 1:emitNone(handler,isFn,this);break;case 2:emitOne(handler,isFn,this,arguments[1]);break;case 3:emitTwo(handler,isFn,this,arguments[1],arguments[2]);break;case 4:emitThree(handler,isFn,this,arguments[1],arguments[2],arguments[3]);break;default:for(args=Array(len-1),i=1;i<len;i++)args[i-1]=arguments[i];emitMany(handler,isFn,this,args);}return!0},EventEmitter.prototype.addListener=function(type,listener){return _addListener(this,type,listener,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function(type,listener){return _addListener(this,type,listener,!0)},EventEmitter.prototype.once=function(type,listener){if("function"!=typeof listener)throw new TypeError("\"listener\" argument must be a function");return this.on(type,_onceWrap(this,type,listener)),this},EventEmitter.prototype.prependOnceListener=function(type,listener){if("function"!=typeof listener)throw new TypeError("\"listener\" argument must be a function");return this.prependListener(type,_onceWrap(this,type,listener)),this},EventEmitter.prototype.removeListener=function(type,listener){var list,events,position,i,originalListener;if("function"!=typeof listener)throw new TypeError("\"listener\" argument must be a function");if(events=this._events,!events)return this;if(list=events[type],!list)return this;if(list===listener||list.listener===listener)0==--this._eventsCount?this._events=objectCreate(null):(delete events[type],events.removeListener&&this.emit("removeListener",type,list.listener||listener));else if("function"!=typeof list){for(position=-1,i=list.length-1;0<=i;i--)if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener,position=i;break}if(0>position)return this;0===position?list.shift():spliceOne(list,position),1===list.length&&(events[type]=list[0]),events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var listeners,events,i;if(events=this._events,!events)return this;if(!events.removeListener)return 0===arguments.length?(this._events=objectCreate(null),this._eventsCount=0):events[type]&&(0==--this._eventsCount?this._events=objectCreate(null):delete events[type]),this;if(0===arguments.length){var keys=objectKeys(events),key;for(i=0;i<keys.length;++i)key=keys[i],"removeListener"===key||this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events=objectCreate(null),this._eventsCount=0,this}if(listeners=events[type],"function"==typeof listeners)this.removeListener(type,listeners);else if(listeners)for(i=listeners.length-1;0<=i;i--)this.removeListener(type,listeners[i]);return this},EventEmitter.prototype.listeners=function(type){return _listeners(this,type,!0)},EventEmitter.prototype.rawListeners=function(type){return _listeners(this,type,!1)},EventEmitter.listenerCount=function(emitter,type){return"function"==typeof emitter.listenerCount?emitter.listenerCount(type):listenerCount.call(emitter,type)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]}},{}],34:[function(require,module){const{Readable}=require("readable-stream"),toBuffer=require("typedarray-to-buffer");module.exports=class extends Readable{constructor(file,opts={}){super(opts),this._offset=0,this._ready=!1,this._file=file,this._size=file.size,this._chunkSize=opts.chunkSize||_Mathmax(this._size/1e3,204800);const reader=new FileReader;reader.onload=()=>{this.push(toBuffer(reader.result))},reader.onerror=()=>{this.emit("error",reader.error)},this.reader=reader,this._generateHeaderBlocks(file,opts,(err,blocks)=>err?this.emit("error",err):void(Array.isArray(blocks)&&blocks.forEach(block=>this.push(block)),this._ready=!0,this.emit("_ready")))}_generateHeaderBlocks(file,opts,callback){callback(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const startOffset=this._offset;let endOffset=this._offset+this._chunkSize;return endOffset>this._size&&(endOffset=this._size),startOffset===this._size?(this.destroy(),void this.push(null)):void(this.reader.readAsArrayBuffer(this._file.slice(startOffset,endOffset)),this._offset=endOffset)}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}}},{"readable-stream":85,"typedarray-to-buffer":112}],35:[function(require,module){module.exports=function(){if("undefined"==typeof window)return null;var wrtc={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return wrtc.RTCPeerConnection?wrtc:null}},{}],36:[function(require,module){function validateParams(params){if("string"==typeof params&&(params=url.parse(params)),params.protocol||(params.protocol="https:"),"https:"!==params.protocol)throw new Error("Protocol \""+params.protocol+"\" not supported. Expected \"https:\"");return params}var http=require("http"),url=require("url"),https=module.exports;for(var key in http)http.hasOwnProperty(key)&&(https[key]=http[key]);https.request=function(params,cb){return params=validateParams(params),http.request.call(this,params,cb)},https.get=function(params,cb){return params=validateParams(params),http.get.call(this,params,cb)}},{http:99,url:116}],37:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i],e,m;for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;0<nBits;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;0<nBits;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=_Mathpow(2,mLen),e-=eBias}return(s?-1:1)*m*_Mathpow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var _MathLN=Math.LN2,_Mathlog=Math.log,eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=23===mLen?_Mathpow(2,-24)-_Mathpow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0,e,m,c;for(value=_Mathabs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=_Mathfloor(_Mathlog(value)/_MathLN),1>value*(c=_Mathpow(2,-e))&&(e--,c*=2),value+=1<=e+eBias?rt/c:rt*_Mathpow(2,1-eBias),2<=value*c&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):1<=e+eBias?(m=(value*c-1)*_Mathpow(2,mLen),e+=eBias):(m=value*_Mathpow(2,eBias-1)*_Mathpow(2,mLen),e=0));8<=mLen;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<<mLen|m,eLen+=mLen;0<eLen;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],38:[function(require,module){const queueMicrotask=require("queue-microtask");module.exports=class{constructor(store){if(this.store=store,this.chunkLength=store.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(index,buf,cb){this.mem[index]=buf,this.store.put(index,buf,err=>{this.mem[index]=null,cb&&cb(err)})}get(index,opts,cb){if("function"==typeof opts)return this.get(index,null,opts);let memoryBuffer=this.mem[index];if(!memoryBuffer)return this.store.get(index,opts,cb);if(opts){const start=opts.offset||0,end=opts.length?start+opts.length:memoryBuffer.length;memoryBuffer=memoryBuffer.slice(start,end)}queueMicrotask(()=>{cb&&cb(null,memoryBuffer)})}close(cb){this.store.close(cb)}destroy(cb){this.store.destroy(cb)}}},{"queue-microtask":67}],39:[function(require,module){module.exports="function"==typeof Object.create?function(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:function(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},{}],40:[function(require,module){module.exports=function(str){for(var i=0,strLen=str.length;i<strLen;++i)if(str.charCodeAt(i)>127)return!1;return!0}},{}],41:[function(require,module){'use strict';function isFileSync(path){return fs.existsSync(path)&&fs.statSync(path).isFile()}var fs=require("fs");module.exports=function(path,cb){return cb?void fs.stat(path,function(err,stats){return err?cb(err):cb(null,stats.isFile())}):isFileSync(path)},module.exports.sync=isFileSync},{fs:22}],42:[function(require,module){function isTypedArray(arr){return isStrictTypedArray(arr)||isLooseTypedArray(arr)}function isStrictTypedArray(arr){return arr instanceof Int8Array||arr instanceof Int16Array||arr instanceof Int32Array||arr instanceof Uint8Array||arr instanceof Uint8ClampedArray||arr instanceof Uint16Array||arr instanceof Uint32Array||arr instanceof Float32Array||arr instanceof Float64Array}function isLooseTypedArray(arr){return names[toString.call(arr)]}module.exports=isTypedArray,isTypedArray.strict=isStrictTypedArray,isTypedArray.loose=isLooseTypedArray;var toString=Object.prototype.toString,names={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0}},{}],43:[function(require,module,exports){'use strict';exports.re=()=>{throw new Error("`junk.re` was renamed to `junk.regex`")},exports.regex=new RegExp(["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"].join("|")),exports.is=filename=>exports.regex.test(filename),exports.not=filename=>!exports.is(filename),exports.default=module.exports},{}],44:[function(require,module){(function(Buffer){function magnetURIDecode(uri){const result={},data=uri.split("magnet:?")[1],params=data&&0<=data.length?data.split("&"):[];params.forEach(param=>{const keyval=param.split("=");if(2!==keyval.length)return;const key=keyval[0];let val=keyval[1];if("dn"===key&&(val=decodeURIComponent(val).replace(/\+/g," ")),("tr"===key||"xs"===key||"as"===key||"ws"===key)&&(val=decodeURIComponent(val)),"kt"===key&&(val=decodeURIComponent(val).split("+")),"ix"===key&&(val=+val),!result[key])result[key]=val;else if(Array.isArray(result[key]))result[key].push(val);else{const old=result[key];result[key]=[old,val]}});let m;if(result.xt){const xts=Array.isArray(result.xt)?result.xt:[result.xt];xts.forEach(xt=>{if(m=xt.match(/^urn:btih:(.{40})/))result.infoHash=m[1].toLowerCase();else if(m=xt.match(/^urn:btih:(.{32})/)){const decodedStr=base32.decode(m[1]);result.infoHash=Buffer.from(decodedStr,"binary").toString("hex")}})}return result.infoHash&&(result.infoHashBuffer=Buffer.from(result.infoHash,"hex")),result.dn&&(result.name=result.dn),result.kt&&(result.keywords=result.kt),result.announce="string"==typeof result.tr?[result.tr]:Array.isArray(result.tr)?result.tr:[],result.urlList=[],("string"==typeof result.as||Array.isArray(result.as))&&(result.urlList=result.urlList.concat(result.as)),("string"==typeof result.ws||Array.isArray(result.ws))&&(result.urlList=result.urlList.concat(result.ws)),uniq(result.announce),uniq(result.urlList),result}module.exports=magnetURIDecode,module.exports.decode=magnetURIDecode,module.exports.encode=function(obj){obj=Object.assign({},obj),obj.infoHashBuffer&&(obj.xt=`urn:btih:${obj.infoHashBuffer.toString("hex")}`),obj.infoHash&&(obj.xt=`urn:btih:${obj.infoHash}`),obj.name&&(obj.dn=obj.name),obj.keywords&&(obj.kt=obj.keywords),obj.announce&&(obj.tr=obj.announce),obj.urlList&&(obj.ws=obj.urlList,delete obj.as);let result="magnet:?";return Object.keys(obj).filter(key=>2===key.length).forEach((key,i)=>{const values=Array.isArray(obj[key])?obj[key]:[obj[key]];values.forEach((val,j)=>{(0<i||0<j)&&("kt"!==key||0===j)&&(result+="&"),"dn"===key&&(val=encodeURIComponent(val).replace(/%20/g,"+")),("tr"===key||"xs"===key||"as"===key||"ws"===key)&&(val=encodeURIComponent(val)),"kt"===key&&(val=encodeURIComponent(val)),result+="kt"===key&&0<j?`+${val}`:`${key}=${val}`})}),result};const base32=require("thirty-two"),uniq=require("uniq")}).call(this,require("buffer").Buffer)},{buffer:26,"thirty-two":107,uniq:114}],45:[function(require,module){function MediaElementWrapper(elem,opts){var self=this;if(!(self instanceof MediaElementWrapper))return new MediaElementWrapper(elem,opts);if(!MediaSource)throw new Error("web browser lacks MediaSource support");opts||(opts={}),self._debug=opts.debug,self._bufferDuration=opts.bufferDuration||60,self._elem=elem,self._mediaSource=new MediaSource,self._streams=[],self.detailedError=null,self._errorHandler=function(){self._elem.removeEventListener("error",self._errorHandler);var streams=self._streams.slice();streams.forEach(function(stream){stream.destroy(self._elem.error)})},self._elem.addEventListener("error",self._errorHandler),self._elem.src=window.URL.createObjectURL(self._mediaSource)}function MediaSourceStream(wrapper,obj){var self=this;if(stream.Writable.call(self),self._wrapper=wrapper,self._elem=wrapper._elem,self._mediaSource=wrapper._mediaSource,self._allStreams=wrapper._streams,self._allStreams.push(self),self._bufferDuration=wrapper._bufferDuration,self._sourceBuffer=null,self._debugBuffers=[],self._openHandler=function(){self._onSourceOpen()},self._flowHandler=function(){self._flow()},self._errorHandler=function(err){self.destroyed||self.emit("error",err)},"string"==typeof obj)self._type=obj,"open"===self._mediaSource.readyState?self._createSourceBuffer():self._mediaSource.addEventListener("sourceopen",self._openHandler);else if(null===obj._sourceBuffer)obj.destroy(),self._type=obj._type,self._mediaSource.addEventListener("sourceopen",self._openHandler);else if(obj._sourceBuffer)obj.destroy(),self._type=obj._type,self._sourceBuffer=obj._sourceBuffer,self._debugBuffers=obj._debugBuffers,self._sourceBuffer.addEventListener("updateend",self._flowHandler),self._sourceBuffer.addEventListener("error",self._errorHandler);else throw new Error("The argument to MediaElementWrapper.createWriteStream must be a string or a previous stream returned from that function");self._elem.addEventListener("timeupdate",self._flowHandler),self.on("error",function(err){self._wrapper.error(err)}),self.on("finish",function(){if(!self.destroyed&&(self._finished=!0,self._allStreams.every(function(other){return other._finished}))){self._wrapper._dumpDebugData();try{self._mediaSource.endOfStream()}catch(err){}}})}function downloadBuffers(bufs,name){var a=document.createElement("a");a.href=window.URL.createObjectURL(new window.Blob(bufs)),a.download=name,a.click()}module.exports=MediaElementWrapper;var inherits=require("inherits"),stream=require("readable-stream"),toArrayBuffer=require("to-arraybuffer"),MediaSource="undefined"!=typeof window&&window.MediaSource;MediaElementWrapper.prototype.createWriteStream=function(obj){var self=this;return new MediaSourceStream(self,obj)},MediaElementWrapper.prototype.error=function(err){var self=this;self.detailedError||(self.detailedError=err),self._dumpDebugData();try{self._mediaSource.endOfStream("decode")}catch(err){}try{window.URL.revokeObjectURL(self._elem.src)}catch(err){}},MediaElementWrapper.prototype._dumpDebugData=function(){var self=this;self._debug&&(self._debug=!1,self._streams.forEach(function(stream,i){downloadBuffers(stream._debugBuffers,"mediasource-stream-"+i)}))},inherits(MediaSourceStream,stream.Writable),MediaSourceStream.prototype._onSourceOpen=function(){var self=this;self.destroyed||(self._mediaSource.removeEventListener("sourceopen",self._openHandler),self._createSourceBuffer())},MediaSourceStream.prototype.destroy=function(err){var self=this;self.destroyed||(self.destroyed=!0,self._allStreams.splice(self._allStreams.indexOf(self),1),self._mediaSource.removeEventListener("sourceopen",self._openHandler),self._elem.removeEventListener("timeupdate",self._flowHandler),self._sourceBuffer&&(self._sourceBuffer.removeEventListener("updateend",self._flowHandler),self._sourceBuffer.removeEventListener("error",self._errorHandler),"open"===self._mediaSource.readyState&&self._sourceBuffer.abort()),err&&self.emit("error",err),self.emit("close"))},MediaSourceStream.prototype._createSourceBuffer=function(){var self=this;if(!self.destroyed)if(!MediaSource.isTypeSupported(self._type))self.destroy(new Error("The provided type is not supported"));else if(self._sourceBuffer=self._mediaSource.addSourceBuffer(self._type),self._sourceBuffer.addEventListener("updateend",self._flowHandler),self._sourceBuffer.addEventListener("error",self._errorHandler),self._cb){var cb=self._cb;self._cb=null,cb()}},MediaSourceStream.prototype._write=function(chunk,encoding,cb){var self=this;if(!self.destroyed){if(!self._sourceBuffer)return void(self._cb=function(err){return err?cb(err):void self._write(chunk,encoding,cb)});if(self._sourceBuffer.updating)return cb(new Error("Cannot append buffer while source buffer updating"));var arr=toArrayBuffer(chunk);self._wrapper._debug&&self._debugBuffers.push(arr);try{self._sourceBuffer.appendBuffer(arr)}catch(err){return void self.destroy(err)}self._cb=cb}},MediaSourceStream.prototype._flow=function(){var self=this;if(!(self.destroyed||!self._sourceBuffer||self._sourceBuffer.updating)&&!("open"===self._mediaSource.readyState&&self._getBufferDuration()>self._bufferDuration)&&self._cb){var cb=self._cb;self._cb=null,cb()}};MediaSourceStream.prototype._getBufferDuration=function(){for(var self=this,buffered=self._sourceBuffer.buffered,currentTime=self._elem.currentTime,bufferEnd=-1,i=0;i<buffered.length;i++){var start=buffered.start(i),end=buffered.end(i)+0;if(start>currentTime)break;else(0<=bufferEnd||currentTime<=end)&&(bufferEnd=end)}var bufferedTime=bufferEnd-currentTime;return 0>bufferedTime&&(bufferedTime=0),bufferedTime}},{inherits:39,"readable-stream":85,"to-arraybuffer":109}],46:[function(require,module){(function(process){function Storage(chunkLength,opts){if(!(this instanceof Storage))return new Storage(chunkLength,opts);if(opts||(opts={}),this.chunkLength=+chunkLength,!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=+opts.length||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=_Mathceil(this.length/this.chunkLength)-1)}function nextTick(cb,err,val){process.nextTick(function(){cb&&cb(err,val)})}module.exports=Storage,Storage.prototype.put=function(index,buf,cb){if(this.closed)return nextTick(cb,new Error("Storage is closed"));var isLastChunk=index===this.lastChunkIndex;return isLastChunk&&buf.length!==this.lastChunkLength?nextTick(cb,new Error("Last chunk length must be "+this.lastChunkLength)):isLastChunk||buf.length===this.chunkLength?void(this.chunks[index]=buf,nextTick(cb,null)):nextTick(cb,new Error("Chunk length must be "+this.chunkLength))},Storage.prototype.get=function(index,opts,cb){if("function"==typeof opts)return this.get(index,null,opts);if(this.closed)return nextTick(cb,new Error("Storage is closed"));var buf=this.chunks[index];if(!buf){var err=new Error("Chunk not found");return err.notFound=!0,nextTick(cb,err)}if(!opts)return nextTick(cb,null,buf);var offset=opts.offset||0,len=opts.length||buf.length-offset;nextTick(cb,null,buf.slice(offset,len+offset))},Storage.prototype.close=Storage.prototype.destroy=function(cb){return this.closed?nextTick(cb,new Error("Storage is closed")):void(this.closed=!0,this.chunks=null,nextTick(cb,null))}}).call(this,require("_process"))},{_process:61}],47:[function(require,module,exports){(function(Buffer){function writeReserved(buf,offset,end){for(var i=offset;i<end;i++)buf[i]=0}function writeDate(date,buf,offset){buf.writeUInt32BE(_Mathfloor((date.getTime()+2082844800000)/1e3),offset)}function writeDate64(date,buf,offset){buf.writeUIntBE(_Mathfloor((date.getTime()+2082844800000)/1e3),offset,6)}function writeFixed32(num,buf,offset){buf.writeUInt16BE(_Mathfloor(num)%65536,offset),buf.writeUInt16BE(_Mathfloor(256*(256*num))%65536,offset+2)}function writeFixed16(num,buf,offset){buf[offset]=_Mathfloor(num)%256,buf[offset+1]=_Mathfloor(256*num)%256}function writeMatrix(list,buf,offset){list||(list=[0,0,0,0,0,0,0,0,0]);for(var i=0;i<list.length;i++)writeFixed32(list[i],buf,offset+4*i)}function writeString(str,buf,offset){var strBuffer=Buffer.from(str,"utf8");strBuffer.copy(buf,offset),buf[offset+strBuffer.length]=0}function readMatrix(buf){for(var list=Array(buf.length/4),i=0;i<list.length;i++)list[i]=readFixed32(buf,4*i);return list}function readDate64(buf,offset){return new Date(1e3*buf.readUIntBE(offset,6)-2082844800000)}function readDate(buf,offset){return new Date(1e3*buf.readUInt32BE(offset)-2082844800000)}function readFixed32(buf,offset){return buf.readUInt16BE(offset)+buf.readUInt16BE(offset+2)/65536}function readFixed16(buf,offset){return buf[offset]+buf[offset+1]/256}function readString(buf,offset,length){var i;for(i=0;i<length&&!(0===buf[offset+i]);i++);return buf.toString("utf8",offset,offset+i)}var Box=require("./index"),Descriptor=require("./descriptor"),uint64be=require("uint64be");exports.fullBoxes={};["mvhd","tkhd","mdhd","vmhd","smhd","stsd","esds","stsz","stco","co64","stss","stts","ctts","stsc","dref","elst","hdlr","mehd","trex","mfhd","tfhd","tfdt","trun"].forEach(function(type){exports.fullBoxes[type]=!0}),exports.ftyp={},exports.ftyp.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(exports.ftyp.encodingLength(box));var brands=box.compatibleBrands||[];buf.write(box.brand,0,4,"ascii"),buf.writeUInt32BE(box.brandVersion,4);for(var i=0;i<brands.length;i++)buf.write(brands[i],8+4*i,4,"ascii");return exports.ftyp.encode.bytes=8+4*brands.length,buf},exports.ftyp.decode=function(buf,offset){buf=buf.slice(offset);for(var brand=buf.toString("ascii",0,4),version=buf.readUInt32BE(4),compatibleBrands=[],i=8;i<buf.length;i+=4)compatibleBrands.push(buf.toString("ascii",i,i+4));return{brand:brand,brandVersion:version,compatibleBrands:compatibleBrands}},exports.ftyp.encodingLength=function(box){return 8+4*(box.compatibleBrands||[]).length},exports.mvhd={},exports.mvhd.encode=function(box,buf,offset){return buf=buf?buf.slice(offset):Buffer.alloc(96),writeDate(box.ctime||new Date,buf,0),writeDate(box.mtime||new Date,buf,4),buf.writeUInt32BE(box.timeScale||0,8),buf.writeUInt32BE(box.duration||0,12),writeFixed32(box.preferredRate||0,buf,16),writeFixed16(box.preferredVolume||0,buf,20),writeReserved(buf,22,32),writeMatrix(box.matrix,buf,32),buf.writeUInt32BE(box.previewTime||0,68),buf.writeUInt32BE(box.previewDuration||0,72),buf.writeUInt32BE(box.posterTime||0,76),buf.writeUInt32BE(box.selectionTime||0,80),buf.writeUInt32BE(box.selectionDuration||0,84),buf.writeUInt32BE(box.currentTime||0,88),buf.writeUInt32BE(box.nextTrackId||0,92),exports.mvhd.encode.bytes=96,buf},exports.mvhd.decode=function(buf,offset){return buf=buf.slice(offset),{ctime:readDate(buf,0),mtime:readDate(buf,4),timeScale:buf.readUInt32BE(8),duration:buf.readUInt32BE(12),preferredRate:readFixed32(buf,16),preferredVolume:readFixed16(buf,20),matrix:readMatrix(buf.slice(32,68)),previewTime:buf.readUInt32BE(68),previewDuration:buf.readUInt32BE(72),posterTime:buf.readUInt32BE(76),selectionTime:buf.readUInt32BE(80),selectionDuration:buf.readUInt32BE(84),currentTime:buf.readUInt32BE(88),nextTrackId:buf.readUInt32BE(92)}},exports.mvhd.encodingLength=function(){return 96},exports.tkhd={},exports.tkhd.encode=function(box,buf,offset){return buf=buf?buf.slice(offset):Buffer.alloc(80),writeDate(box.ctime||new Date,buf,0),writeDate(box.mtime||new Date,buf,4),buf.writeUInt32BE(box.trackId||0,8),writeReserved(buf,12,16),buf.writeUInt32BE(box.duration||0,16),writeReserved(buf,20,28),buf.writeUInt16BE(box.layer||0,28),buf.writeUInt16BE(box.alternateGroup||0,30),buf.writeUInt16BE(box.volume||0,32),writeMatrix(box.matrix,buf,36),buf.writeUInt32BE(box.trackWidth||0,72),buf.writeUInt32BE(box.trackHeight||0,76),exports.tkhd.encode.bytes=80,buf},exports.tkhd.decode=function(buf,offset){return buf=buf.slice(offset),{ctime:readDate(buf,0),mtime:readDate(buf,4),trackId:buf.readUInt32BE(8),duration:buf.readUInt32BE(16),layer:buf.readUInt16BE(28),alternateGroup:buf.readUInt16BE(30),volume:buf.readUInt16BE(32),matrix:readMatrix(buf.slice(36,72)),trackWidth:buf.readUInt32BE(72),trackHeight:buf.readUInt32BE(76)}},exports.tkhd.encodingLength=function(){return 80},exports.mdhd={},exports.mdhd.encode=function(box,buf,offset){return 1===box.version?(buf=buf?buf.slice(offset):Buffer.alloc(32),writeDate64(box.ctime||new Date,buf,0),writeDate64(box.mtime||new Date,buf,8),buf.writeUInt32BE(box.timeScale||0,16),buf.writeUIntBE(box.duration||0,20,6),buf.writeUInt16BE(box.language||0,28),buf.writeUInt16BE(box.quality||0,30),exports.mdhd.encode.bytes=32,buf):(buf=buf?buf.slice(offset):Buffer.alloc(20),writeDate(box.ctime||new Date,buf,0),writeDate(box.mtime||new Date,buf,4),buf.writeUInt32BE(box.timeScale||0,8),buf.writeUInt32BE(box.duration||0,12),buf.writeUInt16BE(box.language||0,16),buf.writeUInt16BE(box.quality||0,18),exports.mdhd.encode.bytes=20,buf)},exports.mdhd.decode=function(buf,offset,end){buf=buf.slice(offset);return 20!=end-offset?{ctime:readDate64(buf,0),mtime:readDate64(buf,8),timeScale:buf.readUInt32BE(16),duration:buf.readUIntBE(20,6),language:buf.readUInt16BE(28),quality:buf.readUInt16BE(30)}:{ctime:readDate(buf,0),mtime:readDate(buf,4),timeScale:buf.readUInt32BE(8),duration:buf.readUInt32BE(12),language:buf.readUInt16BE(16),quality:buf.readUInt16BE(18)}},exports.mdhd.encodingLength=function(box){return 1===box.version?32:20},exports.vmhd={},exports.vmhd.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(8),buf.writeUInt16BE(box.graphicsMode||0,0);var opcolor=box.opcolor||[0,0,0];return buf.writeUInt16BE(opcolor[0],2),buf.writeUInt16BE(opcolor[1],4),buf.writeUInt16BE(opcolor[2],6),exports.vmhd.encode.bytes=8,buf},exports.vmhd.decode=function(buf,offset){return buf=buf.slice(offset),{graphicsMode:buf.readUInt16BE(0),opcolor:[buf.readUInt16BE(2),buf.readUInt16BE(4),buf.readUInt16BE(6)]}},exports.vmhd.encodingLength=function(){return 8},exports.smhd={},exports.smhd.encode=function(box,buf,offset){return buf=buf?buf.slice(offset):Buffer.alloc(4),buf.writeUInt16BE(box.balance||0,0),writeReserved(buf,2,4),exports.smhd.encode.bytes=4,buf},exports.smhd.decode=function(buf,offset){return buf=buf.slice(offset),{balance:buf.readUInt16BE(0)}},exports.smhd.encodingLength=function(){return 4},exports.stsd={},exports.stsd.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(exports.stsd.encodingLength(box));var entries=box.entries||[];buf.writeUInt32BE(entries.length,0);for(var ptr=4,i=0,entry;i<entries.length;i++)entry=entries[i],Box.encode(entry,buf,ptr),ptr+=Box.encode.bytes;return exports.stsd.encode.bytes=ptr,buf},exports.stsd.decode=function(buf,offset,end){buf=buf.slice(offset);for(var num=buf.readUInt32BE(0),entries=Array(num),ptr=4,i=0,entry;i<num;i++)entry=Box.decode(buf,ptr,end),entries[i]=entry,ptr+=entry.length;return{entries:entries}},exports.stsd.encodingLength=function(box){var totalSize=4;if(!box.entries)return totalSize;for(var i=0;i<box.entries.length;i++)totalSize+=Box.encodingLength(box.entries[i]);return totalSize},exports.avc1=exports.VisualSampleEntry={},exports.VisualSampleEntry.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(exports.VisualSampleEntry.encodingLength(box)),writeReserved(buf,0,6),buf.writeUInt16BE(box.dataReferenceIndex||0,6),writeReserved(buf,8,24),buf.writeUInt16BE(box.width||0,24),buf.writeUInt16BE(box.height||0,26),buf.writeUInt32BE(box.hResolution||4718592,28),buf.writeUInt32BE(box.vResolution||4718592,32),writeReserved(buf,36,40),buf.writeUInt16BE(box.frameCount||1,40);var compressorName=box.compressorName||"",nameLen=_Mathmin(compressorName.length,31);buf.writeUInt8(nameLen,42),buf.write(compressorName,43,nameLen,"utf8"),buf.writeUInt16BE(box.depth||24,74),buf.writeInt16BE(-1,76);var ptr=78,children=box.children||[];children.forEach(function(child){Box.encode(child,buf,ptr),ptr+=Box.encode.bytes}),exports.VisualSampleEntry.encode.bytes=ptr},exports.VisualSampleEntry.decode=function(buf,offset,end){buf=buf.slice(offset);for(var length=end-offset,nameLen=_Mathmin(buf.readUInt8(42),31),box={dataReferenceIndex:buf.readUInt16BE(6),width:buf.readUInt16BE(24),height:buf.readUInt16BE(26),hResolution:buf.readUInt32BE(28),vResolution:buf.readUInt32BE(32),frameCount:buf.readUInt16BE(40),compressorName:buf.toString("utf8",43,43+nameLen),depth:buf.readUInt16BE(74),children:[]},ptr=78;8<=length-ptr;){var child=Box.decode(buf,ptr,length);box.children.push(child),box[child.type]=child,ptr+=child.length}return box},exports.VisualSampleEntry.encodingLength=function(box){var len=78,children=box.children||[];return children.forEach(function(child){len+=Box.encodingLength(child)}),len},exports.avcC={},exports.avcC.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(box.buffer.length),box.buffer.copy(buf),exports.avcC.encode.bytes=box.buffer.length},exports.avcC.decode=function(buf,offset,end){return buf=buf.slice(offset,end),{mimeCodec:buf.toString("hex",1,4),buffer:Buffer.from(buf)}},exports.avcC.encodingLength=function(box){return box.buffer.length},exports.mp4a=exports.AudioSampleEntry={},exports.AudioSampleEntry.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(exports.AudioSampleEntry.encodingLength(box)),writeReserved(buf,0,6),buf.writeUInt16BE(box.dataReferenceIndex||0,6),writeReserved(buf,8,16),buf.writeUInt16BE(box.channelCount||2,16),buf.writeUInt16BE(box.sampleSize||16,18),writeReserved(buf,20,24),buf.writeUInt32BE(box.sampleRate||0,24);var ptr=28,children=box.children||[];children.forEach(function(child){Box.encode(child,buf,ptr),ptr+=Box.encode.bytes}),exports.AudioSampleEntry.encode.bytes=ptr},exports.AudioSampleEntry.decode=function(buf,offset,end){buf=buf.slice(offset,end);for(var length=end-offset,box={dataReferenceIndex:buf.readUInt16BE(6),channelCount:buf.readUInt16BE(16),sampleSize:buf.readUInt16BE(18),sampleRate:buf.readUInt32BE(24),children:[]},ptr=28;8<=length-ptr;){var child=Box.decode(buf,ptr,length);box.children.push(child),box[child.type]=child,ptr+=child.length}return box},exports.AudioSampleEntry.encodingLength=function(box){var len=28,children=box.children||[];return children.forEach(function(child){len+=Box.encodingLength(child)}),len},exports.esds={},exports.esds.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(box.buffer.length),box.buffer.copy(buf,0),exports.esds.encode.bytes=box.buffer.length},exports.esds.decode=function(buf,offset,end){buf=buf.slice(offset,end);var desc=Descriptor.Descriptor.decode(buf,0,buf.length),esd="ESDescriptor"===desc.tagName?desc:{},dcd=esd.DecoderConfigDescriptor||{},oti=dcd.oti||0,dsi=dcd.DecoderSpecificInfo,audioConfig=dsi?(248&dsi.buffer.readUInt8(0))>>3:0,mimeCodec=null;return oti&&(mimeCodec=oti.toString(16),audioConfig&&(mimeCodec+="."+audioConfig)),{mimeCodec:mimeCodec,buffer:Buffer.from(buf.slice(0))}},exports.esds.encodingLength=function(box){return box.buffer.length},exports.stsz={},exports.stsz.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.stsz.encodingLength(box)),buf.writeUInt32BE(0,0),buf.writeUInt32BE(entries.length,4);for(var i=0;i<entries.length;i++)buf.writeUInt32BE(entries[i],4*i+8);return exports.stsz.encode.bytes=8+4*entries.length,buf},exports.stsz.decode=function(buf,offset){buf=buf.slice(offset);for(var size=buf.readUInt32BE(0),num=buf.readUInt32BE(4),entries=Array(num),i=0;i<num;i++)entries[i]=0===size?buf.readUInt32BE(4*i+8):size;return{entries:entries}},exports.stsz.encodingLength=function(box){return 8+4*box.entries.length},exports.stss=exports.stco={},exports.stco.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.stco.encodingLength(box)),buf.writeUInt32BE(entries.length,0);for(var i=0;i<entries.length;i++)buf.writeUInt32BE(entries[i],4*i+4);return exports.stco.encode.bytes=4+4*entries.length,buf},exports.stco.decode=function(buf,offset){buf=buf.slice(offset);for(var num=buf.readUInt32BE(0),entries=Array(num),i=0;i<num;i++)entries[i]=buf.readUInt32BE(4*i+4);return{entries:entries}},exports.stco.encodingLength=function(box){return 4+4*box.entries.length},exports.co64={},exports.co64.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.co64.encodingLength(box)),buf.writeUInt32BE(entries.length,0);for(var i=0;i<entries.length;i++)uint64be.encode(entries[i],buf,8*i+4);return exports.co64.encode.bytes=4+8*entries.length,buf},exports.co64.decode=function(buf,offset){buf=buf.slice(offset);for(var num=buf.readUInt32BE(0),entries=Array(num),i=0;i<num;i++)entries[i]=uint64be.decode(buf,8*i+4);return{entries:entries}},exports.co64.encodingLength=function(box){return 4+8*box.entries.length},exports.stts={},exports.stts.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.stts.encodingLength(box)),buf.writeUInt32BE(entries.length,0);for(var i=0,ptr;i<entries.length;i++)ptr=8*i+4,buf.writeUInt32BE(entries[i].count||0,ptr),buf.writeUInt32BE(entries[i].duration||0,ptr+4);return exports.stts.encode.bytes=4+8*box.entries.length,buf},exports.stts.decode=function(buf,offset){buf=buf.slice(offset);for(var num=buf.readUInt32BE(0),entries=Array(num),i=0,ptr;i<num;i++)ptr=8*i+4,entries[i]={count:buf.readUInt32BE(ptr),duration:buf.readUInt32BE(ptr+4)};return{entries:entries}},exports.stts.encodingLength=function(box){return 4+8*box.entries.length},exports.ctts={},exports.ctts.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.ctts.encodingLength(box)),buf.writeUInt32BE(entries.length,0);for(var i=0,ptr;i<entries.length;i++)ptr=8*i+4,buf.writeUInt32BE(entries[i].count||0,ptr),buf.writeUInt32BE(entries[i].compositionOffset||0,ptr+4);return exports.ctts.encode.bytes=4+8*entries.length,buf},exports.ctts.decode=function(buf,offset){buf=buf.slice(offset);for(var num=buf.readUInt32BE(0),entries=Array(num),i=0,ptr;i<num;i++)ptr=8*i+4,entries[i]={count:buf.readUInt32BE(ptr),compositionOffset:buf.readInt32BE(ptr+4)};return{entries:entries}},exports.ctts.encodingLength=function(box){return 4+8*box.entries.length},exports.stsc={},exports.stsc.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.stsc.encodingLength(box)),buf.writeUInt32BE(entries.length,0);for(var i=0,ptr;i<entries.length;i++)ptr=12*i+4,buf.writeUInt32BE(entries[i].firstChunk||0,ptr),buf.writeUInt32BE(entries[i].samplesPerChunk||0,ptr+4),buf.writeUInt32BE(entries[i].sampleDescriptionId||0,ptr+8);return exports.stsc.encode.bytes=4+12*entries.length,buf},exports.stsc.decode=function(buf,offset){buf=buf.slice(offset);for(var num=buf.readUInt32BE(0),entries=Array(num),i=0,ptr;i<num;i++)ptr=12*i+4,entries[i]={firstChunk:buf.readUInt32BE(ptr),samplesPerChunk:buf.readUInt32BE(ptr+4),sampleDescriptionId:buf.readUInt32BE(ptr+8)};return{entries:entries}},exports.stsc.encodingLength=function(box){return 4+12*box.entries.length},exports.dref={},exports.dref.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(exports.dref.encodingLength(box));var entries=box.entries||[];buf.writeUInt32BE(entries.length,0);for(var ptr=4,i=0;i<entries.length;i++){var entry=entries[i],size=(entry.buf?entry.buf.length:0)+4+4;buf.writeUInt32BE(size,ptr),ptr+=4,buf.write(entry.type,ptr,4,"ascii"),ptr+=4,entry.buf&&(entry.buf.copy(buf,ptr),ptr+=entry.buf.length)}return exports.dref.encode.bytes=ptr,buf},exports.dref.decode=function(buf,offset){buf=buf.slice(offset);for(var num=buf.readUInt32BE(0),entries=Array(num),ptr=4,i=0;i<num;i++){var size=buf.readUInt32BE(ptr),type=buf.toString("ascii",ptr+4,ptr+8),tmp=buf.slice(ptr+8,ptr+size);ptr+=size,entries[i]={type:type,buf:tmp}}return{entries:entries}},exports.dref.encodingLength=function(box){var totalSize=4;if(!box.entries)return totalSize;for(var i=0,buf;i<box.entries.length;i++)buf=box.entries[i].buf,totalSize+=(buf?buf.length:0)+4+4;return totalSize},exports.elst={},exports.elst.encode=function(box,buf,offset){var entries=box.entries||[];buf=buf?buf.slice(offset):Buffer.alloc(exports.elst.encodingLength(box)),buf.writeUInt32BE(entries.length,0);for(var i=0,ptr;i<entries.length;i++)ptr=12*i+4,buf.writeUInt32BE(entries[i].trackDuration||0,ptr),buf.writeUInt32BE(entries[i].mediaTime||0,ptr+4),writeFixed32(entries[i].mediaRate||0,buf,ptr+8);return exports.elst.encode.bytes=4+12*entries.length,buf},exports.elst.decode=function(buf,offset){buf=buf.slice(offset);for(var num=buf.readUInt32BE(0),entries=Array(num),i=0,ptr;i<num;i++)ptr=12*i+4,entries[i]={trackDuration:buf.readUInt32BE(ptr),mediaTime:buf.readInt32BE(ptr+4),mediaRate:readFixed32(buf,ptr+8)};return{entries:entries}},exports.elst.encodingLength=function(box){return 4+12*box.entries.length},exports.hdlr={},exports.hdlr.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(exports.hdlr.encodingLength(box));var len=21+(box.name||"").length;return buf.fill(0,0,len),buf.write(box.handlerType||"",4,4,"ascii"),writeString(box.name||"",buf,20),exports.hdlr.encode.bytes=len,buf},exports.hdlr.decode=function(buf,offset,end){return buf=buf.slice(offset),{handlerType:buf.toString("ascii",4,8),name:readString(buf,20,end)}},exports.hdlr.encodingLength=function(box){return 21+(box.name||"").length},exports.mehd={},exports.mehd.encode=function(box,buf,offset){return buf=buf?buf.slice(offset):Buffer.alloc(4),buf.writeUInt32BE(box.fragmentDuration||0,0),exports.mehd.encode.bytes=4,buf},exports.mehd.decode=function(buf,offset){return buf=buf.slice(offset),{fragmentDuration:buf.readUInt32BE(0)}},exports.mehd.encodingLength=function(){return 4},exports.trex={},exports.trex.encode=function(box,buf,offset){return buf=buf?buf.slice(offset):Buffer.alloc(20),buf.writeUInt32BE(box.trackId||0,0),buf.writeUInt32BE(box.defaultSampleDescriptionIndex||0,4),buf.writeUInt32BE(box.defaultSampleDuration||0,8),buf.writeUInt32BE(box.defaultSampleSize||0,12),buf.writeUInt32BE(box.defaultSampleFlags||0,16),exports.trex.encode.bytes=20,buf},exports.trex.decode=function(buf,offset){return buf=buf.slice(offset),{trackId:buf.readUInt32BE(0),defaultSampleDescriptionIndex:buf.readUInt32BE(4),defaultSampleDuration:buf.readUInt32BE(8),defaultSampleSize:buf.readUInt32BE(12),defaultSampleFlags:buf.readUInt32BE(16)}},exports.trex.encodingLength=function(){return 20},exports.mfhd={},exports.mfhd.encode=function(box,buf,offset){return buf=buf?buf.slice(offset):Buffer.alloc(4),buf.writeUInt32BE(box.sequenceNumber||0,0),exports.mfhd.encode.bytes=4,buf},exports.mfhd.decode=function(buf){return{sequenceNumber:buf.readUInt32BE(0)}},exports.mfhd.encodingLength=function(){return 4},exports.tfhd={},exports.tfhd.encode=function(box,buf,offset){return buf=buf?buf.slice(offset):Buffer.alloc(4),buf.writeUInt32BE(box.trackId,0),exports.tfhd.encode.bytes=4,buf},exports.tfhd.decode=function(){},exports.tfhd.encodingLength=function(){return 4},exports.tfdt={},exports.tfdt.encode=function(box,buf,offset){return buf=buf?buf.slice(offset):Buffer.alloc(4),buf.writeUInt32BE(box.baseMediaDecodeTime||0,0),exports.tfdt.encode.bytes=4,buf},exports.tfdt.decode=function(){},exports.tfdt.encodingLength=function(){return 4},exports.trun={},exports.trun.encode=function(box,buf,offset){buf=buf?buf.slice(offset):Buffer.alloc(8+16*box.entries.length),buf.writeUInt32BE(box.entries.length,0),buf.writeInt32BE(box.dataOffset,4);for(var ptr=8,i=0,entry;i<box.entries.length;i++)entry=box.entries[i],buf.writeUInt32BE(entry.sampleDuration,ptr),ptr+=4,buf.writeUInt32BE(entry.sampleSize,ptr),ptr+=4,buf.writeUInt32BE(entry.sampleFlags,ptr),ptr+=4,0===(box.version||0)?buf.writeUInt32BE(entry.sampleCompositionTimeOffset,ptr):buf.writeInt32BE(entry.sampleCompositionTimeOffset,ptr),ptr+=4;exports.trun.encode.bytes=ptr},exports.trun.decode=function(){},exports.trun.encodingLength=function(box){return 8+16*box.entries.length},exports.mdat={},exports.mdat.encode=function(box,buf,offset){box.buffer?(box.buffer.copy(buf,offset),exports.mdat.encode.bytes=box.buffer.length):exports.mdat.encode.bytes=exports.mdat.encodingLength(box)},exports.mdat.decode=function(buf,start,end){return{buffer:Buffer.from(buf.slice(start,end))}},exports.mdat.encodingLength=function(box){return box.buffer?box.buffer.length:box.contentLength}}).call(this,require("buffer").Buffer)},{"./descriptor":48,"./index":49,buffer:26,uint64be:113}],48:[function(require,module,exports){(function(Buffer){var tagToName={3:"ESDescriptor",4:"DecoderConfigDescriptor",5:"DecoderSpecificInfo",6:"SLConfigDescriptor"};exports.Descriptor={},exports.Descriptor.decode=function(buf,start,end){var tag=buf.readUInt8(start),ptr=start+1,len=0,lenByte;do lenByte=buf.readUInt8(ptr++),len=len<<7|127&lenByte;while(128&lenByte);var tagName=tagToName[tag],obj;return obj=exports[tagName]?exports[tagName].decode(buf,ptr,end):{buffer:Buffer.from(buf.slice(ptr,ptr+len))},obj.tag=tag,obj.tagName=tagName,obj.length=ptr-start+len,obj.contentsLen=len,obj},exports.DescriptorArray={},exports.DescriptorArray.decode=function(buf,start,end){for(var ptr=start,obj={};ptr+2<=end;){var descriptor=exports.Descriptor.decode(buf,ptr,end);ptr+=descriptor.length;var tagName=tagToName[descriptor.tag]||"Descriptor"+descriptor.tag;obj[tagName]=descriptor}return obj},exports.ESDescriptor={},exports.ESDescriptor.decode=function(buf,start,end){var flags=buf.readUInt8(start+2),ptr=start+3;if(128&flags&&(ptr+=2),64&flags){var len=buf.readUInt8(ptr);ptr+=len+1}return 32&flags&&(ptr+=2),exports.DescriptorArray.decode(buf,ptr,end)},exports.DecoderConfigDescriptor={},exports.DecoderConfigDescriptor.decode=function(buf,start,end){var oti=buf.readUInt8(start),obj=exports.DescriptorArray.decode(buf,start+13,end);return obj.oti=oti,obj}}).call(this,require("buffer").Buffer)},{buffer:26}],49:[function(require,module,exports){(function(Buffer){var uint64be=require("uint64be"),boxes=require("./boxes"),UINT32_MAX=4294967295,Box=exports,containers=exports.containers={moov:["mvhd","meta","traks","mvex"],trak:["tkhd","tref","trgr","edts","meta","mdia","udta"],edts:["elst"],mdia:["mdhd","hdlr","elng","minf"],minf:["vmhd","smhd","hmhd","sthd","nmhd","dinf","stbl"],dinf:["dref"],stbl:["stsd","stts","ctts","cslg","stsc","stsz","stz2","stco","co64","stss","stsh","padb","stdp","sdtp","sbgps","sgpds","subss","saizs","saios"],mvex:["mehd","trexs","leva"],moof:["mfhd","meta","trafs"],traf:["tfhd","tfdt","trun","sbgps","sgpds","subss","saizs","saios","meta"]};Box.encode=function(obj,buffer,offset){return Box.encodingLength(obj),offset=offset||0,buffer=buffer||Buffer.alloc(obj.length),Box._encode(obj,buffer,offset)},Box._encode=function(obj,buffer,offset){var type=obj.type,len=obj.length;len>UINT32_MAX&&(len=1),buffer.writeUInt32BE(len,offset),buffer.write(obj.type,offset+4,4,"ascii");var ptr=offset+8;if(1===len&&(uint64be.encode(obj.length,buffer,ptr),ptr+=8),boxes.fullBoxes[type]&&(buffer.writeUInt32BE(obj.flags||0,ptr),buffer.writeUInt8(obj.version||0,ptr),ptr+=4),containers[type]){var contents=containers[type];contents.forEach(function(childType){if(5===childType.length){var entry=obj[childType]||[];childType=childType.substr(0,4),entry.forEach(function(child){Box._encode(child,buffer,ptr),ptr+=Box.encode.bytes})}else obj[childType]&&(Box._encode(obj[childType],buffer,ptr),ptr+=Box.encode.bytes)}),obj.otherBoxes&&obj.otherBoxes.forEach(function(child){Box._encode(child,buffer,ptr),ptr+=Box.encode.bytes})}else if(boxes[type]){var encode=boxes[type].encode;encode(obj,buffer,ptr),ptr+=encode.bytes}else if(obj.buffer){var buf=obj.buffer;buf.copy(buffer,ptr),ptr+=obj.buffer.length}else throw new Error("Either `type` must be set to a known type (not'"+type+"') or `buffer` must be set");return Box.encode.bytes=ptr-offset,buffer},Box.readHeaders=function(buffer,start,end){if(start=start||0,end=end||buffer.length,8>end-start)return 8;var len=buffer.readUInt32BE(start),type=buffer.toString("ascii",start+4,start+8),ptr=start+8;if(1===len){if(16>end-start)return 16;len=uint64be.decode(buffer,ptr),ptr+=8}var version,flags;return boxes.fullBoxes[type]&&(version=buffer.readUInt8(ptr),flags=16777215&buffer.readUInt32BE(ptr),ptr+=4),{length:len,headersLen:ptr-start,contentLen:len-(ptr-start),type:type,version:version,flags:flags}},Box.decode=function(buffer,start,end){start=start||0,end=end||buffer.length;var headers=Box.readHeaders(buffer,start,end);if(!headers||headers.length>end-start)throw new Error("Data too short");return Box.decodeWithoutHeaders(headers,buffer,start+headers.headersLen,start+headers.length)},Box.decodeWithoutHeaders=function(headers,buffer,start,end){start=start||0,end=end||buffer.length;var type=headers.type,obj={};if(containers[type]){obj.otherBoxes=[];for(var contents=containers[type],ptr=start,child;8<=end-ptr;)if(child=Box.decode(buffer,ptr,end),ptr+=child.length,0<=contents.indexOf(child.type))obj[child.type]=child;else if(0<=contents.indexOf(child.type+"s")){var childType=child.type+"s",entry=obj[childType]=obj[childType]||[];entry.push(child)}else obj.otherBoxes.push(child)}else if(boxes[type]){var decode=boxes[type].decode;obj=decode(buffer,start,end)}else obj.buffer=Buffer.from(buffer.slice(start,end));return obj.length=headers.length,obj.contentLen=headers.contentLen,obj.type=headers.type,obj.version=headers.version,obj.flags=headers.flags,obj},Box.encodingLength=function(obj){var type=obj.type,len=8;if(boxes.fullBoxes[type]&&(len+=4),containers[type]){var contents=containers[type];contents.forEach(function(childType){if(5===childType.length){var entry=obj[childType]||[];childType=childType.substr(0,4),entry.forEach(function(child){child.type=childType,len+=Box.encodingLength(child)})}else if(obj[childType]){var child=obj[childType];child.type=childType,len+=Box.encodingLength(child)}}),obj.otherBoxes&&obj.otherBoxes.forEach(function(child){len+=Box.encodingLength(child)})}else if(boxes[type])len+=boxes[type].encodingLength(obj);else if(obj.buffer)len+=obj.buffer.length;else throw new Error("Either `type` must be set to a known type (not'"+type+"') or `buffer` must be set");return len>UINT32_MAX&&(len+=8),obj.length=len,len}}).call(this,require("buffer").Buffer)},{"./boxes":47,buffer:26,uint64be:113}],50:[function(require,module){(function(Buffer){var stream=require("readable-stream"),nextEvent=require("next-event"),Box=require("mp4-box-encoding"),EMPTY=Buffer.alloc(0);class Decoder extends stream.Writable{constructor(opts){super(opts),this.destroyed=!1,this._pending=0,this._missing=0,this._ignoreEmpty=!1,this._buf=null,this._str=null,this._cb=null,this._ondrain=null,this._writeBuffer=null,this._writeCb=null,this._ondrain=null,this._kick()}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err),this.emit("close"))}_write(data,enc,next){if(!this.destroyed){for(var drained=!this._str||!this._str._writableState.needDrain;data.length&&!this.destroyed;){if(!this._missing&&!this._ignoreEmpty)return this._writeBuffer=data,void(this._writeCb=next);var consumed=data.length<this._missing?data.length:this._missing;if(this._buf?data.copy(this._buf,this._buf.length-this._missing):this._str&&(drained=this._str.write(consumed===data.length?data:data.slice(0,consumed))),this._missing-=consumed,!this._missing){var buf=this._buf,cb=this._cb,stream=this._str;this._buf=this._cb=this._str=this._ondrain=null,drained=!0,this._ignoreEmpty=!1,stream&&stream.end(),cb&&cb(buf)}data=consumed===data.length?EMPTY:data.slice(consumed)}return this._pending&&!this._missing?(this._writeBuffer=data,void(this._writeCb=next)):void(drained?next():this._ondrain(next))}}_buffer(size,cb){this._missing=size,this._buf=Buffer.alloc(size),this._cb=cb}_stream(size,cb){return this._missing=size,this._str=new MediaData(this),this._ondrain=nextEvent(this._str,"drain"),this._pending++,this._str.on("end",()=>{this._pending--,this._kick()}),this._cb=cb,this._str}_readBox(){const bufferHeaders=(len,buf)=>{this._buffer(len,additionalBuf=>{buf=buf?Buffer.concat([buf,additionalBuf]):additionalBuf;var headers=Box.readHeaders(buf);"number"==typeof headers?bufferHeaders(headers-buf.length,buf):(this._pending++,this._headers=headers,this.emit("box",headers))})};bufferHeaders(8)}stream(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;return this._headers=null,this._stream(headers.contentLen,null)}decode(cb){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;this._headers=null,this._buffer(headers.contentLen,buf=>{var box=Box.decodeWithoutHeaders(headers,buf);cb(box),this._pending--,this._kick()})}ignore(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var headers=this._headers;this._headers=null,this._missing=headers.contentLen,0===this._missing&&(this._ignoreEmpty=!0),this._cb=()=>{this._pending--,this._kick()}}_kick(){if(!this._pending&&(this._buf||this._str||this._readBox(),this._writeBuffer)){var next=this._writeCb,buffer=this._writeBuffer;this._writeBuffer=null,this._writeCb=null,this._write(buffer,null,next)}}}class MediaData extends stream.PassThrough{constructor(parent){super(),this._parent=parent,this.destroyed=!1}destroy(err){this.destroyed||(this.destroyed=!0,this._parent.destroy(err),err&&this.emit("error",err),this.emit("close"))}}module.exports=Decoder}).call(this,require("buffer").Buffer)},{buffer:26,"mp4-box-encoding":49,"next-event":55,"readable-stream":85}],51:[function(require,module){(function(process,Buffer){function noop(){}var stream=require("readable-stream"),Box=require("mp4-box-encoding");class Encoder extends stream.Readable{constructor(opts){super(opts),this.destroyed=!1,this._finalized=!1,this._reading=!1,this._stream=null,this._drain=null,this._want=!1,this._onreadable=()=>{this._want&&(this._want=!1,this._read())},this._onend=()=>{this._stream=null}}mdat(size,cb){this.mediaData(size,cb)}mediaData(size,cb){var stream=new MediaData(this);return this.box({type:"mdat",contentLength:size,encodeBufferLen:8,stream:stream},cb),stream}box(box,cb){if(cb||(cb=noop),this.destroyed)return cb(new Error("Encoder is destroyed"));var buf;if(box.encodeBufferLen&&(buf=Buffer.alloc(box.encodeBufferLen)),box.stream)box.buffer=null,buf=Box.encode(box,buf),this.push(buf),this._stream=box.stream,this._stream.on("readable",this._onreadable),this._stream.on("end",this._onend),this._stream.on("end",cb),this._forward();else{buf=Box.encode(box,buf);var drained=this.push(buf);if(drained)return process.nextTick(cb);this._drain=cb}}destroy(err){if(!this.destroyed){if(this.destroyed=!0,this._stream&&this._stream.destroy&&this._stream.destroy(),this._stream=null,this._drain){var cb=this._drain;this._drain=null,cb(err)}err&&this.emit("error",err),this.emit("close")}}finalize(){this._finalized=!0,this._stream||this._drain||this.push(null)}_forward(){if(this._stream)for(;!this.destroyed;){var buf=this._stream.read();if(!buf)return void(this._want=!!this._stream);if(!this.push(buf))return}}_read(){if(!(this._reading||this.destroyed)){if(this._reading=!0,this._stream&&this._forward(),this._drain){var drain=this._drain;this._drain=null,drain()}this._reading=!1,this._finalized&&this.push(null)}}}class MediaData extends stream.PassThrough{constructor(parent){super(),this._parent=parent,this.destroyed=!1}destroy(err){this.destroyed||(this.destroyed=!0,this._parent.destroy(err),err&&this.emit("error",err),this.emit("close"))}}module.exports=Encoder}).call(this,require("_process"),require("buffer").Buffer)},{_process:61,buffer:26,"mp4-box-encoding":49,"readable-stream":85}],52:[function(require,module,exports){const Decoder=require("./decode"),Encoder=require("./encode");exports.decode=opts=>new Decoder(opts),exports.encode=opts=>new Encoder(opts)},{"./decode":50,"./encode":51}],53:[function(require,module){var _Mathround=Math.round;function parse(str){if(str+="",!(100<str.length)){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);if(match){var n=parseFloat(match[1]),type=(match[2]||"ms").toLowerCase();return"years"===type||"year"===type||"yrs"===type||"yr"===type||"y"===type?31557600000*n:"weeks"===type||"week"===type||"w"===type?604800000*n:"days"===type||"day"===type||"d"===type?86400000*n:"hours"===type||"hour"===type||"hrs"===type||"hr"===type||"h"===type?3600000*n:"minutes"===type||"minute"===type||"mins"===type||"min"===type||"m"===type?60000*n:"seconds"===type||"second"===type||"secs"===type||"sec"===type||"s"===type?1000*n:"milliseconds"===type||"millisecond"===type||"msecs"===type||"msec"===type||"ms"===type?n:void 0}}}function fmtShort(ms){var msAbs=_Mathabs(ms);return 86400000<=msAbs?_Mathround(ms/86400000)+"d":3600000<=msAbs?_Mathround(ms/3600000)+"h":60000<=msAbs?_Mathround(ms/60000)+"m":1000<=msAbs?_Mathround(ms/1000)+"s":ms+"ms"}function fmtLong(ms){var msAbs=_Mathabs(ms);return 86400000<=msAbs?plural(ms,msAbs,86400000,"day"):3600000<=msAbs?plural(ms,msAbs,3600000,"hour"):60000<=msAbs?plural(ms,msAbs,60000,"minute"):1000<=msAbs?plural(ms,msAbs,1000,"second"):ms+" ms"}function plural(ms,msAbs,n,name){return _Mathround(ms/n)+" "+name+(msAbs>=1.5*n?"s":"")}var d=24*(60*60000);module.exports=function(val,options){options=options||{};var type=typeof val;if("string"==type&&0<val.length)return parse(val);if("number"===type&&isFinite(val))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))}},{}],54:[function(require,module){function toStreams2Obj(s){return toStreams2(s,{objectMode:!0,highWaterMark:16})}function toStreams2Buf(s){return toStreams2(s)}function toStreams2(s,opts){if(!s||"function"==typeof s||s._readableState)return s;var wrap=new stream.Readable(opts).wrap(s);return s.destroy&&(wrap.destroy=s.destroy.bind(s)),wrap}var stream=require("readable-stream");class MultiStream extends stream.Readable{constructor(streams,opts){super(opts),this.destroyed=!1,this._drained=!1,this._forwarding=!1,this._current=null,this._toStreams2=opts&&opts.objectMode?toStreams2Obj:toStreams2Buf,"function"==typeof streams?this._queue=streams:(this._queue=streams.map(this._toStreams2),this._queue.forEach(stream=>{"function"!=typeof stream&&this._attachErrorListener(stream)})),this._next()}_read(){this._drained=!0,this._forward()}_forward(){if(!this._forwarding&&this._drained&&this._current){this._forwarding=!0;for(var chunk;null!==(chunk=this._current.read())&&this._drained;)this._drained=this.push(chunk);this._forwarding=!1}}destroy(err){this.destroyed||(this.destroyed=!0,this._current&&this._current.destroy&&this._current.destroy(),"function"!=typeof this._queue&&this._queue.forEach(stream=>{stream.destroy&&stream.destroy()}),err&&this.emit("error",err),this.emit("close"))}_next(){if(this._current=null,"function"==typeof this._queue)this._queue((err,stream)=>err?this.destroy(err):void(stream=this._toStreams2(stream),this._attachErrorListener(stream),this._gotNextStream(stream)));else{var stream=this._queue.shift();"function"==typeof stream&&(stream=this._toStreams2(stream()),this._attachErrorListener(stream)),this._gotNextStream(stream)}}_gotNextStream(stream){if(!stream)return this.push(null),void this.destroy();this._current=stream,this._forward();const onReadable=()=>{this._forward()},onClose=()=>{stream._readableState.ended||this.destroy()},onEnd=()=>{this._current=null,stream.removeListener("readable",onReadable),stream.removeListener("end",onEnd),stream.removeListener("close",onClose),this._next()};stream.on("readable",onReadable),stream.once("end",onEnd),stream.once("close",onClose)}_attachErrorListener(stream){if(!stream)return;const onError=err=>{stream.removeListener("error",onError),this.destroy(err)};stream.once("error",onError)}}MultiStream.obj=streams=>new MultiStream(streams,{objectMode:!0,highWaterMark:16}),module.exports=MultiStream},{"readable-stream":85}],55:[function(require,module){module.exports=function(emitter,name){var next=null;return emitter.on(name,function(data){if(next){var fn=next;next=null,fn(data)}}),function(once){next=once}}},{}],56:[function(require,module){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:122}],57:[function(require,module){function parsePart(str){if(/^-?\d+$/.test(str))return parseInt(str,10);var m;if(m=str.match(/^(-?\d+)(-|\.\.\.?|\u2025|\u2026|\u22EF)(-?\d+)$/)){var lhs=m[1],sep=m[2],rhs=m[3];if(lhs&&rhs){lhs=parseInt(lhs),rhs=parseInt(rhs);var res=[],incr=lhs<rhs?1:-1;("-"==sep||".."==sep||"\u2025"==sep)&&(rhs+=incr);for(var i=lhs;i!=rhs;i+=incr)res.push(i);return res}}return[]}module.exports.parse=function(str){var parts=str.split(","),toFlatten=parts.map(function(el){return parsePart(el)});return 0===toFlatten.length?[]:1===toFlatten.length?Array.isArray(toFlatten[0])?toFlatten[0]:toFlatten:toFlatten.reduce(function(lhs,rhs){return Array.isArray(lhs)||(lhs=[lhs]),Array.isArray(rhs)||(rhs=[rhs]),lhs.concat(rhs)})}},{}],58:[function(require,module){(function(process,Buffer){function parseTorrent(torrentId){if("string"==typeof torrentId&&/^(stream-)?magnet:/.test(torrentId)){const torrentObj=magnet(torrentId);if(!torrentObj.infoHash)throw new Error("Invalid torrent identifier");return torrentObj}if("string"==typeof torrentId&&(/^[a-f0-9]{40}$/i.test(torrentId)||/^[a-z2-7]{32}$/i.test(torrentId)))return magnet(`magnet:?xt=urn:btih:${torrentId}`);if(Buffer.isBuffer(torrentId)&&20===torrentId.length)return magnet(`magnet:?xt=urn:btih:${torrentId.toString("hex")}`);if(Buffer.isBuffer(torrentId))return decodeTorrentFile(torrentId);if(torrentId&&torrentId.infoHash)return torrentId.infoHash=torrentId.infoHash.toLowerCase(),torrentId.announce||(torrentId.announce=[]),"string"==typeof torrentId.announce&&(torrentId.announce=[torrentId.announce]),torrentId.urlList||(torrentId.urlList=[]),torrentId;throw new Error("Invalid torrent identifier")}function decodeTorrentFile(torrent){Buffer.isBuffer(torrent)&&(torrent=bencode.decode(torrent)),ensure(torrent.info,"info"),ensure(torrent.info["name.utf-8"]||torrent.info.name,"info.name"),ensure(torrent.info["piece length"],"info['piece length']"),ensure(torrent.info.pieces,"info.pieces"),torrent.info.files?torrent.info.files.forEach(file=>{ensure("number"==typeof file.length,"info.files[0].length"),ensure(file["path.utf-8"]||file.path,"info.files[0].path")}):ensure("number"==typeof torrent.info.length,"info.length");const result={info:torrent.info,infoBuffer:bencode.encode(torrent.info),name:(torrent.info["name.utf-8"]||torrent.info.name).toString(),announce:[]};result.infoHash=sha1.sync(result.infoBuffer),result.infoHashBuffer=Buffer.from(result.infoHash,"hex"),void 0!==torrent.info.private&&(result.private=!!torrent.info.private),torrent["creation date"]&&(result.created=new Date(1e3*torrent["creation date"])),torrent["created by"]&&(result.createdBy=torrent["created by"].toString()),Buffer.isBuffer(torrent.comment)&&(result.comment=torrent.comment.toString()),Array.isArray(torrent["announce-list"])&&0<torrent["announce-list"].length?torrent["announce-list"].forEach(urls=>{urls.forEach(url=>{result.announce.push(url.toString())})}):torrent.announce&&result.announce.push(torrent.announce.toString()),Buffer.isBuffer(torrent["url-list"])&&(torrent["url-list"]=0<torrent["url-list"].length?[torrent["url-list"]]:[]),result.urlList=(torrent["url-list"]||[]).map(url=>url.toString()),result.announce=Array.from(new Set(result.announce)),result.urlList=Array.from(new Set(result.urlList));const files=torrent.info.files||[torrent.info];result.files=files.map((file,i)=>{const parts=[].concat(result.name,file["path.utf-8"]||file.path||[]).map(p=>p.toString());return{path:path.join.apply(null,[path.sep].concat(parts)).slice(1),name:parts[parts.length-1],length:file.length,offset:files.slice(0,i).reduce(sumLength,0)}}),result.length=files.reduce(sumLength,0);const lastFile=result.files[result.files.length-1];return result.pieceLength=torrent.info["piece length"],result.lastPieceLength=(lastFile.offset+lastFile.length)%result.pieceLength||result.pieceLength,result.pieces=splitPieces(torrent.info.pieces),result}function isBlob(obj){return"undefined"!=typeof Blob&&obj instanceof Blob}function sumLength(sum,file){return sum+file.length}function splitPieces(buf){const pieces=[];for(let i=0;i<buf.length;i+=20)pieces.push(buf.slice(i,i+20).toString("hex"));return pieces}function ensure(bool,fieldName){if(!bool)throw new Error(`Torrent is missing required field: ${fieldName}`)}const bencode=require("bencode"),blobToBuffer=require("blob-to-buffer"),fs=require("fs"),get=require("simple-get"),magnet=require("magnet-uri"),path=require("path"),sha1=require("simple-sha1");module.exports=parseTorrent,module.exports.remote=function(torrentId,cb){function parseOrThrow(torrentBuf){try{parsedTorrent=parseTorrent(torrentBuf)}catch(err){return cb(err)}parsedTorrent&&parsedTorrent.infoHash?cb(null,parsedTorrent):cb(new Error("Invalid torrent identifier"))}let parsedTorrent;if("function"!=typeof cb)throw new Error("second argument must be a Function");try{parsedTorrent=parseTorrent(torrentId)}catch(err){}parsedTorrent&&parsedTorrent.infoHash?process.nextTick(()=>{cb(null,parsedTorrent)}):isBlob(torrentId)?blobToBuffer(torrentId,(err,torrentBuf)=>err?cb(new Error(`Error converting Blob: ${err.message}`)):void parseOrThrow(torrentBuf)):"function"==typeof get&&/^https?:/.test(torrentId)?get.concat({url:torrentId,timeout:30000,headers:{"user-agent":"WebTorrent (https://webtorrent.io)"}},(err,res,torrentBuf)=>err?cb(new Error(`Error downloading torrent: ${err.message}`)):void parseOrThrow(torrentBuf)):"function"==typeof fs.readFile&&"string"==typeof torrentId?fs.readFile(torrentId,(err,torrentBuf)=>err?cb(new Error("Invalid torrent identifier")):void parseOrThrow(torrentBuf)):process.nextTick(()=>{cb(new Error("Invalid torrent identifier"))})},module.exports.toMagnetURI=magnet.encode,module.exports.toTorrentFile=function(parsed){const torrent={info:parsed.info};return torrent["announce-list"]=(parsed.announce||[]).map(url=>(torrent.announce||(torrent.announce=url),url=Buffer.from(url,"utf8"),[url])),torrent["url-list"]=parsed.urlList||[],void 0!==parsed.private&&(torrent.private=+parsed.private),parsed.created&&(torrent["creation date"]=0|parsed.created.getTime()/1e3),parsed.createdBy&&(torrent["created by"]=parsed.createdBy),parsed.comment&&(torrent.comment=parsed.comment),bencode.encode(torrent)};(()=>{Buffer.alloc(0)})()}).call(this,require("_process"),require("buffer").Buffer)},{_process:61,bencode:11,"blob-to-buffer":19,buffer:26,fs:22,"magnet-uri":44,path:59,"simple-get":93,"simple-sha1":95}],59:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){for(var up=0,i=parts.length-1,last;0<=i;i--)last=parts[i],"."===last?parts.splice(i,1):".."===last?(parts.splice(i,1),up++):up&&(parts.splice(i,1),up--);if(allowAboveRoot)for(;up--;up)parts.unshift("..");return parts}function basename(path){"string"!=typeof path&&(path+="");var start=0,end=-1,matchedSlash=!0,i;for(i=path.length-1;0<=i;--i)if(!(47===path.charCodeAt(i)))-1===end&&(matchedSlash=!1,end=i+1);else if(!matchedSlash){start=i+1;break}return-1===end?"":path.slice(start,end)}function filter(xs,f){if(xs.filter)return xs.filter(f);for(var res=[],i=0;i<xs.length;i++)f(xs[i],i,xs)&&res.push(xs[i]);return res}exports.resolve=function(){for(var resolvedPath="",resolvedAbsolute=!1,i=arguments.length-1,path;-1<=i&&!resolvedAbsolute;i--){if(path=0<=i?arguments[i]:process.cwd(),"string"!=typeof path)throw new TypeError("Arguments to path.resolve must be strings");else if(!path)continue;resolvedPath=path+"/"+resolvedPath,resolvedAbsolute="/"===path.charAt(0)}return resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/"),(resolvedAbsolute?"/":"")+resolvedPath||"."},exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash="/"===substr(path,-1);return path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/"),path||isAbsolute||(path="."),path&&trailingSlash&&(path+="/"),(isAbsolute?"/":"")+path},exports.isAbsolute=function(path){return"/"===path.charAt(0)},exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p){if("string"!=typeof p)throw new TypeError("Arguments to path.join must be strings");return p}).join("/"))},exports.relative=function(from,to){function trim(arr){for(var start=0;start<arr.length&&""===arr[start];start++);for(var end=arr.length-1;0<=end&&""===arr[end];end--);return start>end?[]:arr.slice(start,end-start+1)}from=exports.resolve(from).substr(1),to=exports.resolve(to).substr(1);for(var fromParts=trim(from.split("/")),toParts=trim(to.split("/")),length=_Mathmin(fromParts.length,toParts.length),samePartsLength=length,i=0;i<length;i++)if(fromParts[i]!==toParts[i]){samePartsLength=i;break}for(var outputParts=[],i=samePartsLength;i<fromParts.length;i++)outputParts.push("..");return outputParts=outputParts.concat(toParts.slice(samePartsLength)),outputParts.join("/")},exports.sep="/",exports.delimiter=":",exports.dirname=function(path){if("string"!=typeof path&&(path+=""),0===path.length)return".";for(var code=path.charCodeAt(0),hasRoot=47===code,end=-1,matchedSlash=!0,i=path.length-1;1<=i;--i)if(code=path.charCodeAt(i),47!==code)matchedSlash=!1;else if(!matchedSlash){end=i;break}return-1===end?hasRoot?"/":".":hasRoot&&1===end?"/":path.slice(0,end)},exports.basename=function(path,ext){var f=basename(path);return ext&&f.substr(-1*ext.length)===ext&&(f=f.substr(0,f.length-ext.length)),f},exports.extname=function(path){"string"!=typeof path&&(path+="");for(var startDot=-1,startPart=0,end=-1,matchedSlash=!0,preDotState=0,i=path.length-1,code;0<=i;--i){if(code=path.charCodeAt(i),47===code){if(!matchedSlash){startPart=i+1;break}continue}-1===end&&(matchedSlash=!1,end=i+1),46===code?-1===startDot?startDot=i:1!==preDotState&&(preDotState=1):-1!==startDot&&(preDotState=-1)}return-1===startDot||-1===end||0===preDotState||1===preDotState&&startDot===end-1&&startDot===startPart+1?"":path.slice(startDot,end)};var substr=function(str,start,len){return str.substr(start,len)}}).call(this,require("_process"))},{_process:61}],60:[function(require,module){module.exports=function(bytes){return _Mathmax(16384,0|1<<Math.log2(1024>bytes?1:bytes/1024)+.5)}},{}],61:[function(require,module){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}var process=module.exports={},cachedSetTimeout,cachedClearTimeout;(function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}})();var queue=[],draining=!1,queueIndex=-1,currentQueue;process.nextTick=function(fun){var args=Array(arguments.length-1);if(1<arguments.length)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},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(){return[]},process.binding=function(){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],62:[function(require,module){(function(process){var once=require("once"),eos=require("end-of-stream"),fs=require("fs"),noop=function(){},ancient=/^v?\.0/.test(process.version),isFn=function(fn){return"function"==typeof fn},isFS=function(stream){return!!ancient&&!!fs&&(stream instanceof(fs.ReadStream||noop)||stream instanceof(fs.WriteStream||noop))&&isFn(stream.close)},isRequest=function(stream){return stream.setHeader&&isFn(stream.abort)},destroyer=function(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isFS(stream)?stream.close(noop):isRequest(stream)?stream.abort():isFn(stream.destroy)?stream.destroy():void callback(err||new Error("stream was destroyed")))}},call=function(fn){fn()},pipe=function(from,to){return from.pipe(to)};module.exports=function(){var streams=Array.prototype.slice.call(arguments),callback=isFn(streams[streams.length-1]||noop)&&streams.pop()||noop;if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new Error("pump requires two streams per minimum");var destroys=streams.map(function(stream,i){var reading=i<streams.length-1;return destroyer(stream,reading,0<i,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})}),error;return streams.reduce(pipe)}}).call(this,require("_process"))},{_process:61,"end-of-stream":32,fs:21,once:56}],63:[function(require,module,exports){(function(global){/*! https://mths.be/punycode v1.4.1 by @mathias */(function(root){function error(type){throw new RangeError(errors[type])}function map(array,fn){for(var length=array.length,result=[];length--;)result[length]=fn(array[length]);return result}function mapDomain(string,fn){var parts=string.split("@"),result="";1<parts.length&&(result=parts[0]+"@",string=parts[1]),string=string.replace(regexSeparators,".");var labels=string.split("."),encoded=map(labels,fn).join(".");return result+encoded}function ucs2decode(string){for(var output=[],counter=0,length=string.length,value,extra;counter<length;)value=string.charCodeAt(counter++),55296<=value&&56319>=value&&counter<length?(extra=string.charCodeAt(counter++),56320==(64512&extra)?output.push(((1023&value)<<10)+(1023&extra)+65536):(output.push(value),counter--)):output.push(value);return output}function ucs2encode(array){return map(array,function(value){var output="";return 65535<value&&(value-=65536,output+=stringFromCharCode(55296|1023&value>>>10),value=56320|1023&value),output+=stringFromCharCode(value),output}).join("")}function basicToDigit(codePoint){return 10>codePoint-48?codePoint-22:26>codePoint-65?codePoint-65:26>codePoint-97?codePoint-97:36}function digitToBasic(digit,flag){return digit+22+75*(26>digit)-((0!=flag)<<5)}function adapt(delta,numPoints,firstTime){var k=0;for(delta=firstTime?floor(delta/700):delta>>1,delta+=floor(delta/numPoints);455<delta;k+=36)delta=floor(delta/35);return floor(k+36*delta/(delta+38))}function decode(input){var output=[],inputLength=input.length,i=0,n=128,bias=72,out,basic,j,index,oldi,w,k,digit,t,baseMinusT;for(basic=input.lastIndexOf("-"),0>basic&&(basic=0),j=0;j<basic;++j)128<=input.charCodeAt(j)&&error("not-basic"),output.push(input.charCodeAt(j));for(index=0<basic?basic+1:0;index<inputLength;){for(oldi=i,w=1,k=36;;k+=36){if(index>=inputLength&&error("invalid-input"),digit=basicToDigit(input.charCodeAt(index++)),(36<=digit||digit>floor((2147483647-i)/w))&&error("overflow"),i+=digit*w,t=k<=bias?1:k>=bias+26?26:k-bias,digit<t)break;baseMinusT=36-t,w>floor(2147483647/baseMinusT)&&error("overflow"),w*=baseMinusT}out=output.length+1,bias=adapt(i-oldi,out,0==oldi),floor(i/out)>2147483647-n&&error("overflow"),n+=floor(i/out),i%=out,output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var output=[],n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;for(input=ucs2decode(input),inputLength=input.length,n=128,delta=0,bias=72,j=0;j<inputLength;++j)currentValue=input[j],128>currentValue&&output.push(stringFromCharCode(currentValue));for(handledCPCount=basicLength=output.length,basicLength&&output.push("-");handledCPCount<inputLength;){for(m=2147483647,j=0;j<inputLength;++j)currentValue=input[j],currentValue>=n&¤tValue<m&&(m=currentValue);for(handledCPCountPlusOne=handledCPCount+1,m-n>floor((2147483647-delta)/handledCPCountPlusOne)&&error("overflow"),delta+=(m-n)*handledCPCountPlusOne,n=m,j=0;j<inputLength;++j)if(currentValue=input[j],currentValue<n&&2147483647<++delta&&error("overflow"),currentValue==n){for(q=delta,k=36;;k+=36){if(t=k<=bias?1:k>=bias+26?26:k-bias,q<t)break;qMinusT=q-t,baseMinusT=36-t,output.push(stringFromCharCode(digitToBasic(t+qMinusT%baseMinusT,0))),q=floor(qMinusT/baseMinusT)}output.push(stringFromCharCode(digitToBasic(q,0))),bias=adapt(delta,handledCPCountPlusOne,handledCPCount==basicLength),delta=0,++handledCPCount}++delta,++n}return output.join("")}var freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule="object"==typeof module&&module&&!module.nodeType&&module,freeGlobal="object"==typeof global&&global;(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)&&(root=freeGlobal);var regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},floor=_Mathfloor,stringFromCharCode=_StringfromCharCode,punycode,key;if(punycode={version:"1.4.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:function(input){return mapDomain(input,function(string){return /[^\x20-\x7E]/.test(string)?"xn--"+encode(string):string})},toUnicode:function(input){return mapDomain(input,function(string){return /^xn--/.test(string)?decode(string.slice(4).toLowerCase()):string})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return punycode});else if(!(freeExports&&freeModule))root.punycode=punycode;else if(module.exports==freeExports)freeModule.exports=punycode;else for(key in punycode)punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key])})(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],64:[function(require,module){'use strict';function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=function(qs,sep,eq,options){sep=sep||"&",eq=eq||"=";var obj={};if("string"!=typeof qs||0===qs.length)return obj;qs=qs.split(sep);var maxKeys=1e3;options&&"number"==typeof options.maxKeys&&(maxKeys=options.maxKeys);var len=qs.length;0<maxKeys&&len>maxKeys&&(len=maxKeys);for(var i=0;i<len;++i){var x=qs[i].replace(/\+/g,"%20"),idx=x.indexOf(eq),kstr,vstr,k,v;0<=idx?(kstr=x.substr(0,idx),vstr=x.substr(idx+1)):(kstr=x,vstr=""),k=decodeURIComponent(kstr),v=decodeURIComponent(vstr),hasOwnProperty(obj,k)?isArray(obj[k])?obj[k].push(v):obj[k]=[obj[k],v]:obj[k]=v}return obj};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)}},{}],65:[function(require,module){'use strict';function map(xs,f){if(xs.map)return xs.map(f);for(var res=[],i=0;i<xs.length;i++)res.push(f(xs[i],i));return res}var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return"";}};module.exports=function(obj,sep,eq,name){return sep=sep||"&",eq=eq||"=",null===obj&&(obj=void 0),"object"==typeof obj?map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;return isArray(obj[k])?map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep):ks+encodeURIComponent(stringifyPrimitive(obj[k]))}).join(sep):name?encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj)):""};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)},objectKeys=Object.keys||function(obj){var res=[];for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&res.push(key);return res}},{}],66:[function(require,module,exports){'use strict';exports.decode=exports.parse=require("./decode"),exports.encode=exports.stringify=require("./encode")},{"./decode":64,"./encode":65}],67:[function(require,module){let promise;module.exports="function"==typeof queueMicrotask?queueMicrotask:cb=>(promise||(promise=Promise.resolve())).then(cb).catch(err=>setTimeout(()=>{throw err},0))},{}],68:[function(require,module){module.exports=function(list){var offset=0;return function(){if(offset===list.length)return null;var len=list.length-offset,i=0|Math.random()*len,el=list[offset+i],tmp=list[offset];return list[offset]=el,list[offset+i]=tmp,offset++,el}}},{}],69:[function(require,module){(function(process,global){'use strict';var Buffer=require("safe-buffer").Buffer,crypto=global.crypto||global.msCrypto;module.exports=crypto&&crypto.getRandomValues?function(size,cb){if(size>4294967295)throw new RangeError("requested too many random bytes");var bytes=Buffer.allocUnsafe(size);if(0<size)if(65536<size)for(var generated=0;generated<size;generated+=65536)crypto.getRandomValues(bytes.slice(generated,generated+65536));else crypto.getRandomValues(bytes);return"function"==typeof cb?process.nextTick(function(){cb(null,bytes)}):bytes}:function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{_process:61,"safe-buffer":91}],70:[function(require,module){const{Writable,PassThrough}=require("readable-stream");module.exports=class extends Writable{constructor(offset,opts={}){super(opts),this.destroyed=!1,this._queue=[],this._position=offset||0,this._cb=null,this._buffer=null,this._out=null}_write(chunk,encoding,cb){let drained=!0;for(;;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=chunk,void(this._cb=cb);this._buffer=null;var currRange=this._queue[0];const writeStart=_Mathmax(currRange.start-this._position,0),writeEnd=currRange.end-this._position;if(writeStart>=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}},{"readable-stream":85}],71:[function(require,module){'use strict';function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}function createErrorType(code,message,Base){function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return _inheritsLoose(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return i+""}),2<len?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}return"of ".concat(thing," ").concat(expected+"")}function startsWith(str,search,pos){return str.substr(!pos||0>pos?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}var codes={};createErrorType("ERR_INVALID_OPT_VALUE",function(name,value){return"The value \""+value+"\" is invalid for option \""+name+"\""},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function(name,expected,actual){var determiner;"string"==typeof expected&&startsWith(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be";var msg;if(endsWith(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=includes(name,".")?"property":"argument";msg="The \"".concat(name,"\" ").concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual),msg},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function(name){return"The "+name+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function(name){return"Cannot call "+name+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function(arg){return"Unknown encoding: "+arg},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.codes=codes},{}],72:[function(require,module){(function(process){'use strict';function Duplex(options){return this instanceof Duplex?void(Readable.call(this,options),Writable.call(this,options),this.allowHalfOpen=!0,options&&(!1===options.readable&&(this.readable=!1),!1===options.writable&&(this.writable=!1),!1===options.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",onend)))):new Duplex(options)}function onend(){this._writableState.ended||process.nextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0,method;v<keys.length;v++)method=keys[v],Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method]);Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Duplex.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Duplex.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(Duplex.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(value){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=value,this._writableState.destroyed=value)}})}).call(this,require("_process"))},{"./_stream_readable":74,"./_stream_writable":76,_process:61,inherits:39}],73:[function(require,module){'use strict';function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=require("./_stream_transform");require("inherits")(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":75,inherits:39}],74:[function(require,module){(function(process,global){'use strict';function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?Array.isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex),this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(!StringDecoder&&(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||require("./_stream_duplex"),!(this instanceof Readable))return new Readable(options);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var state=stream._readableState;if(null===chunk)state.reading=!1,onEofChunk(stream,state);else{var er;if(skipChunkCheck||(er=chunkInvalid(state,chunk)),er)errorOrDestroy(stream,er);else if(!(state.objectMode||chunk&&0<chunk.length))addToFront||(state.reading=!1,maybeReadMore(stream,state));else if("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront)state.endEmitted?errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT):addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF);else{if(state.destroyed)return!1;state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1)}}return!state.ended&&(state.length<state.highWaterMark||0===state.length)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(state.awaitDrain=0,stream.emit("data",chunk)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)),er}function computeNewHighWaterMark(n){return 1073741824<=n?n=1073741824:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0>=n||0===state.length&&state.ended?0:state.objectMode?1:n===n?(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0)):state.flowing&&state.length?state.buffer.head.data.length:state.length}function onEofChunk(stream,state){if(debug("onEofChunk"),!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,!state.emittedReadable&&(state.emittedReadable=!0,emitReadable_(stream)))}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),!state.destroyed&&(state.length||state.ended)&&(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length<state.highWaterMark||state.flowing&&0===state.length);){var len=state.length;if(debug("maybeReadMore read 0"),stream.read(0),len===state.length)break}state.readingMore=!1}function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function updateReadableListening(self){var state=self._readableState;state.readableListening=0<self.listenerCount("readable"),state.resumeScheduled&&!state.paused?state.flowing=!0:0<self.listenerCount("data")&&self.resume()}function nReadingNextTick(self){debug("readable nexttick read 0"),self.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,process.nextTick(resume_,stream,state))}function resume_(stream,state){debug("resume",state.reading),state.reading||stream.read(0),state.resumeScheduled=!1,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){if(0===state.length)return null;var ret;return state.objectMode?ret=state.buffer.shift():!n||n>=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++)if(xs[i]===x)return i;return-1}module.exports=Readable;var Duplex;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter,EElistenerCount=function(emitter,type){return emitter.listeners(type).length},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},debugUtil=require("util"),debug;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function(){};var BufferList=require("./internal/streams/buffer_list"),destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,StringDecoder,createReadableStreamAsyncIterator,from;require("inherits")(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy,kProxyEvents=["error","close","destroy","pause","resume"];Object.defineProperty(Readable.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(value){this._readableState&&(this._readableState.destroyed=value)}}),Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype.push=function(chunk,encoding){var state=this._readableState,skipChunkCheck;return state.objectMode?skipChunkCheck=!0:"string"==typeof chunk&&(encoding=encoding||state.defaultEncoding,encoding!==state.encoding&&(chunk=Buffer.from(chunk,encoding),encoding=""),skipChunkCheck=!0),readableAddChunk(this,chunk,encoding,!1,skipChunkCheck)},Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,!0,!1)},Readable.prototype.isPaused=function(){return!1===this._readableState.flowing},Readable.prototype.setEncoding=function(enc){StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder);var decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;for(var p=this._readableState.buffer.head,content="";null!==p;)content+=decoder.write(p.data),p=p.next;return this._readableState.buffer.clear(),""!==content&&this._readableState.buffer.push(content),this._readableState.length=content.length,this};Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&((0===state.highWaterMark?0<state.length:state.length>=state.highWaterMark)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n<state.highWaterMark)&&(doRead=!0,debug("length less than watermark",doRead)),state.ended||state.reading?(doRead=!1,debug("reading or ended",doRead)):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,!state.reading&&(n=howMuchToRead(nOrig,state)));var ret;return ret=0<n?fromList(n,state):null,null===ret?(state.needReadable=state.length<=state.highWaterMark,n=0):(state.length-=n,state.awaitDrain=0),0===state.length&&(!state.ended&&(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,state.awaitDrain&&(!dest._writableState||dest._writableState.needDrain)&&ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret),!1===ret&&((1===state.pipesCount&&state.pipes===dest||1<state.pipesCount&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&errorOrDestroy(dest,er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this,{hasUnpiped:!1});return this}var index=indexOf(state.pipes,dest);return-1===index?this:(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this,unpipeInfo),this)},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;return"data"===ev?(state.readableListening=0<this.listenerCount("readable"),!1!==state.flowing&&this.resume()):"readable"==ev&&!state.endEmitted&&!state.readableListening&&(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,debug("on readable",state.length,state.reading),state.length?emitReadable(this):!state.reading&&process.nextTick(nReadingNextTick,this)),res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);return"readable"===ev&&process.nextTick(updateReadableListening,this),res},Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);return("readable"===ev||void 0===ev)&&process.nextTick(updateReadableListening,this),res},Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!state.readableListening,resume(this,state)),state.paused=!1,this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)}),stream.on("data",function(chunk){if((debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),!(state.objectMode&&(null===chunk||void 0===chunk)))&&(state.objectMode||chunk&&chunk.length)){var ret=_this.push(chunk);ret||(paused=!0,stream.pause())}}),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n<kProxyEvents.length;n++)stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]));return this._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},this},"function"==typeof Symbol&&(Readable.prototype[Symbol.asyncIterator]=function(){return void 0===createReadableStreamAsyncIterator&&(createReadableStreamAsyncIterator=require("./internal/streams/async_iterator")),createReadableStreamAsyncIterator(this)}),Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(Readable.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(Readable.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(state){this._readableState&&(this._readableState.flowing=state)}}),Readable._fromList=fromList,Object.defineProperty(Readable.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(Readable.from=function(iterable,opts){return void 0===from&&(from=require("./internal/streams/from")),from(Readable,iterable,opts)})}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":71,"./_stream_duplex":72,"./internal/streams/async_iterator":77,"./internal/streams/buffer_list":78,"./internal/streams/destroy":79,"./internal/streams/from":81,"./internal/streams/state":83,"./internal/streams/stream":84,_process:61,buffer:26,events:33,inherits:39,"string_decoder/":106,util:21}],75:[function(require,module){'use strict';function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(null===cb)return this.emit("error",new ERR_MULTIPLE_CALLBACK);ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}function Transform(options){return this instanceof Transform?void(Duplex.call(this,options),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.on("prefinish",prefinish)):new Transform(options)}function prefinish(){var _this=this;"function"!=typeof this._flush||this._readableState.destroyed?done(this,null,null):this._flush(function(er,data){done(_this,er,data)})}function done(stream,er,data){if(er)return stream.emit("error",er);if(null!=data&&stream.push(data),stream._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if(stream._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return stream.push(null)}module.exports=Transform;var _require$codes=require("../errors").codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require("./_stream_duplex");require("inherits")(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(){var ts=this._transformState;null===ts.writechunk||ts.transforming?ts.needTransform=!0:(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform))},Transform.prototype._destroy=function(err,cb){Duplex.prototype._destroy.call(this,err,function(err2){cb(err2)})}},{"../errors":71,"./_stream_duplex":72,inherits:39}],76:[function(require,module){(function(process,global){'use strict';function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){onCorkedFinish(_this,state)}}function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||require("./_stream_duplex"),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){Duplex=Duplex||require("./_stream_duplex");var isDuplex=this instanceof Duplex;return isDuplex||realHasInstance.call(Writable,this)?void(this._writableState=new WritableState(options,this,isDuplex),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)):new Writable(options)}function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er),process.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var er;return null===chunk?er=new ERR_STREAM_NULL_VALUES:"string"!=typeof chunk&&!state.objectMode&&(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)),!er||(errorOrDestroy(stream,er),process.nextTick(cb,er),!1)}function decodeChunk(state,chunk,encoding){return state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null},last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,state.destroyed?state.onwrite(new ERR_STREAM_DESTROYED("write")):writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(process.nextTick(cb,er),process.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er)):(cb(er),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er),finishMaybe(stream,state))}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if("function"!=typeof cb)throw new ERR_MULTIPLE_CALLBACK;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?process.nextTick(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount,buffer=Array(l),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback,len=state.objectMode?1:chunk.length;if(doWrite(stream,state,!1,len,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--,err&&errorOrDestroy(stream,err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)})}function prefinish(stream,state){state.prefinished||state.finalCalled||("function"!=typeof stream._final||state.destroyed?(state.prefinished=!0,stream.emit("prefinish")):(state.pendingcb++,state.finalCalled=!0,process.nextTick(callFinal,stream,state)))}function finishMaybe(stream,state){var need=needFinish(state);if(need&&(prefinish(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"),state.autoDestroy))){var rState=stream._readableState;(!rState||rState.autoDestroy&&rState.endEmitted)&&stream.destroy()}return need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?process.nextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;for(corkReq.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}module.exports=Writable;var Duplex;Writable.WritableState=WritableState;var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},destroyImpl=require("./internal/streams/destroy"),_require=require("./internal/streams/state"),getHighWaterMark=_require.getHighWaterMark,_require$codes=require("../errors").codes,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING,errorOrDestroy=destroyImpl.errorOrDestroy;require("inherits")(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||!(this!==Writable)&&object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":!encoding&&(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ending?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,!state.writing&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest&&clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;return"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||endWritable(this,state,cb),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){cb(err)}}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":71,"./_stream_duplex":72,"./internal/streams/destroy":79,"./internal/streams/state":83,"./internal/streams/stream":84,_process:61,buffer:26,inherits:39,"util-deprecate":119}],77:[function(require,module){(function(process){'use strict';function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function createIterResult(value,done){return{value:value,done:done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(null!==resolve){var data=iter[kStream].read();null!==data&&(iter[kLastPromise]=null,iter[kLastResolve]=null,iter[kLastReject]=null,resolve(createIterResult(data,!1)))}}function onReadable(iter){process.nextTick(readAndResolve,iter)}function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then(function(){return iter[kEnded]?void resolve(createIterResult(void 0,!0)):void iter[kHandlePromise](resolve,reject)},reject)}}var finished=require("./end-of-stream"),kLastResolve=Symbol("lastResolve"),kLastReject=Symbol("lastReject"),kError=Symbol("error"),kEnded=Symbol("ended"),kLastPromise=Symbol("lastPromise"),kHandlePromise=Symbol("handlePromise"),kStream=Symbol("stream"),AsyncIteratorPrototype=Object.getPrototypeOf(function(){}),ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_Object$setPrototypeO={get stream(){return this[kStream]},next:function(){var _this=this,error=this[kError];if(null!==error)return Promise.reject(error);if(this[kEnded])return Promise.resolve(createIterResult(void 0,!0));if(this[kStream].destroyed)return new Promise(function(resolve,reject){process.nextTick(function(){_this[kError]?reject(_this[kError]):resolve(createIterResult(void 0,!0))})});var lastPromise=this[kLastPromise],promise;if(lastPromise)promise=new Promise(wrapForNext(lastPromise,this));else{var data=this[kStream].read();if(null!==data)return Promise.resolve(createIterResult(data,!1));promise=new Promise(this[kHandlePromise])}return this[kLastPromise]=promise,promise}},_defineProperty(_Object$setPrototypeO,Symbol.asyncIterator,function(){return this}),_defineProperty(_Object$setPrototypeO,"return",function(){var _this2=this;return new Promise(function(resolve,reject){_this2[kStream].destroy(null,function(err){return err?void reject(err):void resolve(createIterResult(void 0,!0))})})}),_Object$setPrototypeO),AsyncIteratorPrototype),_Object$setPrototypeO;module.exports=function(stream){var iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_Object$create={},_defineProperty(_Object$create,kStream,{value:stream,writable:!0}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:!0}),_defineProperty(_Object$create,kLastReject,{value:null,writable:!0}),_defineProperty(_Object$create,kError,{value:null,writable:!0}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:!0}),_defineProperty(_Object$create,kHandlePromise,{value:function(resolve,reject){var data=iterator[kStream].read();data?(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(data,!1))):(iterator[kLastResolve]=resolve,iterator[kLastReject]=reject)},writable:!0}),_Object$create)),_Object$create;return iterator[kLastPromise]=null,finished(stream,function(err){if(err&&"ERR_STREAM_PREMATURE_CLOSE"!==err.code){var reject=iterator[kLastReject];return null!==reject&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,reject(err)),void(iterator[kError]=err)}var resolve=iterator[kLastResolve];null!==resolve&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(void 0,!0))),iterator[kEnded]=!0}),stream.on("readable",onReadable.bind(null,iterator)),iterator}}).call(this,require("_process"))},{"./end-of-stream":80,_process:61}],78:[function(require,module){'use strict';function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable})),keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1,source;i<arguments.length;i++)source=null==arguments[i]?{}:arguments[i],i%2?ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))});return target}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0,descriptor;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}function copyBuffer(src,target,offset){Buffer.prototype.copy.call(src,target,offset)}var _require=require("buffer"),Buffer=_require.Buffer,_require2=require("util"),inspect=_require2.inspect,custom=inspect&&inspect.custom||"inspect";module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return _createClass(BufferList,[{key:"push",value:function(v){var entry={data:v,next:null};0<this.length?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length}},{key:"unshift",value:function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length}},{key:"shift",value:function(){if(0!==this.length){var ret=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,ret}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret}},{key:"concat",value:function(n){if(0===this.length)return Buffer.alloc(0);for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function(n,hasStrings){var ret;return n<this.head.data.length?(ret=this.head.data.slice(0,n),this.head.data=this.head.data.slice(n)):n===this.head.data.length?ret=this.shift():ret=hasStrings?this._getString(n):this._getBuffer(n),ret}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(n){var p=this.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,this.head=p.next?p.next:this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:!1}))}}]),BufferList}()},{buffer:26,util:21}],79:[function(require,module){(function(process){'use strict';function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}}}).call(this,require("_process"))},{_process:61}],80:[function(require,module){'use strict';function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}function noop(){}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function(err){callback.call(stream,err)},onclose=function(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;module.exports=eos},{"../../../errors":71}],81:[function(require,module){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],82:[function(require,module){'use strict';function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=!1;stream.on("close",function(){closed=!0}),eos===void 0&&(eos=require("./end-of-stream")),eos(stream,{readable:reading,writable:writing},function(err){return err?callback(err):void(closed=!0,callback())});var destroyed=!1;return function(err){if(!closed)return destroyed?void 0:(destroyed=!0,isRequest(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe")))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"==typeof streams[streams.length-1]?streams.pop():noop:noop}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,eos;module.exports=function(){for(var _len=arguments.length,streams=Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),2>streams.length)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map(function(stream,i){var reading=i<streams.length-1;return destroyer(stream,reading,0<i,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})}),error;return streams.reduce(pipe)}},{"../../../errors":71,"./end-of-stream":80}],83:[function(require,module){'use strict';function highWaterMarkFrom(options,isDuplex,duplexKey){return null==options.highWaterMark?isDuplex?options[duplexKey]:null:options.highWaterMark}var ERR_INVALID_OPT_VALUE=require("../../../errors").codes.ERR_INVALID_OPT_VALUE;module.exports={getHighWaterMark:function(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(null!=hwm){if(!(isFinite(hwm)&&_Mathfloor(hwm)===hwm)||0>hwm){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return _Mathfloor(hwm)}return state.objectMode?16:16384}}},{"../../../errors":71}],84:[function(require,module){module.exports=require("events").EventEmitter},{events:33}],85:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js"),exports.finished=require("./lib/internal/streams/end-of-stream.js"),exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":72,"./lib/_stream_passthrough.js":73,"./lib/_stream_readable.js":74,"./lib/_stream_transform.js":75,"./lib/_stream_writable.js":76,"./lib/internal/streams/end-of-stream.js":80,"./lib/internal/streams/pipeline.js":82}],86:[function(require,module,exports){function renderMedia(file,getElem,opts,cb){function checkBlobLength(){return!("number"==typeof file.length&&file.length>opts.maxBlobLength)||(debug("File length too large for Blob URL approach: %d (max: %d)",file.length,opts.maxBlobLength),fatalError(new Error("File length too large for Blob URL approach: "+file.length+" (max: "+opts.maxBlobLength+")")),!1)}function renderMediaElement(type){checkBlobLength()&&(elem=getElem(type),getBlobURL(file,function(err,url){return err?fatalError(err):void(elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),elem.src=url)}))}function onLoadStart(){elem.removeEventListener("loadstart",onLoadStart),opts.autoplay&&elem.play()}function onCanPlay(){elem.removeEventListener("canplay",onCanPlay),cb(null,elem)}function renderIframe(){getBlobURL(file,function(err,url){return err?fatalError(err):void(".pdf"===extname?(elem=getElem("object"),elem.setAttribute("typemustmatch",!0),elem.setAttribute("type","application/pdf"),elem.setAttribute("data",url)):(elem=getElem("iframe"),elem.sandbox="allow-forms allow-scripts",elem.src=url),cb(null,elem))})}function fatalError(err){err.message="Error rendering file \""+file.name+"\": "+err.message,debug(err.message),cb(err)}var extname=path.extname(file.name).toLowerCase(),currentTime=0,elem;0<=MEDIASOURCE_EXTS.indexOf(extname)?function(){function useVideostream(){debug("Use `videostream` package for "+file.name),prepareElem(),elem.addEventListener("error",fallbackToMediaSource),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),videostream(file,elem)}function useMediaSource(){debug("Use MediaSource API for "+file.name),prepareElem(),elem.addEventListener("error",fallbackToBlobURL),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay);var wrapper=new MediaElementWrapper(elem),writable=wrapper.createWriteStream(getCodec(file.name));file.createReadStream().pipe(writable),currentTime&&(elem.currentTime=currentTime)}function useBlobURL(){debug("Use Blob URL for "+file.name),prepareElem(),elem.addEventListener("error",fatalError),elem.addEventListener("loadstart",onLoadStart),elem.addEventListener("canplay",onCanPlay),getBlobURL(file,function(err,url){return err?fatalError(err):void(elem.src=url,currentTime&&(elem.currentTime=currentTime))})}function fallbackToMediaSource(err){debug("videostream error: fallback to MediaSource API: %o",err.message||err),elem.removeEventListener("error",fallbackToMediaSource),elem.removeEventListener("canplay",onCanPlay),useMediaSource()}function fallbackToBlobURL(err){debug("MediaSource API error: fallback to Blob URL: %o",err.message||err);checkBlobLength()&&(elem.removeEventListener("error",fallbackToBlobURL),elem.removeEventListener("canplay",onCanPlay),useBlobURL())}function prepareElem(){elem||(elem=getElem(tagName),elem.addEventListener("progress",function(){currentTime=elem.currentTime}))}var tagName=0<=MEDIASOURCE_VIDEO_EXTS.indexOf(extname)?"video":"audio";MediaSource?0<=VIDEOSTREAM_EXTS.indexOf(extname)?useVideostream():useMediaSource():useBlobURL()}():0<=VIDEO_EXTS.indexOf(extname)?renderMediaElement("video"):0<=AUDIO_EXTS.indexOf(extname)?renderMediaElement("audio"):0<=IMAGE_EXTS.indexOf(extname)?function(){elem=getElem("img"),getBlobURL(file,function(err,url){return err?fatalError(err):void(elem.src=url,elem.alt=file.name,cb(null,elem))})}():0<=IFRAME_EXTS.indexOf(extname)?renderIframe():function(){function done(){isAscii(str)?(debug("File extension \"%s\" appears ascii, so will render.",extname),renderIframe()):(debug("File extension \"%s\" appears non-ascii, will not render.",extname),cb(new Error("Unsupported file type \""+extname+"\": Cannot append to DOM")))}debug("Unknown file extension \"%s\" - will attempt to render into iframe",extname);var str="";file.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",function(chunk){str+=chunk}).on("end",done).on("error",cb)}()}function getBlobURL(file,cb){var extname=path.extname(file.name).toLowerCase();streamToBlobURL(file.createReadStream(),exports.mime[extname]).then(blobUrl=>cb(null,blobUrl),err=>cb(err))}function validateFile(file){if(null==file)throw new Error("file cannot be null or undefined");if("string"!=typeof file.name)throw new Error("missing or invalid file.name property");if("function"!=typeof file.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function getCodec(name){var extname=path.extname(name).toLowerCase();return{".m4a":"audio/mp4; codecs=\"mp4a.40.5\"",".m4b":"audio/mp4; codecs=\"mp4a.40.5\"",".m4p":"audio/mp4; codecs=\"mp4a.40.5\"",".m4v":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".mkv":"video/webm; codecs=\"avc1.640029, mp4a.40.5\"",".mp3":"audio/mpeg",".mp4":"video/mp4; codecs=\"avc1.640029, mp4a.40.5\"",".webm":"video/webm; codecs=\"vorbis, vp8\""}[extname]}function parseOpts(opts){null==opts.autoplay&&(opts.autoplay=!1),null==opts.muted&&(opts.muted=!1),null==opts.controls&&(opts.controls=!0),null==opts.maxBlobLength&&(opts.maxBlobLength=200000000)}function setMediaOpts(elem,opts){elem.autoplay=!!opts.autoplay,elem.muted=!!opts.muted,elem.controls=!!opts.controls}exports.render=function(file,elem,opts,cb){"function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=function(){}),validateFile(file),parseOpts(opts),"string"==typeof elem&&(elem=document.querySelector(elem)),renderMedia(file,function(tagName){if(elem.nodeName!==tagName.toUpperCase()){var extname=path.extname(file.name).toLowerCase();throw new Error("Cannot render \""+extname+"\" inside a \""+elem.nodeName.toLowerCase()+"\" element, expected \""+tagName+"\"")}return("video"===tagName||"audio"===tagName)&&setMediaOpts(elem,opts),elem},opts,cb)},exports.append=function(file,rootElem,opts,cb){function createMedia(tagName){var elem=createElem(tagName);return setMediaOpts(elem,opts),rootElem.appendChild(elem),elem}function createElem(tagName){var elem=document.createElement(tagName);return rootElem.appendChild(elem),elem}function done(err,elem){err&&elem&&elem.remove(),cb(err,elem)}if("function"==typeof opts&&(cb=opts,opts={}),opts||(opts={}),cb||(cb=function(){}),validateFile(file),parseOpts(opts),"string"==typeof rootElem&&(rootElem=document.querySelector(rootElem)),rootElem&&("VIDEO"===rootElem.nodeName||"AUDIO"===rootElem.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");renderMedia(file,function(tagName){return"video"===tagName||"audio"===tagName?createMedia(tagName):createElem(tagName)},opts,done)},exports.mime=require("./lib/mime.json");var debug=require("debug")("render-media"),isAscii=require("is-ascii"),MediaElementWrapper=require("mediasource"),path=require("path"),streamToBlobURL=require("stream-to-blob-url"),videostream=require("videostream"),VIDEOSTREAM_EXTS=[".m4a",".m4b",".m4p",".m4v",".mp4"],MEDIASOURCE_VIDEO_EXTS=[".m4v",".mkv",".mp4",".webm"],MEDIASOURCE_EXTS=[].concat(MEDIASOURCE_VIDEO_EXTS,[".m4a",".m4b",".m4p",".mp3"]),VIDEO_EXTS=[".mov",".ogv"],AUDIO_EXTS=[".aac",".oga",".ogg",".wav",".flac"],IMAGE_EXTS=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],IFRAME_EXTS=[".css",".html",".js",".md",".pdf",".txt"],MediaSource="undefined"!=typeof window&&window.MediaSource},{"./lib/mime.json":87,debug:30,"is-ascii":40,mediasource:45,path:59,"stream-to-blob-url":103,videostream:121}],87:[function(require,module){module.exports={".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},{}],88:[function(require,module){(function(process){module.exports=function(tasks,limit,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){if(results[i]=result,err&&(isErrored=!0),0==--pending||err)done(err);else if(!isErrored&&next<len){var key;keys?(key=keys[next],next+=1,tasks[key](function(err,result){each(key,err,result)})):(key=next,next+=1,tasks[key](function(err,result){each(key,err,result)}))}}if("number"!=typeof limit)throw new Error("second argument must be a Number");var isSync=!0,results,len,pending,keys,isErrored;Array.isArray(tasks)?(results=[],pending=len=tasks.length):(keys=Object.keys(tasks),results={},pending=len=keys.length);var next=limit;pending?keys?keys.some(function(key,i){if(tasks[key](function(err,result){each(key,err,result)}),i===limit-1)return!0}):tasks.some(function(task,i){if(task(function(err,result){each(i,err,result)}),i===limit-1)return!0}):done(null),isSync=!1}}).call(this,require("_process"))},{_process:61}],89:[function(require,module){(function(process){module.exports=function(tasks,cb){function done(err){function end(){cb&&cb(err,results),cb=null}isSync?process.nextTick(end):end()}function each(i,err,result){results[i]=result,(0==--pending||err)&&done(err)}var isSync=!0,results,pending,keys;Array.isArray(tasks)?(results=[],pending=tasks.length):(keys=Object.keys(tasks),results={},pending=keys.length),pending?keys?keys.forEach(function(key){tasks[key](function(err,result){each(key,err,result)})}):tasks.forEach(function(task,i){task(function(err,result){each(i,err,result)})}):done(null),isSync=!1}}).call(this,require("_process"))},{_process:61}],90:[function(require,module,exports){(function(root,factory){"object"==typeof exports&&"object"==typeof module?module.exports=factory():"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports?exports.Rusha=factory():root.Rusha=factory()})("undefined"==typeof self?this:self,function(){return function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module["default"]}:function(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=3)}([function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var RushaCore=__webpack_require__(5),_require=__webpack_require__(1),toHex=_require.toHex,ceilHeapSize=_require.ceilHeapSize,conv=__webpack_require__(6),padlen=function(len){for(len+=9;0<len%64;len+=1);return len},padZeroes=function(bin,len){var h8=new Uint8Array(bin.buffer),om=len%4,align=len-om;switch(om){case 0:h8[align+3]=0;case 1:h8[align+2]=0;case 2:h8[align+1]=0;case 3:h8[align+0]=0;}for(var i=(len>>2)+1;i<bin.length;i++)bin[i]=0},padData=function(bin,chunkLen,msgLen){bin[chunkLen>>2]|=128<<24-(chunkLen%4<<3),bin[(-16&(chunkLen>>2)+2)+14]=0|msgLen/536870912,bin[(-16&(chunkLen>>2)+2)+15]=msgLen<<3},getRawDigest=function(heap,padMaxChunkLen){var io=new Int32Array(heap,padMaxChunkLen+320,5),out=new Int32Array(5),arr=new DataView(out.buffer);return arr.setInt32(0,io[0],!1),arr.setInt32(4,io[1],!1),arr.setInt32(8,io[2],!1),arr.setInt32(12,io[3],!1),arr.setInt32(16,io[4],!1),out},Rusha=function(){function Rusha(chunkSize){if(_classCallCheck(this,Rusha),chunkSize=chunkSize||65536,0<chunkSize%64)throw new Error("Chunk size must be a multiple of 128 bit");this._offset=0,this._maxChunkLen=chunkSize,this._padMaxChunkLen=padlen(chunkSize),this._heap=new ArrayBuffer(ceilHeapSize(this._padMaxChunkLen+320+20)),this._h32=new Int32Array(this._heap),this._h8=new Int8Array(this._heap),this._core=new RushaCore({Int32Array:Int32Array},{},this._heap)}return Rusha.prototype._initState=function(heap,padMsgLen){this._offset=0;var io=new Int32Array(heap,padMsgLen+320,5);io[0]=1732584193,io[1]=-271733879,io[2]=-1732584194,io[3]=271733878,io[4]=-1009589776},Rusha.prototype._padChunk=function(chunkLen,msgLen){var padChunkLen=padlen(chunkLen),view=new Int32Array(this._heap,0,padChunkLen>>2);return padZeroes(view,chunkLen),padData(view,chunkLen,msgLen),padChunkLen},Rusha.prototype._write=function(data,chunkOffset,chunkLen,off){conv(data,this._h8,this._h32,chunkOffset,chunkLen,off||0)},Rusha.prototype._coreCall=function(data,chunkOffset,chunkLen,msgLen,finalize){var padChunkLen=chunkLen;this._write(data,chunkOffset,chunkLen),finalize&&(padChunkLen=this._padChunk(chunkLen,msgLen)),this._core.hash(padChunkLen,this._padMaxChunkLen)},Rusha.prototype.rawDigest=function(str){var msgLen=str.byteLength||str.length||str.size||0;this._initState(this._heap,this._padMaxChunkLen);var chunkOffset=0,chunkLen=this._maxChunkLen;for(chunkOffset=0;msgLen>chunkOffset+chunkLen;chunkOffset+=chunkLen)this._coreCall(str,chunkOffset,chunkLen,msgLen,!1);return this._coreCall(str,chunkOffset,msgLen-chunkOffset,msgLen,!0),getRawDigest(this._heap,this._padMaxChunkLen)},Rusha.prototype.digest=function(str){return toHex(this.rawDigest(str).buffer)},Rusha.prototype.digestFromString=function(str){return this.digest(str)},Rusha.prototype.digestFromBuffer=function(str){return this.digest(str)},Rusha.prototype.digestFromArrayBuffer=function(str){return this.digest(str)},Rusha.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},Rusha.prototype.append=function(chunk){var chunkOffset=0,chunkLen=chunk.byteLength||chunk.length||chunk.size||0,turnOffset=this._offset%this._maxChunkLen,inputLen=void 0;for(this._offset+=chunkLen;chunkOffset<chunkLen;)inputLen=_Mathmin(chunkLen-chunkOffset,this._maxChunkLen-turnOffset),this._write(chunk,chunkOffset,inputLen,turnOffset),turnOffset+=inputLen,chunkOffset+=inputLen,turnOffset===this._maxChunkLen&&(this._core.hash(this._maxChunkLen,this._padMaxChunkLen),turnOffset=0);return this},Rusha.prototype.getState=function(){var turnOffset=this._offset%this._maxChunkLen,heap=void 0;if(!turnOffset){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);heap=io.buffer.slice(io.byteOffset,io.byteOffset+io.byteLength)}else heap=this._heap.slice(0);return{offset:this._offset,heap:heap}},Rusha.prototype.setState=function(state){if(this._offset=state.offset,20===state.heap.byteLength){var io=new Int32Array(this._heap,this._padMaxChunkLen+320,5);io.set(new Int32Array(state.heap))}else this._h32.set(new Int32Array(state.heap));return this},Rusha.prototype.rawEnd=function(){var msgLen=this._offset,chunkLen=msgLen%this._maxChunkLen,padChunkLen=this._padChunk(chunkLen,msgLen);this._core.hash(padChunkLen,this._padMaxChunkLen);var result=getRawDigest(this._heap,this._padMaxChunkLen);return this._initState(this._heap,this._padMaxChunkLen),result},Rusha.prototype.end=function(){return toHex(this.rawEnd().buffer)},Rusha}();module.exports=Rusha,module.exports._core=RushaCore},function(module){for(var precomputedHex=Array(256),i=0;256>i;i++)precomputedHex[i]=(16>i?"0":"")+i.toString(16);module.exports.toHex=function(arrayBuffer){for(var binarray=new Uint8Array(arrayBuffer),res=Array(arrayBuffer.byteLength),_i=0;_i<res.length;_i++)res[_i]=precomputedHex[binarray[_i]];return res.join("")},module.exports.ceilHeapSize=function(v){var p=0;if(65536>=v)return 65536;if(16777216>v)for(p=1;p<v;p<<=1);else for(p=16777216;p<v;p+=16777216);return p},module.exports.isDedicatedWorkerScope=function(self){var isRunningInWorker="WorkerGlobalScope"in self&&self instanceof self.WorkerGlobalScope,isRunningInSharedWorker="SharedWorkerGlobalScope"in self&&self instanceof self.SharedWorkerGlobalScope,isRunningInServiceWorker="ServiceWorkerGlobalScope"in self&&self instanceof self.ServiceWorkerGlobalScope;return isRunningInWorker&&!isRunningInSharedWorker&&!isRunningInServiceWorker}},function(module,exports,__webpack_require__){module.exports=function(){var Rusha=__webpack_require__(0),hashData=function(hasher,data,cb){try{return cb(null,hasher.digest(data))}catch(e){return cb(e)}},hashFile=function(hasher,readTotal,blockSize,file,cb){var reader=new self.FileReader;reader.onloadend=function(){if(reader.error)return cb(reader.error);var buffer=reader.result;readTotal+=reader.result.byteLength;try{hasher.append(buffer)}catch(e){return void cb(e)}readTotal<file.size?hashFile(hasher,readTotal,blockSize,file,cb):cb(null,hasher.end())},reader.readAsArrayBuffer(file.slice(readTotal,readTotal+blockSize))},workerBehaviourEnabled=!0;return self.onmessage=function(event){if(workerBehaviourEnabled){var data=event.data.data,file=event.data.file,id=event.data.id;if("undefined"!=typeof id&&(file||data)){var blockSize=event.data.blockSize||4194304,hasher=new Rusha(blockSize);hasher.resetState();var done=function(err,hash){err?self.postMessage({id:id,error:err.name}):self.postMessage({id:id,hash:hash})};data&&hashData(hasher,data,done),file&&hashFile(hasher,0,blockSize,file,done)}}},function(){workerBehaviourEnabled=!1}}},function(module,exports,__webpack_require__){var work=__webpack_require__(4),Rusha=__webpack_require__(0),createHash=__webpack_require__(7),runWorker=__webpack_require__(2),_require=__webpack_require__(1),isDedicatedWorkerScope=_require.isDedicatedWorkerScope,isRunningInDedicatedWorker="undefined"!=typeof self&&isDedicatedWorkerScope(self);Rusha.disableWorkerBehaviour=isRunningInDedicatedWorker?runWorker():function(){},Rusha.createWorker=function(){var worker=work(2),terminate=worker.terminate;return worker.terminate=function(){URL.revokeObjectURL(worker.objectURL),terminate.call(worker)},worker},Rusha.createHash=createHash,module.exports=Rusha},function(module,exports,__webpack_require__){function webpackBootstrapFunc(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};__webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){__webpack_require__.o(exports,name)||Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.r=function(exports){Object.defineProperty(exports,"__esModule",{value:!0})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module["default"]}:function(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="/",__webpack_require__.oe=function(err){throw console.error(err),err};var f=__webpack_require__(__webpack_require__.s=ENTRY_MODULE);return f.default||f}function quoteRegExp(str){return(str+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function getModuleDependencies(sources,module,queueName){var retval={};retval[queueName]=[];var fnString=module.toString(),wrapperSignature=fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/);if(!wrapperSignature)return retval;for(var webpackRequireName=wrapperSignature[1],re=new RegExp("(\\\\n|\\W)"+quoteRegExp(webpackRequireName)+"\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g"),match;match=re.exec(fnString);)"dll-reference"!==match[3]&&retval[queueName].push(match[3]);for(re=new RegExp("\\("+quoteRegExp(webpackRequireName)+"\\(\"(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))\"\\)\\)\\((/\\*.*?\\*/)?s?.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");match=re.exec(fnString);)sources[match[2]]||(retval[queueName].push(match[1]),sources[match[2]]=__webpack_require__(match[1]).m),retval[match[2]]=retval[match[2]]||[],retval[match[2]].push(match[4]);return retval}function hasValuesInQueues(queues){var keys=Object.keys(queues);return keys.reduce(function(hasValues,key){return hasValues||0<queues[key].length},!1)}function getRequiredModules(sources,moduleId){for(var modulesQueue={main:[moduleId]},requiredModules={main:[]},seenModules={main:{}};hasValuesInQueues(modulesQueue);)for(var queues=Object.keys(modulesQueue),i=0;i<queues.length;i++){var queueName=queues[i],queue=modulesQueue[queueName],moduleToCheck=queue.pop();if(seenModules[queueName]=seenModules[queueName]||{},!seenModules[queueName][moduleToCheck]&&sources[queueName][moduleToCheck]){seenModules[queueName][moduleToCheck]=!0,requiredModules[queueName]=requiredModules[queueName]||[],requiredModules[queueName].push(moduleToCheck);for(var newModules=getModuleDependencies(sources,sources[queueName][moduleToCheck],queueName),newModulesKeys=Object.keys(newModules),j=0;j<newModulesKeys.length;j++)modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]]||[],modulesQueue[newModulesKeys[j]]=modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])}}return requiredModules}module.exports=function(moduleId,options){options=options||{};var sources={main:__webpack_require__.m},requiredModules=options.all?{main:Object.keys(sources)}:getRequiredModules(sources,moduleId),src="";Object.keys(requiredModules).filter(function(m){return"main"!==m}).forEach(function(module){for(var entryModule=0;requiredModules[module][entryModule];)entryModule++;requiredModules[module].push(entryModule),sources[module][entryModule]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",src=src+"var "+module+" = ("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(entryModule))+")({"+requiredModules[module].map(function(id){return""+JSON.stringify(id)+": "+sources[module][id].toString()}).join(",")+"});\n"}),src=src+"("+webpackBootstrapFunc.toString().replace("ENTRY_MODULE",JSON.stringify(moduleId))+")({"+requiredModules.main.map(function(id){return""+JSON.stringify(id)+": "+sources.main[id].toString()}).join(",")+"})(self);";var blob=new window.Blob([src],{type:"text/javascript"});if(options.bare)return blob;var URL=window.URL||window.webkitURL||window.mozURL||window.msURL,workerUrl=URL.createObjectURL(blob),worker=new window.Worker(workerUrl);return worker.objectURL=workerUrl,worker}},function(module){module.exports=function(stdlib$846,foreign$847,heap$848){'use asm';var H$849=new stdlib$846.Int32Array(heap$848);return{hash:function(k$851,x$852){k$851|=0,x$852|=0;var i$853=0,j$854=0,y0$855=0,z0$856=0,y1$857=0,z1$858=0,y2$859=0,z2$860=0,y3$861=0,z3$862=0,y4$863=0,z4$864=0,t0$865=0,t1$866=0;for(y0$855=0|H$849[x$852+320>>2],y1$857=0|H$849[x$852+324>>2],y2$859=0|H$849[x$852+328>>2],y3$861=0|H$849[x$852+332>>2],y4$863=0|H$849[x$852+336>>2],i$853=0;(0|i$853)<(0|k$851);i$853=0|i$853+64){for(z0$856=y0$855,z1$858=y1$857,z2$860=y2$859,z3$862=y3$861,z4$864=y4$863,j$854=0;64>(0|j$854);j$854=0|j$854+4)t1$866=0|H$849[i$853+j$854>>2],t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[k$851+j$854>>2]=t1$866;for(j$854=0|k$851+64;(0|j$854)<(0|k$851+80);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|~y1$857&y3$861))+(0|(0|t1$866+y4$863)+1518500249),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+80;(0|j$854)<(0|k$851+160);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)+1859775393),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+160;(0|j$854)<(0|k$851+240);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857&y2$859|y1$857&y3$861|y2$859&y3$861))+(0|(0|t1$866+y4$863)-1894007588),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;for(j$854=0|k$851+240;(0|j$854)<(0|k$851+320);j$854=0|j$854+4)t1$866=(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])<<1|(H$849[j$854-12>>2]^H$849[j$854-32>>2]^H$849[j$854-56>>2]^H$849[j$854-64>>2])>>>31,t0$865=0|(0|(y0$855<<5|y0$855>>>27)+(y1$857^y2$859^y3$861))+(0|(0|t1$866+y4$863)-899497514),y4$863=y3$861,y3$861=y2$859,y2$859=y1$857<<30|y1$857>>>2,y1$857=y0$855,y0$855=t0$865,H$849[j$854>>2]=t1$866;y0$855=0|y0$855+z0$856,y1$857=0|y1$857+z1$858,y2$859=0|y2$859+z2$860,y3$861=0|y3$861+z3$862,y4$863=0|y4$863+z4$864}H$849[x$852+320>>2]=y0$855,H$849[x$852+324>>2]=y1$857,H$849[x$852+328>>2]=y2$859,H$849[x$852+332>>2]=y3$861,H$849[x$852+336>>2]=y4$863}}}},function(module){var _this=this,reader=void 0;"undefined"!=typeof self&&"undefined"!=typeof self.FileReaderSync&&(reader=new self.FileReaderSync);var convStr=function(str,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=str.charCodeAt(start+3);case 1:H8[0|off+1-(om<<1)]=str.charCodeAt(start+2);case 2:H8[0|off+2-(om<<1)]=str.charCodeAt(start+1);case 3:H8[0|off+3-(om<<1)]=str.charCodeAt(start);}if(!(len<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[off+i>>2]=str.charCodeAt(start+i)<<24|str.charCodeAt(start+i+1)<<16|str.charCodeAt(start+i+2)<<8|str.charCodeAt(start+i+3);switch(lm){case 3:H8[0|off+j+1]=str.charCodeAt(start+j+2);case 2:H8[0|off+j+2]=str.charCodeAt(start+j+1);case 1:H8[0|off+j+3]=str.charCodeAt(start+j);}}},convBuf=function(buf,H8,H32,start,len,off){var om=off%4,lm=(len+om)%4,j=len-lm,i;switch(om){case 0:H8[off]=buf[start+3];case 1:H8[0|off+1-(om<<1)]=buf[start+2];case 2:H8[0|off+2-(om<<1)]=buf[start+1];case 3:H8[0|off+3-(om<<1)]=buf[start];}if(!(len<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>2]=buf[start+i]<<24|buf[start+i+1]<<16|buf[start+i+2]<<8|buf[start+i+3];switch(lm){case 3:H8[0|off+j+1]=buf[start+j+2];case 2:H8[0|off+j+2]=buf[start+j+1];case 1:H8[0|off+j+3]=buf[start+j];}}},convBlob=function(blob,H8,H32,start,len,off){var i=void 0,om=off%4,lm=(len+om)%4,j=len-lm,buf=new Uint8Array(reader.readAsArrayBuffer(blob.slice(start,start+len)));switch(om){case 0:H8[off]=buf[3];case 1:H8[0|off+1-(om<<1)]=buf[2];case 2:H8[0|off+2-(om<<1)]=buf[1];case 3:H8[0|off+3-(om<<1)]=buf[0];}if(!(len<lm+(4-om))){for(i=4-om;i<j;i=0|i+4)H32[0|off+i>>2]=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];switch(lm){case 3:H8[0|off+j+1]=buf[j+2];case 2:H8[0|off+j+2]=buf[j+1];case 1:H8[0|off+j+3]=buf[j];}}};module.exports=function(data,H8,H32,start,len,off){if("string"==typeof data)return convStr(data,H8,H32,start,len,off);if(data instanceof Array)return convBuf(data,H8,H32,start,len,off);if(_this&&_this.Buffer&&_this.Buffer.isBuffer(data))return convBuf(data,H8,H32,start,len,off);if(data instanceof ArrayBuffer)return convBuf(new Uint8Array(data),H8,H32,start,len,off);if(data.buffer instanceof ArrayBuffer)return convBuf(new Uint8Array(data.buffer,data.byteOffset,data.byteLength),H8,H32,start,len,off);if(data instanceof Blob)return convBlob(data,H8,H32,start,len,off);throw new Error("Unsupported data type.")}},function(module,exports,__webpack_require__){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var Rusha=__webpack_require__(0),_require=__webpack_require__(1),toHex=_require.toHex,Hash=function(){function Hash(){_classCallCheck(this,Hash),this._rusha=new Rusha,this._rusha.resetState()}return Hash.prototype.update=function(data){return this._rusha.append(data),this},Hash.prototype.digest=function digest(encoding){var digest=this._rusha.rawEnd().buffer;if(!encoding)return digest;if("hex"===encoding)return toHex(digest);throw new Error("unsupported digest encoding")},Hash}();module.exports=function(){return new Hash}}])})},{}],91:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0===fill?buf.fill(0):"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:26}],92:[function(require,module){(function(Buffer){module.exports=function(stream,cb){var chunks=[];stream.on("data",function(chunk){chunks.push(chunk)}),stream.once("end",function(){cb&&cb(null,Buffer.concat(chunks)),cb=null}),stream.once("error",function(err){cb&&cb(err),cb=null})}}).call(this,require("buffer").Buffer)},{buffer:26}],93:[function(require,module){(function(Buffer){function simpleGet(opts,cb){if(opts=Object.assign({maxRedirects:10},"string"==typeof opts?{url:opts}:opts),cb=once(cb),opts.url){const{hostname,port,protocol,auth,path}=url.parse(opts.url);delete opts.url,hostname||port||protocol||auth?Object.assign(opts,{hostname,port,protocol,auth,path}):opts.path=path}const headers={"accept-encoding":"gzip, deflate"};opts.headers&&Object.keys(opts.headers).forEach(k=>headers[k.toLowerCase()]=opts.headers[k]),opts.headers=headers;let body;opts.body?body=opts.json&&!isStream(opts.body)?JSON.stringify(opts.body):opts.body:opts.form&&(body="string"==typeof opts.form?opts.form:querystring.stringify(opts.form),opts.headers["content-type"]="application/x-www-form-urlencoded"),body&&(!opts.method&&(opts.method="POST"),!isStream(body)&&(opts.headers["content-length"]=Buffer.byteLength(body)),opts.json&&!opts.form&&(opts.headers["content-type"]="application/json")),delete opts.body,delete opts.form,opts.json&&(opts.headers.accept="application/json"),opts.method&&(opts.method=opts.method.toUpperCase());const protocol="https:"===opts.protocol?https:http,req=protocol.request(opts,res=>{if(!1!==opts.followRedirects&&300<=res.statusCode&&400>res.statusCode&&res.headers.location)return opts.url=res.headers.location,delete opts.headers.host,res.resume(),"POST"===opts.method&&[301,302].includes(res.statusCode)&&(opts.method="GET",delete opts.headers["content-length"],delete opts.headers["content-type"]),0==opts.maxRedirects--?cb(new Error("too many redirects")):simpleGet(opts,cb);const tryUnzip="function"==typeof decompressResponse&&"HEAD"!==opts.method;cb(null,tryUnzip?decompressResponse(res):res)});return req.on("timeout",()=>{req.abort(),cb(new Error("Request timed out"))}),req.on("error",cb),isStream(body)?body.on("error",cb).pipe(req):req.end(body),req}module.exports=simpleGet;const concat=require("simple-concat"),decompressResponse=require("decompress-response"),http=require("http"),https=require("https"),once=require("once"),querystring=require("querystring"),url=require("url"),isStream=o=>null!==o&&"object"==typeof o&&"function"==typeof o.pipe;simpleGet.concat=(opts,cb)=>simpleGet(opts,(err,res)=>err?cb(err):void concat(res,(err,data)=>{if(err)return cb(err);if(opts.json)try{data=JSON.parse(data.toString())}catch(err){return cb(err,res,data)}cb(null,res,data)})),["get","post","put","patch","head","delete"].forEach(method=>{simpleGet[method]=(opts,cb)=>("string"==typeof opts&&(opts={url:opts}),simpleGet(Object.assign({method:method.toUpperCase()},opts),cb))})}).call(this,require("buffer").Buffer)},{buffer:26,"decompress-response":21,http:99,https:36,once:56,querystring:66,"simple-concat":92,url:116}],94:[function(require,module){(function(Buffer){function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function makeError(message,code){var err=new Error(message);return err.code=code,err}function warn(message){console.warn(message)}var debug=require("debug")("simple-peer"),getBrowserRTC=require("get-browser-rtc"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),MAX_BUFFERED_AMOUNT=65536;class Peer extends stream.Duplex{constructor(opts){if(opts=Object.assign({allowHalfOpen:!1},opts),super(opts),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",opts),this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null,this.initiator=opts.initiator||!1,this.channelConfig=opts.channelConfig||Peer.channelConfig,this.config=Object.assign({},Peer.config,opts.config),this.offerOptions=opts.offerOptions||{},this.answerOptions=opts.answerOptions||{},this.sdpTransform=opts.sdpTransform||(sdp=>sdp),this.streams=opts.streams||(opts.stream?[opts.stream]:[]),this.trickle=void 0===opts.trickle||opts.trickle,this.allowHalfTrickle=void 0!==opts.allowHalfTrickle&&opts.allowHalfTrickle,this.iceCompleteTimeout=opts.iceCompleteTimeout||5000,this.destroyed=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=opts.wrtc&&"object"==typeof opts.wrtc?opts.wrtc:getBrowserRTC(),!this._wrtc)if("undefined"==typeof window)throw makeError("No WebRTC support: Specify `opts.wrtc` option in this environment","ERR_WEBRTC_SUPPORT");else throw makeError("No WebRTC support: Not a supported browser","ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!this.initiator,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._firstStable=!0,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){return void queueMicrotask(()=>this.destroy(makeError(err,"ERR_PC_CONSTRUCTOR")))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=event=>{this._onIceCandidate(event)},this.initiator?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=event=>{this._setupData(event)},this.streams&&this.streams.forEach(stream=>{this.addStream(stream)}),this._pc.ontrack=event=>{this._onTrack(event)},this.initiator&&this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(this.destroyed)throw makeError("cannot signal after peer is destroyed","ERR_SIGNALING");if("string"==typeof data)try{data=JSON.parse(data)}catch(err){data={}}this._debug("signal()"),data.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),data.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)),data.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(data.candidate):this._pendingCandidates.push(data.candidate)),data.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(candidate=>{this._addIceCandidate(candidate)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(err=>{this.destroy(makeError(err,"ERR_SET_REMOTE_DESCRIPTION"))}),data.sdp||data.candidate||data.renegotiate||data.transceiverRequest||this.destroy(makeError("signal() called with invalid signal data","ERR_SIGNALING"))}_addIceCandidate(candidate){var iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch(err=>{!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")?warn("Ignoring unsupported ICE candidate."):this.destroy(makeError(err,"ERR_ADD_ICE_CANDIDATE"))})}send(chunk){this._channel.send(chunk)}addTransceiver(kind,init){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(kind,init),this._needsNegotiation()}catch(err){this.destroy(makeError(err,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{transceiverRequest:{kind,init}})}addStream(stream){this._debug("addStream()"),stream.getTracks().forEach(track=>{this.addTrack(track,stream)})}addTrack(track,stream){this._debug("addTrack()");var submap=this._senderMap.get(track)||new Map,sender=submap.get(stream);if(!sender)sender=this._pc.addTrack(track,stream),submap.set(stream,sender),this._senderMap.set(track,submap),this._needsNegotiation();else if(sender.removed)throw makeError("Track has been removed. You should enable/disable tracks that you want to re-add.","ERR_SENDER_REMOVED");else throw makeError("Track has already been added to that stream.","ERR_SENDER_ALREADY_ADDED")}replaceTrack(oldTrack,newTrack,stream){this._debug("replaceTrack()");var submap=this._senderMap.get(oldTrack),sender=submap?submap.get(stream):null;if(!sender)throw makeError("Cannot replace track that was never added.","ERR_TRACK_NOT_ADDED");newTrack&&this._senderMap.set(newTrack,submap),null==sender.replaceTrack?this.destroy(makeError("replaceTrack is not supported in this browser","ERR_UNSUPPORTED_REPLACETRACK")):sender.replaceTrack(newTrack)}removeTrack(track,stream){this._debug("removeSender()");var submap=this._senderMap.get(track),sender=submap?submap.get(stream):null;if(!sender)throw makeError("Cannot remove track that was never added.","ERR_TRACK_NOT_ADDED");try{sender.removed=!0,this._pc.removeTrack(sender)}catch(err){"NS_ERROR_UNEXPECTED"===err.name?this._sendersAwaitingStable.push(sender):this.destroy(makeError(err,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(stream){this._debug("removeSenders()"),stream.getTracks().forEach(track=>{this.removeTrack(track,stream)})}_needsNegotiation(){this._debug("_needsNegotiation");this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask(()=>{this._batchedNegotiation=!1,this._debug("starting batched negotiation"),this.negotiate()}))}negotiate(){this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):!this._isNegotiating&&(this._debug("requesting negotiation from initiator"),this.emit("signal",{renegotiate:!0})),this._isNegotiating=!0}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.destroyed=!0,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,err&&this.emit("error",err),this.emit("close"),cb()}}_setupData(event){if(!event.channel)return this.destroy(makeError("Data channel event is missing `channel` property","ERR_DATA_CHANNEL"));this._channel=event.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT),this.channelName=this._channel.label,this._channel.onmessage=event=>{this._onChannelMessage(event)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=err=>{this.destroy(makeError(err,"ERR_DATA_CHANNEL"))};var isClosing=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(isClosing&&this._onChannelClose(),isClosing=!0):isClosing=!1},5000)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(makeError("cannot write after peer is destroyed","ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(makeError(err,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?destroySoon():this.once("connect",destroySoon)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(offer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(offer.sdp=filterTrickle(offer.sdp)),offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(!this.destroyed){var signal=this._pc.localDescription||offer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp})}};this._pc.setLocalDescription(offer).then(()=>{this._debug("createOffer success");this.destroyed||(this.trickle||this._iceComplete?sendOffer():this.once("_iceComplete",sendOffer))}).catch(err=>{this.destroy(makeError(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(makeError(err,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(transceiver=>{transceiver.mid||!transceiver.sender.track||transceiver.requested||(transceiver.requested=!0,this.addTransceiver(transceiver.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(answer=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(answer.sdp=filterTrickle(answer.sdp)),answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(!this.destroyed){var signal=this._pc.localDescription||answer;this._debug("signal"),this.emit("signal",{type:signal.type,sdp:signal.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(answer).then(()=>{this.destroyed||(this.trickle||this._iceComplete?sendAnswer():this.once("_iceComplete",sendAnswer))}).catch(err=>{this.destroy(makeError(err,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(err=>{this.destroy(makeError(err,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(makeError("Connection failed.","ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(!this.destroyed){var iceConnectionState=this._pc.iceConnectionState,iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState),this.emit("iceStateChange",iceConnectionState,iceGatheringState),("connected"===iceConnectionState||"completed"===iceConnectionState)&&(this._pcReady=!0,this._maybeReady()),"failed"===iceConnectionState&&this.destroy(makeError("Ice connection failed.","ERR_ICE_CONNECTION_FAILURE")),"closed"===iceConnectionState&&this.destroy(makeError("Ice connection closed.","ERR_ICE_CONNECTION_CLOSED"))}}getStats(cb){const flattenValues=report=>("[object Array]"===Object.prototype.toString.call(report.values)&&report.values.forEach(value=>{Object.assign(report,value)}),report);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(res=>{var reports=[];res.forEach(report=>{reports.push(flattenValues(report))}),cb(null,reports)},err=>cb(err)):0<this._pc.getStats.length?this._pc.getStats(res=>{if(!this.destroyed){var reports=[];res.result().forEach(result=>{var report={};result.names().forEach(name=>{report[name]=result.stat(name)}),report.id=result.id,report.type=result.type,report.timestamp=result.timestamp,reports.push(flattenValues(report))}),cb(null,reports)}},err=>cb(err)):cb(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const findCandidatePair=()=>{this.destroyed||this.getStats((err,items)=>{if(this.destroyed)return;err&&(items=[]);var remoteCandidates={},localCandidates={},candidatePairs={},foundSelectedCandidatePair=!1;items.forEach(item=>{("remotecandidate"===item.type||"remote-candidate"===item.type)&&(remoteCandidates[item.id]=item),("localcandidate"===item.type||"local-candidate"===item.type)&&(localCandidates[item.id]=item),("candidatepair"===item.type||"candidate-pair"===item.type)&&(candidatePairs[item.id]=item)});const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=!0;var local=localCandidates[selectedCandidatePair.localCandidateId];local&&(local.ip||local.address)?(this.localAddress=local.ip||local.address,this.localPort=+local.port):local&&local.ipAddress?(this.localAddress=local.ipAddress,this.localPort=+local.portNumber):"string"==typeof selectedCandidatePair.googLocalAddress&&(local=selectedCandidatePair.googLocalAddress.split(":"),this.localAddress=local[0],this.localPort=+local[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");var remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];remote&&(remote.ip||remote.address)?(this.remoteAddress=remote.ip||remote.address,this.remotePort=+remote.port):remote&&remote.ipAddress?(this.remoteAddress=remote.ipAddress,this.remotePort=+remote.portNumber):"string"==typeof selectedCandidatePair.googRemoteAddress&&(remote=selectedCandidatePair.googRemoteAddress.split(":"),this.remoteAddress=remote[0],this.remotePort=+remote[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(items.forEach(item=>{"transport"===item.type&&item.selectedCandidatePairId&&setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]),("googCandidatePair"===item.type&&"true"===item.googActiveConnection||("candidatepair"===item.type||"candidate-pair"===item.type)&&item.selected)&&setSelectedCandidatePair(item)}),!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length))return void setTimeout(findCandidatePair,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(makeError(err,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug("sent chunk from \"write before connect\"");var cb=this._cb;this._cb=null,cb(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};findCandidatePair()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&!this._firstStable&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(sender=>{this._pc.removeTrack(sender),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation&&(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()),this._debug("negotiate"),this.emit("negotiate")),this._firstStable=!1,this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(event){this.destroyed||(event.candidate&&this.trickle?this.emit("signal",{candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}}):!event.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),event.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(event){if(!this.destroyed){var data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);var cb=this._cb;this._cb=null,cb(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(event){this.destroyed||event.streams.forEach(eventStream=>{this._debug("on track"),this.emit("track",event.track,eventStream),this._remoteTracks.push({track:event.track,stream:eventStream});this._remoteStreams.some(remoteStream=>remoteStream.id===eventStream.id)||(this._remoteStreams.push(eventStream),queueMicrotask(()=>{this.emit("stream",eventStream)}))})}_debug(){var args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478?transport=udp"}],sdpSemantics:"unified-plan"},Peer.channelConfig={},module.exports=Peer}).call(this,require("buffer").Buffer)},{buffer:26,debug:30,"get-browser-rtc":35,"queue-microtask":67,randombytes:69,"readable-stream":85}],95:[function(require,module){function sha1sync(buf){return rusha.digest(buf)}function sha1(buf,cb){return subtle?void("string"==typeof buf&&(buf=uint8array(buf)),subtle.digest({name:"sha-1"},buf).then(function(result){cb(hex(new Uint8Array(result)))},function(){cb(sha1sync(buf))})):void("undefined"==typeof window?queueMicrotask(()=>cb(sha1sync(buf))):rushaWorkerSha1(buf,function(err,hash){return err?void cb(sha1sync(buf)):void cb(hash)}))}function uint8array(s){for(var l=s.length,array=new Uint8Array(l),i=0;i<l;i++)array[i]=s.charCodeAt(i);return array}function hex(buf){for(var l=buf.length,chars=[],i=0,bite;i<l;i++)bite=buf[i],chars.push((bite>>>4).toString(16)),chars.push((15&bite).toString(16));return chars.join("")}var Rusha=require("rusha"),rushaWorkerSha1=require("./rusha-worker-sha1"),rusha=new Rusha,scope="undefined"==typeof window?self:window,crypto=scope.crypto||scope.msCrypto||{},subtle=crypto.subtle||crypto.webkitSubtle;try{subtle.digest({name:"sha-1"},new Uint8Array).catch(function(){subtle=!1})}catch(err){subtle=!1}module.exports=sha1,module.exports.sync=sha1sync},{"./rusha-worker-sha1":96,rusha:90}],96:[function(require,module){function init(){worker=Rusha.createWorker(),nextTaskId=1,cbs={},worker.onmessage=function(e){var taskId=e.data.id,cb=cbs[taskId];delete cbs[taskId],null==e.data.error?cb(null,e.data.hash):cb(new Error("Rusha worker error: "+e.data.error))}}function sha1(buf,cb){worker||init(),cbs[nextTaskId]=cb,worker.postMessage({id:nextTaskId,data:buf}),nextTaskId+=1}var Rusha=require("rusha"),worker,nextTaskId,cbs;module.exports=sha1},{rusha:90}],97:[function(require,module){(function(Buffer){const debug=require("debug")("simple-websocket"),randombytes=require("randombytes"),stream=require("readable-stream"),queueMicrotask=require("queue-microtask"),ws=require("ws"),_WebSocket="function"==typeof ws?ws:WebSocket,MAX_BUFFERED_AMOUNT=65536;class Socket extends stream.Duplex{constructor(opts={}){if("string"==typeof opts&&(opts={url:opts}),opts=Object.assign({allowHalfOpen:!1},opts),super(opts),null==opts.url&&null==opts.socket)throw new Error("Missing required `url` or `socket` option");if(null!=opts.url&&null!=opts.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new websocket: %o",opts),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,opts.socket)this.url=opts.socket.url,this._ws=opts.socket,this.connected=opts.socket.readyState===_WebSocket.OPEN;else{this.url=opts.url;try{this._ws="function"==typeof ws?new _WebSocket(opts.url,opts):new _WebSocket(opts.url)}catch(err){return void queueMicrotask(()=>this.destroy(err))}}this._ws.binaryType="arraybuffer",this._ws.onopen=()=>{this._onOpen()},this._ws.onmessage=event=>{this._onMessage(event)},this._ws.onclose=()=>{this._onClose()},this._ws.onerror=()=>{this.destroy(new Error("connection error to "+this.url))},this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}send(chunk){this._ws.send(chunk)}destroy(err){this._destroy(err,()=>{})}_destroy(err,cb){if(!this.destroyed){if(this._debug("destroy (error: %s)",err&&(err.message||err)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const ws=this._ws,onClose=()=>{ws.onclose=null};if(ws.readyState===_WebSocket.CLOSED)onClose();else try{ws.onclose=onClose,ws.close()}catch(err){onClose()}ws.onopen=null,ws.onmessage=null,ws.onerror=()=>{}}if(this._ws=null,err){if("undefined"!=typeof DOMException&&err instanceof DOMException){const code=err.code;err=new Error(err.message),err.code=code}this.emit("error",err)}this.emit("close"),cb()}}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(chunk)}catch(err){return this.destroy(err)}"function"!=typeof ws&&this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=cb):cb(null)}else this._debug("write before connect"),this._chunk=chunk,this._cb=cb}_onFinish(){if(!this.destroyed){const destroySoon=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?destroySoon():this.once("connect",destroySoon)}}_onMessage(event){if(this.destroyed)return;let data=event.data;data instanceof ArrayBuffer&&(data=Buffer.from(data)),this.push(data)}_onOpen(){if(!(this.connected||this.destroyed)){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(err)}this._chunk=null,this._debug("sent chunk from \"write before connect\"");const cb=this._cb;this._cb=null,cb(null)}"function"!=typeof ws&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(this._cb&&this._ws&&!(this._ws.bufferedAmount>MAX_BUFFERED_AMOUNT)){this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const cb=this._cb;this._cb=null,cb(null)}}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0],debug.apply(null,args)}}Socket.WEBSOCKET_SUPPORT=!!_WebSocket,module.exports=Socket}).call(this,require("buffer").Buffer)},{buffer:26,debug:30,"queue-microtask":67,randombytes:69,"readable-stream":85,ws:21}],98:[function(require,module){var tick=1,maxTick=65535,resolution=4,inc=function(){tick=tick+1&maxTick},timer;module.exports=function(seconds){timer||(timer=setInterval(inc,0|1e3/resolution),timer.unref&&timer.unref());var size=resolution*(seconds||5),buffer=[0],pointer=1,last=tick-1&maxTick;return function(delta){var dist=tick-last&maxTick;for(dist>size&&(dist=size),last=tick;dist--;)pointer===size&&(pointer=0),buffer[pointer]=buffer[0===pointer?size-1:pointer-1],pointer++;delta&&(buffer[pointer-1]+=delta);var top=buffer[pointer-1],btm=buffer.length<size?0:buffer[pointer===size?0:pointer];return buffer.length<resolution?top:(top-btm)*resolution/buffer.length}}},{}],99:[function(require,module,exports){(function(global){var ClientRequest=require("./lib/request"),response=require("./lib/response"),extend=require("xtend"),statusCodes=require("builtin-status-codes"),url=require("url"),http=exports;http.request=function(opts,cb){opts="string"==typeof opts?url.parse(opts):extend(opts);var defaultProtocol=-1===global.location.protocol.search(/^https?:$/)?"http:":"",protocol=opts.protocol||defaultProtocol,host=opts.hostname||opts.host,port=opts.port,path=opts.path||"/";host&&-1!==host.indexOf(":")&&(host="["+host+"]"),opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path,opts.method=(opts.method||"GET").toUpperCase(),opts.headers=opts.headers||{};var req=new ClientRequest(opts);return cb&&req.on("response",cb),req},http.get=function(opts,cb){var req=http.request(opts,cb);return req.end(),req},http.ClientRequest=ClientRequest,http.IncomingMessage=response.IncomingMessage,http.Agent=function(){},http.Agent.defaultMaxSockets=4,http.globalAgent=new http.Agent,http.STATUS_CODES=statusCodes,http.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"./lib/request":101,"./lib/response":102,"builtin-status-codes":27,url:116,xtend:123}],100:[function(require,module,exports){(function(global){function getXHR(){if(xhr!==void 0)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else xhr=null;return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return!1;try{return xhr.responseType=type,xhr.responseType===type}catch(e){}return!1}function isFunction(value){return"function"==typeof value}exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream),exports.writableStream=isFunction(global.WritableStream),exports.abortController=isFunction(global.AbortController);var xhr;exports.arraybuffer=exports.fetch||checkTypeSupport("arraybuffer"),exports.msstream=!exports.fetch&&checkTypeSupport("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&checkTypeSupport("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!getXHR()&&isFunction(getXHR().overrideMimeType),xhr=null}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],101:[function(require,module){(function(process,global,Buffer){function decideMode(preferBinary,useFetch){return capability.fetch&&useFetch?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&preferBinary?"arraybuffer":"text"}function statusValid(xhr){try{var status=xhr.status;return null!==status&&0!==status}catch(e){return!1}}var capability=require("./capability"),inherits=require("inherits"),response=require("./response"),stream=require("readable-stream"),IncomingMessage=response.IncomingMessage,rStates=response.readyStates,ClientRequest=module.exports=function(opts){var self=this;stream.Writable.call(self),self._opts=opts,self._body=[],self._headers={},opts.auth&&self.setHeader("Authorization","Basic "+Buffer.from(opts.auth).toString("base64")),Object.keys(opts.headers).forEach(function(name){self.setHeader(name,opts.headers[name])});var useFetch=!0,preferBinary;if("disable-fetch"===opts.mode||"requestTimeout"in opts&&!capability.abortController)useFetch=!1,preferBinary=!0;else if("prefer-streaming"===opts.mode)preferBinary=!1;else if("allow-wrong-content-type"===opts.mode)preferBinary=!capability.overrideMimeType;else if(!opts.mode||"default"===opts.mode||"prefer-fast"===opts.mode)preferBinary=!0;else throw new Error("Invalid value for opts.mode");self._mode=decideMode(preferBinary,useFetch),self._fetchTimer=null,self.on("finish",function(){self._onFinish()})};inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(name,value){var self=this,lowerName=name.toLowerCase();-1!==unsafeHeaders.indexOf(lowerName)||(self._headers[lowerName]={name:name,value:value})},ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];return header?header.value:null},ClientRequest.prototype.removeHeader=function(name){var self=this;delete self._headers[name.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var self=this;if(!self._destroyed){var opts=self._opts,headersObj=self._headers,body=null;"GET"!==opts.method&&"HEAD"!==opts.method&&(body=new Blob(self._body,{type:(headersObj["content-type"]||{}).value||""}));var headersList=[];if(Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name,value=headersObj[keyName].value;Array.isArray(value)?value.forEach(function(v){headersList.push([name,v])}):headersList.push([name,value])}),"fetch"===self._mode){var signal=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal,self._fetchAbortController=controller,"requestTimeout"in opts&&0!==opts.requestTimeout&&(self._fetchTimer=global.setTimeout(function(){self.emit("requestTimeout"),self._fetchAbortController&&self._fetchAbortController.abort()},opts.requestTimeout))}global.fetch(self._opts.url,{method:self._opts.method,headers:headersList,body:body||void 0,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self._fetchResponse=response,self._connect()},function(reason){global.clearTimeout(self._fetchTimer),self._destroyed||self.emit("error",reason)})}else{var xhr=self._xhr=new global.XMLHttpRequest;try{xhr.open(self._opts.method,self._opts.url,!0)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}"responseType"in xhr&&(xhr.responseType=self._mode),"withCredentials"in xhr&&(xhr.withCredentials=!!opts.withCredentials),"text"===self._mode&&"overrideMimeType"in xhr&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in opts&&(xhr.timeout=opts.requestTimeout,xhr.ontimeout=function(){self.emit("requestTimeout")}),headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])}),self._response=null,xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress();}},"moz-chunked-arraybuffer"===self._mode&&(xhr.onprogress=function(){self._onXHRProgress()}),xhr.onerror=function(){self._destroyed||self.emit("error",new Error("XHR error"))};try{xhr.send(body)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}}}},ClientRequest.prototype._onXHRProgress=function(){var self=this;!statusValid(self._xhr)||self._destroyed||(!self._response&&self._connect(),self._response._onXHRProgress())},ClientRequest.prototype._connect=function(){var self=this;self._destroyed||(self._response=new IncomingMessage(self._xhr,self._fetchResponse,self._mode,self._fetchTimer),self._response.on("error",function(err){self.emit("error",err)}),self.emit("response",self._response))},ClientRequest.prototype._write=function(chunk,encoding,cb){var self=this;self._body.push(chunk),cb()},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(){var self=this;self._destroyed=!0,global.clearTimeout(self._fetchTimer),self._response&&(self._response._destroyed=!0),self._xhr?self._xhr.abort():self._fetchAbortController&&self._fetchAbortController.abort()},ClientRequest.prototype.end=function(data,encoding,cb){var self=this;"function"==typeof data&&(cb=data,data=void 0),stream.Writable.prototype.end.call(self,data,encoding,cb)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setTimeout=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":100,"./response":102,_process:61,buffer:26,inherits:39,"readable-stream":85}],102:[function(require,module,exports){(function(process,global,Buffer){var capability=require("./capability"),inherits=require("inherits"),stream=require("readable-stream"),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,fetchTimer){var self=this;if(stream.Readable.call(self),self._mode=mode,self.headers={},self.rawHeaders=[],self.trailers={},self.rawTrailers=[],self.on("end",function(){process.nextTick(function(){self.emit("close")})}),"fetch"===mode){function read(){reader.read().then(function(result){return self._destroyed?void 0:result.done?(global.clearTimeout(fetchTimer),void self.push(null)):void(self.push(Buffer.from(result.value)),read())}).catch(function(err){global.clearTimeout(fetchTimer),self._destroyed||self.emit("error",err)})}if(self._fetchResponse=response,self.url=response.url,self.statusCode=response.status,self.statusMessage=response.statusText,response.headers.forEach(function(header,key){self.headers[key.toLowerCase()]=header,self.rawHeaders.push(key,header)}),capability.writableStream){var writable=new WritableStream({write:function(chunk){return new Promise(function(resolve,reject){self._destroyed?reject():self.push(Buffer.from(chunk))?resolve():self._resumeFetch=resolve})},close:function(){global.clearTimeout(fetchTimer),self._destroyed||self.push(null)},abort:function(err){self._destroyed||self.emit("error",err)}});try{return void response.body.pipeTo(writable).catch(function(err){global.clearTimeout(fetchTimer),self._destroyed||self.emit("error",err)})}catch(e){}}var reader=response.body.getReader();read()}else{self._xhr=xhr,self._pos=0,self.url=xhr.responseURL,self.statusCode=xhr.status,self.statusMessage=xhr.statusText;var headers=xhr.getAllResponseHeaders().split(/\r?\n/);if(headers.forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();"set-cookie"===key?(void 0===self.headers[key]&&(self.headers[key]=[]),self.headers[key].push(matches[2])):void 0===self.headers[key]?self.headers[key]=matches[2]:self.headers[key]+=", "+matches[2],self.rawHeaders.push(matches[1],matches[2])}}),self._charset="x-user-defined",!capability.overrideMimeType){var mimeType=self.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);charsetMatch&&(self._charset=charsetMatch[1].toLowerCase())}self._charset||(self._charset="utf-8")}}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){var self=this,resolve=self._resumeFetch;resolve&&(self._resumeFetch=null,resolve())},IncomingMessage.prototype._onXHRProgress=function(){var self=this,xhr=self._xhr,response=null;switch(self._mode){case"text":if(response=xhr.responseText,response.length>self._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=Buffer.alloc(newData.length),i=0;i<newData.length;i++)buffer[i]=255&newData.charCodeAt(i);self.push(buffer)}else self.push(newData,self._charset);self._pos=response.length}break;case"arraybuffer":if(xhr.readyState!==rStates.DONE||!xhr.response)break;response=xhr.response,self.push(Buffer.from(new Uint8Array(response)));break;case"moz-chunked-arraybuffer":if(response=xhr.response,xhr.readyState!==rStates.LOADING||!response)break;self.push(Buffer.from(new Uint8Array(response)));break;case"ms-stream":if(response=xhr.response,xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){reader.result.byteLength>self._pos&&(self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){self.push(null)},reader.readAsArrayBuffer(response);}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&self.push(null)}}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./capability":100,_process:61,buffer:26,inherits:39,"readable-stream":85}],103:[function(require,module){module.exports=async function(stream,mimeType){const blob=await getBlob(stream,mimeType),url=URL.createObjectURL(blob);return url};const getBlob=require("stream-to-blob")},{"stream-to-blob":104}],104:[function(require,module){module.exports=function(stream,mimeType){if(null!=mimeType&&"string"!=typeof mimeType)throw new Error("Invalid mimetype, expected string.");return new Promise((resolve,reject)=>{const chunks=[];stream.on("data",chunk=>chunks.push(chunk)).once("end",()=>{const blob=null==mimeType?new Blob(chunks):new Blob(chunks,{type:mimeType});resolve(blob)}).once("error",reject)})}},{}],105:[function(require,module){(function(Buffer){var once=require("once");module.exports=function(stream,length,cb){cb=once(cb);var buf=Buffer.alloc(length),offset=0;stream.on("data",function(chunk){chunk.copy(buf,offset),offset+=chunk.length}).on("end",function(){cb(null,buf)}).on("error",cb)}}).call(this,require("buffer").Buffer)},{buffer:26,once:56}],106:[function(require,module,exports){'use strict';function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0;}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd);}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){if(127>=byte)return 0;return 6==byte>>5?2:14==byte>>4?3:30==byte>>3?4:2==byte>>6?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);return 0<=nb?(0<nb&&(self.lastNeed=nb-1),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb)?(0<nb&&(self.lastNeed=nb-2),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]),0<=nb?(0<nb&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf){if(128!=(192&buf[0]))return self.lastNeed=0,"\uFFFD";if(1<self.lastNeed&&1<buf.length){if(128!=(192&buf[1]))return self.lastNeed=1,"\uFFFD";if(2<self.lastNeed&&2<buf.length&&128!=(192&buf[2]))return self.lastNeed=2,"\uFFFD"}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0===r?this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,p,0,buf.length),this.lastNeed-=buf.length):r}function utf16Text(buf,i){if(0==(buf.length-i)%2){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(55296<=c&&56319>=c)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0==n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch(encoding=""+encoding,encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1;}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(r=this.fillLast(buf),void 0===r)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<buf.length?r?r+this.text(buf,i):this.text(buf,i):r||""},StringDecoder.prototype.end=function(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"\uFFFD":r},StringDecoder.prototype.text=function(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)},StringDecoder.prototype.fillLast=function(buf){return this.lastNeed<=buf.length?(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):void(buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length),this.lastNeed-=buf.length)}},{"safe-buffer":91}],107:[function(require,module,exports){var base32=require("./thirty-two");exports.encode=base32.encode,exports.decode=base32.decode},{"./thirty-two":108}],108:[function(require,module,exports){(function(Buffer){'use strict';function quintetCount(buff){var quintets=_Mathfloor(buff.length/5);return 0==buff.length%5?quintets:quintets+1}var byteTable=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];exports.encode=function(plain){Buffer.isBuffer(plain)||(plain=new Buffer(plain));for(var i=0,j=0,shiftIndex=0,digit=0,encoded=new Buffer(8*quintetCount(plain));i<plain.length;){var current=plain[i];3<shiftIndex?(digit=current&255>>shiftIndex,shiftIndex=(shiftIndex+5)%8,digit=digit<<shiftIndex|(i+1<plain.length?plain[i+1]:0)>>8-shiftIndex,i++):(digit=31¤t>>8-(shiftIndex+5),shiftIndex=(shiftIndex+5)%8,0===shiftIndex&&i++),encoded[j]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(digit),j++}for(i=j;i<encoded.length;i++)encoded[i]=61;return encoded},exports.decode=function(encoded){var shiftIndex=0,plainDigit=0,plainPos=0,plainChar;Buffer.isBuffer(encoded)||(encoded=new Buffer(encoded));for(var decoded=new Buffer(_Mathceil(5*encoded.length/8)),i=0;i<encoded.length&&!(61===encoded[i]);i++){var encodedByte=encoded[i]-48;if(encodedByte<byteTable.length)plainDigit=byteTable[encodedByte],3>=shiftIndex?(shiftIndex=(shiftIndex+5)%8,0===shiftIndex?(plainChar|=plainDigit,decoded[plainPos]=plainChar,plainPos++,plainChar=0):plainChar|=255&plainDigit<<8-shiftIndex):(shiftIndex=(shiftIndex+5)%8,plainChar|=255&plainDigit>>>shiftIndex,decoded[plainPos]=plainChar,plainPos++,plainChar=255&plainDigit<<8-shiftIndex);else throw new Error("Invalid input - it is not base32 encoded string")}return decoded.slice(0,plainPos)}}).call(this,require("buffer").Buffer)},{buffer:26}],109:[function(require,module){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;i<len;i++)arrayCopy[i]=buf[i];return arrayCopy.buffer}throw new Error("Argument must be a Buffer")}},{buffer:26}],110:[function(require,module){(function(process){const debug=require("debug")("torrent-discovery"),DHT=require("bittorrent-dht/client"),EventEmitter=require("events").EventEmitter,parallel=require("run-parallel"),Tracker=require("bittorrent-tracker/client");module.exports=class extends EventEmitter{constructor(opts){if(super(),!opts.peerId)throw new Error("Option `peerId` is required");if(!opts.infoHash)throw new Error("Option `infoHash` is required");if(!process.browser&&!opts.port)throw new Error("Option `port` is required");this.peerId="string"==typeof opts.peerId?opts.peerId:opts.peerId.toString("hex"),this.infoHash="string"==typeof opts.infoHash?opts.infoHash.toLowerCase():opts.infoHash.toString("hex"),this._port=opts.port,this._userAgent=opts.userAgent,this.destroyed=!1,this._announce=opts.announce||[],this._intervalMs=opts.intervalMs||900000,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=err=>{this.emit("warning",err)},this._onError=err=>{this.emit("error",err)},this._onDHTPeer=(peer,infoHash)=>{infoHash.toString("hex")!==this.infoHash||this.emit("peer",`${peer.host}:${peer.port}`,"dht")},this._onTrackerPeer=peer=>{this.emit("peer",peer,"tracker")},this._onTrackerAnnounce=()=>{this.emit("trackerAnnounce")};const createDHT=(port,opts)=>{const dht=new DHT(opts);return dht.on("warning",this._onWarning),dht.on("error",this._onError),dht.listen(port),this._internalDHT=!0,dht};!1===opts.tracker?this.tracker=null:opts.tracker&&"object"==typeof opts.tracker?(this._trackerOpts=Object.assign({},opts.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),this.dht=!1===opts.dht||"function"!=typeof DHT?null:opts.dht&&"function"==typeof opts.dht.addNode?opts.dht:opts.dht&&"object"==typeof opts.dht?createDHT(opts.dhtPort,opts.dht):createDHT(opts.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce())}updatePort(port){port===this._port||(this._port=port,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(opts){this.tracker&&this.tracker.complete(opts)}destroy(cb){if(!this.destroyed){this.destroyed=!0,clearTimeout(this._dhtTimeout);const tasks=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),tasks.push(cb=>{this.tracker.destroy(cb)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),tasks.push(cb=>{this.dht.destroy(cb)})),parallel(tasks,cb),this.dht=null,this.tracker=null,this._announce=null}}_createTracker(){const opts=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),tracker=new Tracker(opts);return tracker.on("warning",this._onWarning),tracker.on("error",this._onError),tracker.on("peer",this._onTrackerPeer),tracker.on("update",this._onTrackerAnnounce),tracker.setInterval(this._intervalMs),tracker.start(),tracker}_dhtAnnounce(){this._dhtAnnouncing||(debug("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,err=>{this._dhtAnnouncing=!1,debug("dht announce complete"),err&&this.emit("warning",err),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+_Mathfloor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}}}).call(this,require("_process"))},{_process:61,"bittorrent-dht/client":21,"bittorrent-tracker/client":15,debug:30,events:33,"run-parallel":89}],111:[function(require,module){(function(Buffer){const BLOCK_LENGTH=16384;class Piece{constructor(length){this.length=length,this.missing=length,this.sources=null,this._chunks=_Mathceil(length/BLOCK_LENGTH),this._remainder=length%BLOCK_LENGTH||BLOCK_LENGTH,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(i){return i===this._chunks-1?this._remainder:BLOCK_LENGTH}chunkLengthRemaining(i){return this.length-i*BLOCK_LENGTH}chunkOffset(i){return i*BLOCK_LENGTH}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations<this._chunks?this._reservations++:-1:-1}reserveRemaining(){if(!this.init())return-1;if(this._reservations<this._chunks){const min=this._reservations;return this._reservations=this._chunks,min}return-1}cancel(i){this.init()&&this._cancellations.push(i)}cancelRemaining(i){this.init()&&(this._reservations=i)}get(i){return this.init()?this._buffer[i]:null}set(i,data,source){if(!this.init())return!1;const len=data.length,blocks=_Mathceil(len/BLOCK_LENGTH);for(let j=0;j<blocks;j++)if(!this._buffer[i+j]){const offset=j*BLOCK_LENGTH,splitData=data.slice(offset,offset+BLOCK_LENGTH);this._buffered++,this._buffer[i+j]=splitData,this.missing-=splitData.length,this.sources.includes(source)||this.sources.push(source)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const buffer=Buffer.concat(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,buffer}init(){return!this._flushed&&(!!this._buffer||(this._buffer=Array(this._chunks),this._cancellations=[],this.sources=[],!0))}}Object.defineProperty(Piece,"BLOCK_LENGTH",{value:16384}),module.exports=Piece}).call(this,require("buffer").Buffer)},{buffer:26}],112:[function(require,module){(function(Buffer){var isTypedArray=require("is-typedarray").strict;module.exports=function(arr){if(isTypedArray(arr)){var buf=Buffer.from(arr.buffer);return arr.byteLength!==arr.buffer.byteLength&&(buf=buf.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)),buf}return Buffer.from(arr)}}).call(this,require("buffer").Buffer)},{buffer:26,"is-typedarray":42}],113:[function(require,module,exports){var bufferAlloc=require("buffer-alloc"),UINT_32_MAX=_Mathpow(2,32);exports.encodingLength=function(){return 8},exports.encode=function(num,buf,offset){buf||(buf=bufferAlloc(8)),offset||(offset=0);var top=_Mathfloor(num/UINT_32_MAX);return buf.writeUInt32BE(top,offset),buf.writeUInt32BE(num-top*UINT_32_MAX,offset+4),buf},exports.decode=function(buf,offset){offset||(offset=0);var top=buf.readUInt32BE(offset),rem=buf.readUInt32BE(offset+4);return top*UINT_32_MAX+rem},exports.encode.bytes=8,exports.decode.bytes=8},{"buffer-alloc":24}],114:[function(require,module){"use strict";function unique_pred(list,compare){for(var ptr=1,len=list.length,a=list[0],b=list[0],i=1;i<len;++i)if(b=a,a=list[i],compare(a,b)){if(i===ptr){ptr++;continue}list[ptr++]=a}return list.length=ptr,list}function unique_eq(list){for(var ptr=1,len=list.length,a=list[0],b=list[0],i=1;i<len;++i,b=a)if(b=a,a=list[i],a!==b){if(i===ptr){ptr++;continue}list[ptr++]=a}return list.length=ptr,list}module.exports=function(list,compare,sorted){return 0===list.length?list:compare?(sorted||list.sort(compare),unique_pred(list,compare)):(sorted||list.sort(),unique_eq(list))}},{}],115:[function(require,module){module.exports=function(arr,i){if(!(i>=arr.length||0>i)){var last=arr.pop();if(i<arr.length){var tmp=arr[i];return arr[i]=last,tmp}return last}}},{}],116:[function(require,module,exports){'use strict';function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}var punycode=require("punycode"),util=require("./util");exports.parse=urlParse,exports.resolve=function(source,relative){return urlParse(source,!1,!0).resolve(relative)},exports.resolveObject=function(source,relative){return source?urlParse(source,!1,!0).resolveObject(relative):relative},exports.format=function(obj){return util.isString(obj)&&(obj=urlParse(obj)),obj instanceof Url?obj.format():Url.prototype.format.call(obj)},exports.Url=Url;var unwise=["{","}","|","\\","^","`"].concat(["<",">","\"","`"," ","\r","\n","\t"]),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=-1!==queryIndex&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter);uSplit[0]=uSplit[0].replace(/\\/g,"/"),url=uSplit.join(splitter);var rest=url;if(rest=rest.trim(),!slashesDenoteHost&&1===url.split("#").length){var simplePath=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/.exec(rest);if(simplePath)return this.path=rest,this.href=rest,this.pathname=simplePath[1],simplePath[2]?(this.search=simplePath[2],this.query=parseQueryString?querystring.parse(this.search.substr(1)):this.search.substr(1)):parseQueryString&&(this.search="",this.query={}),this}var proto=/^([a-z0-9.+-]+:)/i.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto,rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes="//"===rest.substr(0,2);slashes&&!(proto&&hostlessProtocol[proto])&&(rest=rest.substr(2),this.slashes=!0)}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){for(var hostEnd=-1,i=0,hec;i<hostEndingChars.length;i++)hec=rest.indexOf(hostEndingChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);var auth,atSign;atSign=-1===hostEnd?rest.lastIndexOf("@"):rest.lastIndexOf("@",hostEnd),-1!==atSign&&(auth=rest.slice(0,atSign),rest=rest.slice(atSign+1),this.auth=decodeURIComponent(auth)),hostEnd=-1;for(var i=0,hec;i<nonHostChars.length;i++)hec=rest.indexOf(nonHostChars[i]),-1!==hec&&(-1===hostEnd||hec<hostEnd)&&(hostEnd=hec);-1===hostEnd&&(hostEnd=rest.length),this.host=rest.slice(0,hostEnd),rest=rest.slice(hostEnd),this.parseHost(),this.hostname=this.hostname||"";var ipv6Hostname="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!ipv6Hostname)for(var hostparts=this.hostname.split(/\./),i=0,l=hostparts.length,part;i<l;i++)if(part=hostparts[i],part&&!part.match(hostnamePartPattern)){for(var newpart="",j=0,k=part.length;j<k;j++)newpart+=127<part.charCodeAt(j)?"x":part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(/^([+a-z0-9A-Z_-]{0,63})(.*)$/);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}this.hostname=255<this.hostname.length?"":this.hostname.toLowerCase(),ipv6Hostname||(this.hostname=punycode.toASCII(this.hostname));var p=this.port?":"+this.port:"",h=this.hostname||"";this.host=h+p,this.href+=this.host,ipv6Hostname&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==rest[0]&&(rest="/"+rest))}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length,ae;i<l;i++)if(ae=autoEscape[i],-1!==rest.indexOf(ae)){var esc=encodeURIComponent(ae);esc===ae&&(esc=escape(ae)),rest=rest.split(ae).join(esc)}var hash=rest.indexOf("#");-1!==hash&&(this.hash=rest.substr(hash),rest=rest.slice(0,hash));var qm=rest.indexOf("?");if(-1===qm?parseQueryString&&(this.search="",this.query={}):(this.search=rest.substr(qm),this.query=rest.substr(qm+1),parseQueryString&&(this.query=querystring.parse(this.query)),rest=rest.slice(0,qm)),rest&&(this.pathname=rest),slashedProtocol[lowerProto]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var p=this.pathname||"",s=this.search||"";this.path=p+s}return this.href=this.format(),this},Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=encodeURIComponent(auth),auth=auth.replace(/%3A/i,":"),auth+="@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=!1,query="";this.host?host=auth+this.host:this.hostname&&(host=auth+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(host+=":"+this.port)),this.query&&util.isObject(this.query)&&Object.keys(this.query).length&&(query=querystring.stringify(this.query));var search=this.search||query&&"?"+query||"";return protocol&&":"!==protocol.substr(-1)&&(protocol+=":"),this.slashes||(!protocol||slashedProtocol[protocol])&&!1!==host?(host="//"+(host||""),pathname&&"/"!==pathname.charAt(0)&&(pathname="/"+pathname)):!host&&(host=""),hash&&"#"!==hash.charAt(0)&&(hash="#"+hash),search&&"?"!==search.charAt(0)&&(search="?"+search),pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)}),search=search.replace("#","%23"),protocol+host+pathname+search+hash},Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,!1,!0)).format()},Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,!1,!0),relative=rel}for(var result=new Url,tkeys=Object.keys(this),tk=0,tkey;tk<tkeys.length;tk++)tkey=tkeys[tk],result[tkey]=this[tkey];if(result.hash=relative.hash,""===relative.href)return result.href=result.format(),result;if(relative.slashes&&!relative.protocol){for(var rkeys=Object.keys(relative),rk=0,rkey;rk<rkeys.length;rk++)rkey=rkeys[rk],"protocol"!==rkey&&(result[rkey]=relative[rkey]);return slashedProtocol[result.protocol]&&result.hostname&&!result.pathname&&(result.path=result.pathname="/"),result.href=result.format(),result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){for(var keys=Object.keys(relative),v=0,k;v<keys.length;v++)k=keys[v],result[k]=relative[k];return result.href=result.format(),result}if(result.protocol=relative.protocol,!relative.host&&!hostlessProtocol[relative.protocol]){for(var relPath=(relative.pathname||"").split("/");relPath.length&&!(relative.host=relPath.shift()););relative.host||(relative.host=""),relative.hostname||(relative.hostname=""),""!==relPath[0]&&relPath.unshift(""),2>relPath.length&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative.pathname;if(result.search=relative.search,result.query=relative.query,result.host=relative.host||"",result.auth=relative.auth,result.hostname=relative.hostname||relative.host,result.port=relative.port,result.pathname||result.search){var p=result.pathname||"",s=result.search||"";result.path=p+s}return result.slashes=result.slashes||relative.slashes,result.href=result.format(),result}var isSourceAbs=result.pathname&&"/"===result.pathname.charAt(0),isRelAbs=relative.host||relative.pathname&&"/"===relative.pathname.charAt(0),mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic&&(result.hostname="",result.port=null,result.host&&(""===srcPath[0]?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative.protocol&&(relative.hostname=null,relative.port=null,relative.host&&(""===relPath[0]?relPath[0]=relative.host:relPath.unshift(relative.host)),relative.host=null),mustEndAbs=mustEndAbs&&(""===relPath[0]||""===srcPath[0])),isRelAbs)result.host=relative.host||""===relative.host?relative.host:result.host,result.hostname=relative.hostname||""===relative.hostname?relative.hostname:result.hostname,result.search=relative.search,result.query=relative.query,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative.search,result.query=relative.query;else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=!!(result.host&&0<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.path=result.search?"/"+result.search:null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||1<srcPath.length)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;0<=i;i--)last=srcPath[i],"."===last?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");mustEndAbs&&""!==srcPath[0]&&(!srcPath[0]||"/"!==srcPath[0].charAt(0))&&srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=!!(result.host&&0<result.host.indexOf("@"))&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=/:[0-9]*$/.exec(host);port&&(port=port[0],":"!==port&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},{"./util":117,punycode:63,querystring:66}],117:[function(require,module){'use strict';module.exports={isString:function(arg){return"string"==typeof arg},isObject:function(arg){return"object"==typeof arg&&null!==arg},isNull:function(arg){return null===arg},isNullOrUndefined:function(arg){return null==arg}}},{}],118:[function(require,module){(function(Buffer){const{EventEmitter}=require("events"),bencode=require("bencode"),BitField=require("bitfield"),debug=require("debug")("ut_metadata"),sha1=require("simple-sha1"),BITFIELD_GROW=1E3,PIECE_LENGTH=16384;module.exports=metadata=>{class utMetadata extends EventEmitter{constructor(wire){super(),this._wire=wire,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),Buffer.isBuffer(metadata)&&this.setMetadata(metadata)}onHandshake(infoHash){this._infoHash=infoHash}onExtendedHandshake(handshake){return handshake.m&&handshake.m.ut_metadata?handshake.metadata_size?"number"!=typeof handshake.metadata_size||1E7<handshake.metadata_size||0>=handshake.metadata_size?this.emit("warning",new Error("Peer gave invalid metadata size")):void(this._metadataSize=handshake.metadata_size,this._numPieces=_Mathceil(this._metadataSize/PIECE_LENGTH),this._remainingRejects=2*this._numPieces,this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(buf){let dict,trailer;try{const str=buf.toString(),trailerIndex=str.indexOf("ee")+2;dict=bencode.decode(str.substring(0,trailerIndex)),trailer=buf.slice(trailerIndex)}catch(err){return}switch(dict.msg_type){case 0:this._onRequest(dict.piece);break;case 1:this._onData(dict.piece,trailer,dict.total_size);break;case 2:this._onReject(dict.piece);}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}setMetadata(metadata){if(this._metadataComplete)return!0;debug("set metadata");try{const info=bencode.decode(metadata).info;info&&(metadata=bencode.encode(info))}catch(err){}return!(this._infoHash&&this._infoHash!==sha1.sync(metadata))&&(this.cancel(),this.metadata=metadata,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",bencode.encode({info:bencode.decode(this.metadata)})),!0)}_send(dict,trailer){let buf=bencode.encode(dict);Buffer.isBuffer(trailer)&&(buf=Buffer.concat([buf,trailer])),this._wire.extended("ut_metadata",buf)}_request(piece){this._send({msg_type:0,piece})}_data(piece,buf,totalSize){const msg={msg_type:1,piece};"number"==typeof totalSize&&(msg.total_size=totalSize),this._send(msg,buf)}_reject(piece){this._send({msg_type:2,piece})}_onRequest(piece){if(!this._metadataComplete)return void this._reject(piece);const start=piece*PIECE_LENGTH;let end=start+PIECE_LENGTH;end>this._metadataSize&&(end=this._metadataSize);const buf=this.metadata.slice(start,end);this._data(piece,buf,this._metadataSize)}_onData(piece,buf){buf.length>PIECE_LENGTH||!this._fetching||(buf.copy(this.metadata,piece*PIECE_LENGTH),this._bitfield.set(piece),this._checkDone())}_onReject(piece){0<this._remainingRejects&&this._fetching?(this._request(piece),this._remainingRejects-=1):this.emit("warning",new Error("Peer sent \"reject\" too much"))}_requestPieces(){if(this._fetching){this.metadata=Buffer.alloc(this._metadataSize);for(let piece=0;piece<this._numPieces;piece++)this._request(piece)}}_checkDone(){let done=!0;for(let piece=0;piece<this._numPieces;piece++)if(!this._bitfield.get(piece)){done=!1;break}if(done){const success=this.setMetadata(this.metadata);success||this._failedMetadata()}}_failedMetadata(){this._bitfield=new BitField(0,{grow:BITFIELD_GROW}),this._remainingRejects-=this._numPieces,0<this._remainingRejects?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return utMetadata.prototype.name="ut_metadata",utMetadata}}).call(this,require("buffer").Buffer)},{bencode:11,bitfield:13,buffer:26,debug:30,events:33,"simple-sha1":95}],119:[function(require,module){(function(global){function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===(val+"").toLowerCase()}module.exports=function(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);else config("traceDeprecation")?console.trace(msg):console.warn(msg);warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],120:[function(require,module){(function(Buffer){function empty(){return{version:0,flags:0,entries:[]}}const bs=require("binary-search"),EventEmitter=require("events"),mp4=require("mp4-stream"),Box=require("mp4-box-encoding"),RangeSliceStream=require("range-slice-stream");class RunLengthIndex{constructor(entries,countName){this._entries=entries,this._countName=countName||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}module.exports=class extends EventEmitter{constructor(file){super(),this._tracks=[],this._file=file,this._decoder=null,this._findMoov(0)}_findMoov(offset){this._decoder&&this._decoder.destroy();let toSkip=0;this._decoder=mp4.decode();const fileStream=this._file.createReadStream({start:offset});fileStream.pipe(this._decoder);const boxHandler=headers=>{"moov"===headers.type?(this._decoder.removeListener("box",boxHandler),this._decoder.decode(moov=>{fileStream.destroy();try{this._processMoov(moov)}catch(err){err.message=`Cannot parse mp4 file: ${err.message}`,this.emit("error",err)}})):headers.length<4096?(toSkip+=headers.length,this._decoder.ignore()):(this._decoder.removeListener("box",boxHandler),toSkip+=headers.length,fileStream.destroy(),this._decoder.destroy(),this._findMoov(offset+toSkip))};this._decoder.on("box",boxHandler)}_processMoov(moov){const traks=moov.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let i=0;i<traks.length;i++){const trak=traks[i],stbl=trak.mdia.minf.stbl,stsdEntry=stbl.stsd.entries[0],handlerType=trak.mdia.hdlr.handlerType;let codec,mime;if("vide"===handlerType&&"avc1"===stsdEntry.type){if(this._hasVideo)continue;this._hasVideo=!0,codec="avc1",stsdEntry.avcC&&(codec+=`.${stsdEntry.avcC.mimeCodec}`),mime=`video/mp4; codecs="${codec}"`}else if("soun"===handlerType&&"mp4a"===stsdEntry.type){if(this._hasAudio)continue;this._hasAudio=!0,codec="mp4a",stsdEntry.esds&&stsdEntry.esds.mimeCodec&&(codec+=`.${stsdEntry.esds.mimeCodec}`),mime=`audio/mp4; codecs="${codec}"`}else continue;const samples=[];let sample=0,sampleInChunk=0,chunk=0,offsetInChunk=0,sampleToChunkIndex=0,dts=0;const decodingTimeEntry=new RunLengthIndex(stbl.stts.entries);let presentationOffsetEntry=null;stbl.ctts&&(presentationOffsetEntry=new RunLengthIndex(stbl.ctts.entries));for(let syncSampleIndex=0;;){var currChunkEntry=stbl.stsc.entries[sampleToChunkIndex];const size=stbl.stsz.entries[sample],duration=decodingTimeEntry.value.duration,presentationOffset=presentationOffsetEntry?presentationOffsetEntry.value.compositionOffset:0;let sync=!0;stbl.stss&&(sync=stbl.stss.entries[syncSampleIndex]===sample+1);const chunkOffsetTable=stbl.stco||stbl.co64;if(samples.push({size,duration,dts,presentationOffset,sync,offset:offsetInChunk+chunkOffsetTable.entries[chunk]}),sample++,sample>=stbl.stsz.entries.length)break;if(sampleInChunk++,offsetInChunk+=size,sampleInChunk>=currChunkEntry.samplesPerChunk){sampleInChunk=0,offsetInChunk=0,chunk++;const nextChunkEntry=stbl.stsc.entries[sampleToChunkIndex+1];nextChunkEntry&&chunk+1>=nextChunkEntry.firstChunk&&sampleToChunkIndex++}dts+=duration,decodingTimeEntry.inc(),presentationOffsetEntry&&presentationOffsetEntry.inc(),sync&&syncSampleIndex++}trak.mdia.mdhd.duration=0,trak.tkhd.duration=0;const defaultSampleDescriptionIndex=currChunkEntry.sampleDescriptionId,trackMoov={type:"moov",mvhd:moov.mvhd,traks:[{tkhd:trak.tkhd,mdia:{mdhd:trak.mdia.mdhd,hdlr:trak.mdia.hdlr,elng:trak.mdia.elng,minf:{vmhd:trak.mdia.minf.vmhd,smhd:trak.mdia.minf.smhd,dinf:trak.mdia.minf.dinf,stbl:{stsd:stbl.stsd,stts:empty(),ctts:empty(),stsc:empty(),stsz:empty(),stco:empty(),stss:empty()}}}}],mvex:{mehd:{fragmentDuration:moov.mvhd.duration},trexs:[{trackId:trak.tkhd.trackId,defaultSampleDescriptionIndex,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:trak.tkhd.trackId,timeScale:trak.mdia.mdhd.timeScale,samples,currSample:null,currTime:null,moov:trackMoov,mime})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));moov.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const ftypBuf=Box.encode(this._ftyp),data=this._tracks.map(track=>{const moovBuf=Box.encode(track.moov);return{mime:track.mime,init:Buffer.concat([ftypBuf,moovBuf])}});this.emit("ready",data)}seek(time){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let startOffset=-1;if(this._tracks.map((track,i)=>{track.outStream&&track.outStream.destroy(),track.inStream&&(track.inStream.destroy(),track.inStream=null);const outStream=track.outStream=mp4.encode(),fragment=this._generateFragment(i,time);if(!fragment)return outStream.finalize();(-1===startOffset||fragment.ranges[0].start<startOffset)&&(startOffset=fragment.ranges[0].start);const writeFragment=frag=>{outStream.destroyed||outStream.box(frag.moof,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const slicedStream=track.inStream.slice(frag.ranges);slicedStream.pipe(outStream.mediaData(frag.length,err=>{if(err)return this.emit("error",err);if(!outStream.destroyed){const nextFrag=this._generateFragment(i);return nextFrag?void writeFragment(nextFrag):outStream.finalize()}}))}})};writeFragment(fragment)}),0<=startOffset){const fileStream=this._fileStream=this._file.createReadStream({start:startOffset});this._tracks.forEach(track=>{track.inStream=new RangeSliceStream(startOffset,{highWaterMark:1e7}),fileStream.pipe(track.inStream)})}return this._tracks.map(track=>track.outStream)}_findSampleBefore(trackInd,time){const track=this._tracks[trackInd],scaledTime=_Mathfloor(track.timeScale*time);let sample=bs(track.samples,scaledTime,(sample,t)=>{const pts=sample.dts+sample.presentationOffset;return pts-t});for(-1===sample?sample=0:0>sample&&(sample=-sample-2);!track.samples[sample].sync;)sample--;return sample}_generateFragment(track,time){const currTrack=this._tracks[track];let firstSample;if(firstSample=void 0===time?currTrack.currSample:this._findSampleBefore(track,time),firstSample>=currTrack.samples.length)return null;const startDts=currTrack.samples[firstSample].dts;let totalLen=0;const ranges=[];for(var currSample=firstSample;currSample<currTrack.samples.length;currSample++){const sample=currTrack.samples[currSample];if(sample.sync&&sample.dts-startDts>=currTrack.timeScale*1)break;totalLen+=sample.size;const currRange=ranges.length-1;0>currRange||ranges[currRange].end!==sample.offset?ranges.push({start:sample.offset,end:sample.offset+sample.size}):ranges[currRange].end+=sample.size}return currTrack.currSample=currSample,{moof:this._generateMoof(track,firstSample,currSample),ranges,length:totalLen}}_generateMoof(track,firstSample,lastSample){const currTrack=this._tracks[track],entries=[];let trunVersion=0;for(let j=firstSample;j<lastSample;j++){const currSample=currTrack.samples[j];0>currSample.presentationOffset&&(trunVersion=1),entries.push({sampleDuration:currSample.duration,sampleSize:currSample.size,sampleFlags:currSample.sync?33554432:16842752,sampleCompositionTimeOffset:currSample.presentationOffset})}const moof={type:"moof",mfhd:{sequenceNumber:currTrack.fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:currTrack.trackId},tfdt:{baseMediaDecodeTime:currTrack.samples[firstSample].dts},trun:{flags:3841,dataOffset:8,entries,version:trunVersion}}]};return moof.trafs[0].trun.dataOffset+=Box.encodingLength(moof),moof}}}).call(this,require("buffer").Buffer)},{"binary-search":12,buffer:26,events:33,"mp4-box-encoding":49,"mp4-stream":52,"range-slice-stream":70}],121:[function(require,module){function VideoStream(file,mediaElem,opts={}){return this instanceof VideoStream?void(this.detailedError=null,this._elem=mediaElem,this._elemWrapper=new MediaElementWrapper(mediaElem),this._waitingFired=!1,this._trackMeta=null,this._file=file,this._tracks=null,"none"!==this._elem.preload&&this._createMuxer(),this._onError=()=>{this.detailedError=this._elemWrapper.detailedError,this.destroy()},this._onWaiting=()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()},mediaElem.autoplay&&(mediaElem.preload="auto"),mediaElem.addEventListener("waiting",this._onWaiting),mediaElem.addEventListener("error",this._onError)):(console.warn("don't invoked VideoStream without 'new'"),new VideoStream(file,mediaElem,opts))}const MediaElementWrapper=require("mediasource"),pump=require("pump"),MP4Remuxer=require("./mp4-remuxer");VideoStream.prototype={_createMuxer(){this._muxer=new MP4Remuxer(this._file),this._muxer.on("ready",data=>{this._tracks=data.map(trackData=>{const mediaSource=this._elemWrapper.createWriteStream(trackData.mime);mediaSource.on("error",err=>{this._elemWrapper.error(err)});const track={muxed:null,mediaSource,initFlushed:!1,onInitFlushed:null};return mediaSource.write(trackData.init,err=>{track.initFlushed=!0,track.onInitFlushed&&track.onInitFlushed(err)}),track}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",err=>{this._elemWrapper.error(err)})},_pump(){const muxed=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((track,i)=>{const pumpTrack=()=>{track.muxed&&(track.muxed.destroy(),track.mediaSource=this._elemWrapper.createWriteStream(track.mediaSource),track.mediaSource.on("error",err=>{this._elemWrapper.error(err)})),track.muxed=muxed[i],pump(track.muxed,track.mediaSource)};track.initFlushed?pumpTrack():track.onInitFlushed=err=>err?void this._elemWrapper.error(err):void pumpTrack()})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(track=>{track.muxed&&track.muxed.destroy()}),this._elem.src="")}},module.exports=VideoStream},{"./mp4-remuxer":120,mediasource:45,pump:62}],122:[function(require,module){function wrappy(fn,cb){function wrapper(){for(var args=Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];var ret=fn.apply(this,args),cb=args[args.length-1];return"function"==typeof ret&&ret!==cb&&Object.keys(cb).forEach(function(k){ret[k]=cb[k]}),ret}if(fn&&cb)return wrappy(fn)(cb);if("function"!=typeof fn)throw new TypeError("need wrapper function");return Object.keys(fn).forEach(function(k){wrapper[k]=fn[k]}),wrapper}module.exports=wrappy},{}],123:[function(require,module){module.exports=function(){for(var target={},i=0,source;i<arguments.length;i++)for(var key in source=arguments[i],source)hasOwnProperty.call(source,key)&&(target[key]=source[key]);return target};var hasOwnProperty=Object.prototype.hasOwnProperty},{}],124:[function(require,module){module.exports={version:"0.108.1"}},{}],125:[function(require,module){(function(process,global,Buffer){function isReadable(obj){return"object"==typeof obj&&null!=obj&&"function"==typeof obj.pipe}function isFileList(obj){return"undefined"!=typeof FileList&&obj instanceof FileList}const{EventEmitter}=require("events"),concat=require("simple-concat"),createTorrent=require("create-torrent"),debug=require("debug")("webtorrent"),DHT=require("bittorrent-dht/client"),loadIPSet=require("load-ip-set"),parallel=require("run-parallel"),parseTorrent=require("parse-torrent"),path=require("path"),Peer=require("simple-peer"),randombytes=require("randombytes"),speedometer=require("speedometer"),TCPPool=require("./lib/tcp-pool"),Torrent=require("./lib/torrent"),VERSION=require("./package.json").version,VERSION_STR=VERSION.replace(/\d*./g,v=>`0${v%100}`.slice(-2)).slice(0,4);class WebTorrent extends EventEmitter{constructor(opts={}){super(),this.peerId="string"==typeof opts.peerId?opts.peerId:Buffer.isBuffer(opts.peerId)?opts.peerId.toString("hex"):Buffer.from(`-WW${VERSION_STR}-`+randombytes(9).toString("base64")).toString("hex"),this.peerIdBuffer=Buffer.from(this.peerId,"hex"),this.nodeId="string"==typeof opts.nodeId?opts.nodeId:Buffer.isBuffer(opts.nodeId)?opts.nodeId.toString("hex"):randombytes(20).toString("hex"),this.nodeIdBuffer=Buffer.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=opts.torrentPort||0,this.dhtPort=opts.dhtPort||0,this.tracker=opts.tracker===void 0?{}:opts.tracker,this.torrents=[],this.maxConns=+opts.maxConns||55,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),opts.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=opts.rtcConfig),opts.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=opts.wrtc),global.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=global.WRTC)),"function"==typeof TCPPool?this._tcpPool=new TCPPool(this):process.nextTick(()=>{this._onListening()}),this._downloadSpeed=speedometer(),this._uploadSpeed=speedometer(),!1!==opts.dht&&"function"==typeof DHT?(this.dht=new DHT(Object.assign({},{nodeId:this.nodeId},opts.dht)),this.dht.once("error",err=>{this._destroy(err)}),this.dht.once("listening",()=>{const address=this.dht.address();address&&(this.dhtPort=address.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==opts.webSeeds;const ready=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof loadIPSet&&null!=opts.blocklist?loadIPSet(opts.blocklist,{headers:{"user-agent":`WebTorrent/${VERSION} (https://webtorrent.io)`}},(err,ipSet)=>err?this.error(`Failed to load blocklist: ${err.message}`):void(this.blocked=ipSet,ready())):process.nextTick(ready)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const torrents=this.torrents.filter(torrent=>1!==torrent.progress),downloaded=torrents.reduce((total,torrent)=>total+torrent.downloaded,0),length=torrents.reduce((total,torrent)=>total+(torrent.length||0),0)||1;return downloaded/length}get ratio(){const uploaded=this.torrents.reduce((total,torrent)=>total+torrent.uploaded,0),received=this.torrents.reduce((total,torrent)=>total+torrent.received,0)||1;return uploaded/received}get(torrentId){if(!(torrentId instanceof Torrent)){let parsed;try{parsed=parseTorrent(torrentId)}catch(err){}if(!parsed)return null;if(!parsed.infoHash)throw new Error("Invalid torrent identifier");for(const torrent of this.torrents)if(torrent.infoHash===parsed.infoHash)return torrent}else if(this.torrents.includes(torrentId))return torrentId;return null}download(torrentId,opts,ontorrent){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(torrentId,opts,ontorrent)}add(torrentId,opts={},ontorrent){function onClose(){torrent.removeListener("_infoHash",onInfoHash),torrent.removeListener("ready",onReady),torrent.removeListener("close",onClose)}if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,ontorrent]=[{},opts]);const onInfoHash=()=>{if(!this.destroyed)for(const t of this.torrents)if(t.infoHash===torrent.infoHash&&t!==torrent)return void torrent._destroy(new Error(`Cannot add duplicate torrent ${torrent.infoHash}`))},onReady=()=>{this.destroyed||("function"==typeof ontorrent&&ontorrent(torrent),this.emit("torrent",torrent))};this._debug("add"),opts=opts?Object.assign({},opts):{};const torrent=new Torrent(torrentId,this,opts);return this.torrents.push(torrent),torrent.once("_infoHash",onInfoHash),torrent.once("ready",onReady),torrent.once("close",onClose),torrent}seed(input,opts,onseed){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof opts&&([opts,onseed]=[{},opts]),this._debug("seed"),opts=opts?Object.assign({},opts):{},opts.skipVerify=!0;const isFilePath="string"==typeof input;isFilePath&&(opts.path=path.dirname(input)),opts.createdBy||(opts.createdBy=`WebTorrent/${VERSION_STR}`);const _onseed=torrent=>{this._debug("on seed"),"function"==typeof onseed&&onseed(torrent),torrent.emit("seed"),this.emit("seed",torrent)},torrent=this.add(null,opts,torrent=>{const tasks=[cb=>isFilePath?cb():void torrent.load(streams,cb)];this.dht&&tasks.push(cb=>{torrent.once("dhtAnnounce",cb)}),parallel(tasks,err=>this.destroyed?void 0:err?torrent._destroy(err):void _onseed(torrent))});let streams;return isFileList(input)?input=Array.from(input):!Array.isArray(input)&&(input=[input]),parallel(input.map(item=>cb=>{isReadable(item)?concat(item,cb):cb(null,item)}),(err,input)=>this.destroyed?void 0:err?torrent._destroy(err):void createTorrent.parseInput(input,opts,(err,files)=>this.destroyed?void 0:err?torrent._destroy(err):void(streams=files.map(file=>file.getStream),createTorrent(input,opts,(err,torrentBuf)=>{if(!this.destroyed){if(err)return torrent._destroy(err);const existingTorrent=this.get(torrentBuf);existingTorrent?torrent._destroy(new Error(`Cannot add duplicate torrent ${existingTorrent.infoHash}`)):torrent._onTorrentId(torrentBuf)}})))),torrent}remove(torrentId,cb){this._debug("remove");const torrent=this.get(torrentId);if(!torrent)throw new Error(`No torrent with id ${torrentId}`);this._remove(torrentId,cb)}_remove(torrentId,cb){const torrent=this.get(torrentId);torrent&&(this.torrents.splice(this.torrents.indexOf(torrent),1),torrent.destroy(cb))}address(){return this.listening?this._tcpPool?this._tcpPool.server.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(cb){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,cb)}_destroy(err,cb){this._debug("client destroy"),this.destroyed=!0;const tasks=this.torrents.map(torrent=>cb=>{torrent.destroy(cb)});this._tcpPool&&tasks.push(cb=>{this._tcpPool.destroy(cb)}),this.dht&&tasks.push(cb=>{this.dht.destroy(cb)}),parallel(tasks,cb),err&&this.emit("error",err),this.torrents=[],this._tcpPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._tcpPool){const address=this._tcpPool.server.address();address&&(this.torrentPort=address.port)}this.emit("listening")}_debug(){const args=[].slice.call(arguments);args[0]=`[${this._debugId}] ${args[0]}`,debug(...args)}}WebTorrent.WEBRTC_SUPPORT=Peer.WEBRTC_SUPPORT,WebTorrent.VERSION=VERSION,module.exports=WebTorrent}).call(this,require("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global,require("buffer").Buffer)},{"./lib/tcp-pool":21,"./lib/torrent":5,"./package.json":124,_process:61,"bittorrent-dht/client":21,buffer:26,"create-torrent":29,debug:30,events:33,"load-ip-set":21,"parse-torrent":58,path:59,randombytes:69,"run-parallel":89,"simple-concat":92,"simple-peer":94,speedometer:98}]},{},[125])(125)});
\ No newline at end of file |