diff --git a/.gitattributes b/.gitattributes index 461405f4..641ba134 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,12 @@ *.dat.gz filter=lfs diff=lfs merge=lfs -text *.nnue filter=lfs diff=lfs merge=lfs -text + +lib/engine/stockfish-dev/*.nnue -filter -diff -merge -text +lib/engine/stockfish-18-small/*.nnue -filter -diff -merge -text +lib/engine/stockfish-18/*.nnue -filter -diff -merge -text +lib/engine/stockfish-17-79/*.nnue -filter -diff -merge -text +lib/engine/fairy-stockfish-14/nnue/*.nnue -filter -diff -merge -text + +# README screenshots: they belong on GitHub, not inside the installed extension -- +# keep them out of the release zip (git archive honours export-ignore). +docs/ export-ignore diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 00000000..47123612 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,49 @@ +name: Something is broken +description: A bug, a site that stopped working, an engine misbehaving — no diagnosis needed. +labels: [bug] +body: + - type: markdown + attributes: + value: | + You don't need to know what caused it. Several of the worst bugs here were silent rather + than loud — autoplay skipping a move with nothing logged, an engine that never loaded — so + "it did nothing" is a real report, not a vague one. + - type: textarea + id: what + attributes: + label: What happened? + placeholder: It stopped playing moves on lichess this morning. Panel showed a move, nothing clicked. + validations: + required: true + - type: input + id: version + attributes: + label: Version + description: Shown at the top of the extension's settings page. + placeholder: "3.1.200" + - type: input + id: where + attributes: + label: Site and browser + placeholder: chess.com, Chrome 141 on Windows 11 + - type: dropdown + id: windows-4pc + attributes: + label: Is this the Windows four-player setup? + description: > + If so, which stage failed? Native-messaging failures on Windows are silent — Chrome reports + the host as unavailable and says nothing about why — so the stage is most of the diagnosis. + options: + - "No, not four-player on Windows" + - "1. setup.sh does not produce build/tetrarch.dll" + - "2. `from tetrarch import core` raises" + - "3. `python uci.py` does not answer `go` in a terminal" + - "4. Engine works in a terminal, but the panel cannot find it" + - type: textarea + id: console + attributes: + label: Anything in the console? + description: > + Optional. Right-click the page → Inspect → Console, and for the worker, chrome://extensions + → Mephisto → "service worker". Paste whatever looks relevant. + render: text diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..8e1dd409 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,3 @@ +# Freeform issues stay enabled on purpose: "it did nothing this morning" is a useful report, and a +# required-fields form is a good way to lose it. +blank_issues_enabled: true diff --git a/.github/ISSUE_TEMPLATE/idea.yml b/.github/ISSUE_TEMPLATE/idea.yml new file mode 100644 index 00000000..f89f4fea --- /dev/null +++ b/.github/ISSUE_TEMPLATE/idea.yml @@ -0,0 +1,14 @@ +name: Idea or request +description: A feature, a site to support, an engine to add, or just a thought. +labels: [idea] +body: + - type: markdown + attributes: + value: | + Most of what's in here exists because something was annoying in a real game. Half-formed is fine. + - type: textarea + id: idea + attributes: + label: What would you like? + validations: + required: true diff --git a/.gitignore b/.gitignore index 090a1f02..5424001c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ .idea .DS_Store + +__pycache__/ +*.pyc diff --git a/LICENSING.md b/LICENSING.md new file mode 100644 index 00000000..829f52e7 --- /dev/null +++ b/LICENSING.md @@ -0,0 +1,56 @@ +# Licensing + +This project bundles third-party engines, neural networks, and libraries under several +licenses. Because some of those components are copyleft, the licensing of the project as a +**whole distribution** is not simply the MIT license in [`LICENSE`](LICENSE). Please read this +file before redistributing. + +## Short version + +- The **original Mephisto source code** (by Alexandru Petrusca) and this fork's own source-code + changes are made available under the **MIT License** — see [`LICENSE`](LICENSE). +- However, the project **bundles and distributes** components licensed under **GPL-3.0** + (Stockfish, Fairy-Stockfish, and their NNUE nets; the Maia-1 nets and the Maia 2200 net) and + under **AGPL-3.0** (the Maia-3 model, and this project's Maia-3 encoder which is derived from + the Maia-3 source). +- Because AGPL-3.0 is the strongest copyleft here and it is one-way compatible with GPL-3.0, the + **combined work as distributed (the released .zip / the installed extension) is governed by the + GNU Affero General Public License, version 3** — see [`licenses/AGPL-3.0.txt`](licenses/AGPL-3.0.txt). + The GPL-3.0 text is included at [`licenses/GPL-3.0.txt`](licenses/GPL-3.0.txt). + +MIT-licensed code stays MIT-licensed (MIT is compatible with, and may be included in, an +AGPL/GPL work); the copyleft obligations attach to the combined distribution. + +## What that means if you redistribute + +If you distribute this project (or a modified version), the AGPL-3.0 / GPL-3.0 terms require you to: + +1. **Keep the license texts and notices.** Ship `LICENSE`, `LICENSING.md`, `THIRD-PARTY-NOTICES.md`, + and `licenses/` intact, and preserve the copyright/permission headers inside the bundled files. +2. **License your combined work under AGPL-3.0** and make **complete corresponding source** available + to the people you distribute to (this repository is that source for the JavaScript; see + `THIRD-PARTY-NOTICES.md` for where to obtain the source of the compiled engine binaries and of the + neural-network models). +3. **Do not add further restrictions** beyond those the licenses allow. + +## Corresponding source + +- This Git repository **is** the corresponding source for all of the project's own JavaScript/HTML/CSS. +- The **Stockfish** and **Fairy-Stockfish** engines are shipped as pre-compiled WebAssembly. Their + corresponding C++ source, and the source used to produce the WebAssembly builds, are available from + the upstream projects listed in `THIRD-PARTY-NOTICES.md`. +- The **Maia** neural networks (Maia-1, Maia 2200, Maia-3) are trained models. Their training code, + and where applicable the model weights in their original form, are available from the upstream + projects listed in `THIRD-PARTY-NOTICES.md`. + +## Note on AGPL-3.0 §13 (network use) + +The Maia-3 component is AGPL-3.0, whose §13 requires that users **interacting with a modified version +over a network** be offered its source. In this project Maia-3 runs **locally in the user's own +browser** (an offscreen document); it is not offered as a network service. §13 is therefore not +expected to be triggered by ordinary use of this extension. The ordinary copyleft obligations above +(source-on-distribution, license text, no added restrictions) still apply because the model and its +derived code are distributed. + +*This file is a good-faith summary, not legal advice. If in doubt, consult a lawyer or the individual +upstream licenses.* diff --git a/README.md b/README.md index f3ed6f45..53380074 100644 --- a/README.md +++ b/README.md @@ -1,56 +1,771 @@ -![alt text](https://raw.githubusercontent.com/AlexPetrusca/Mephisto/master/res/mephisto_banner_lowercase.png) +![Mephisto](https://raw.githubusercontent.com/AlexPetrusca/Mephisto/master/res/mephisto_banner_lowercase.png) -Mephisto is a browser extension that provides next-best-move analysis and can automate gameplay on Chess.com and Lichess. +**Real-time chess analysis and automated play on Chess.com, Lichess, BlitzTactics, TakeTakeTake and ChessBase +Tactics.** Mephisto reads the position straight off the page, runs **Stockfish** (NNUE), **Fairy-Stockfish** or +**Maia** entirely in your browser — no server, no account — and draws the best move on the board, or plays it for you +with timing and move choices tuned to look human. -

- -

Mephisto crushing some Puzzle Rush in real-time

-

+Click the toolbar icon to toggle a floating panel over the board. Unlike a normal extension popup it stays open while +you click and play, so analysis and autoplay keep running for the whole game. -## Getting Started +![Analysis with five candidate lines drawn on the board](docs/analysis-lines.png) - - - -     - - - -
-
+[Fair play](#fair-play--read-this-first) · [Install](#install) · [Engines](#engines) · [Features](#features) · +[Sites](#supported-sites) · [Settings](#settings-reference) · [Footprint](#page-footprint) · [Roadmap](#roadmap) -Click the Mephisto icon to open its popup window. It will automatically detect and analyze the current chess position on the page. +--- -For quick access, pin Mephisto to Chrome’s toolbar: -1. Click the puzzle icon next to Chrome’s address bar. -2. Find "Mephisto Chess Extension" and click the pin icon next to it. +## Fair play — read this first -Note: The popup window will close if you click outside of it. To keep it open, right-click the pinned Mephisto icon and select "Inspect Popup." +**Using this in a live game against another person violates the Terms of Service of every chess site.** Account +closures are typically permanent, applied at the device and payment level (so your other accounts go too), and +ratings, prizes and tournament results get rolled back. -For more details, visit the [Getting Started](https://github.com/AlexPetrusca/Mephisto/wiki/Getting-Started) guide. +**This extension cannot make you undetectable.** What catches engine users is server-side and behavioural: move +agreement measured over many games, think-time distributions that look nothing like a person's, accuracy that doesn't +fit your rating history. Those are statistical and aggregated across your account — they don't care what your DOM +looks like. The anti-detection work here addresses one narrow thing, *passive client-side fingerprinting*: a site +noticing the extension is installed. Even [the people writing detection for +it](https://github.com/AlexPetrusca/Mephisto/issues/35) call that a corroborating signal that shouldn't trigger a +sanction alone. Reducing your footprint changes a footnote in a case file, not the case. -## How to Develop Locally -Set up a local install: -1. Clone the repo -2. Navigate to `chrome://extensions` through the Chrome address bar -3. Enable developer mode -4. Click on "Load unpacked" and select the cloned repo folder -5. Mephisto Chess Extension is now installed +**Genuinely good for:** reviewing your own finished games · studying openings and endgames · puzzles and tactics · +engine development and benchmarking · analysis boards and offline play · unrated games where your opponent knows. -Test a code change: -1. Navigate to `chrome://extensions` -2. Reload Mephisto Chess Extension -3. Reload the webpage you want to test on -4. Test the changes +You are responsible for how you use this. -For technical details, see [Technical Overview](https://github.com/AlexPetrusca/Mephisto/wiki/Technical-Overview). +--- +## Why this fork -## How to Contribute -Thank you for your interest in contributing to Mephisto! There are many ways to contribute, and we appreciate all of them. +An **actively maintained** continuation of [Mephisto by Alex +Petrusca](https://github.com/AlexPetrusca/Mephisto). Installed from upstream today it detects nothing — the 2026 +Chess.com and Lichess redesigns broke every scraper. This fork revives it and goes well past it. Everything the +original did still works. -Ways to Contribute: -- Help contribute ideas to Mephisto -- Help identify and document bugs with Mephisto -- Implement requested features through PRs -- Fix identified bugs through PRs +New here: + +- **Engines** — modern **Stockfish dev / 18**, the human-like **Maia** and **Maia-3** nets, and an **Elo cap**. +- **Playing like a person** — **Humanize**, **Clock Mode** and **Mirror Time**. +- **Automation** — **Safe Premove**, **Pondering**, **Help Mode**, **Manual Mode** and rebindable **hotkeys**. +- **Beyond the engine** — the **Opening Explorer**, an **endgame tablebase** and the **puzzle database**. +- **On screen** — the **eval bar**, the **eval history graph**, **screen reading** and a **playable panel board**. +- **Coverage** — **Chess.com variants**, **TakeTakeTake**, **Chess960** and **fourteen languages**. +- **Under the hood** — a **zero-iframe panel** with no page-visible extension URLs, move-correctness guards, + copy FEN/PGN and settings export/import. + +--- + +## Install + +Distributed as an unpacked extension, not through the stores. + +1. Download or clone this repository. +2. Open `chrome://extensions` and enable **Developer mode**. +3. **Load unpacked** → select the repository folder. +4. Pin it: puzzle icon right of the address bar → pin "Mephisto Chess Extension". + +### Which download? + +Every [release](https://github.com/IchNukeDichWeg/Mephisto/releases) carries two archives: + +| | | | +|---|---|---| +| `mephisto-.zip` | **~585 MB** | **First install, always.** Everything, engines included. | +| `mephisto--update.zip` | **~6 MB** | **Already have it.** Code only — extract *over* your existing folder. | + +Nearly all of the full archive is bundled engines: 874 MB of neural nets and WASM under `lib/engine`, plus 13 MB of +onnxruntime under `lib/ort`. Those change on almost no release, so the update archive leaves them alone and carries +only the ~1 MB of extension code — about a hundredth the download. + +> ⚠️ **Extract the update over your existing install, never into an empty folder.** Without the engines it cannot +> run. If you do it anyway the panel says so rather than failing obscurely — it checks for the bundled engines at +> startup and tells you to fetch the full archive. + +**Extract in place.** Chrome derives an unpacked extension's id from its folder path, so replacing files in the +folder you already loaded keeps the same id — and native engines, which are registered against that id, keep +working. Unpacking into a *new* folder changes the id and means re-running the native-host installer. + +To pick up a change: reload on `chrome://extensions`, then reload the game tab. The panel checks this repository for +a newer release at most once every 12 hours, from the service worker, so the chess page never makes the request. + + +### Automatic updates (opt-in) + +Chrome never updates an extension you loaded yourself, so Mephisto can do it for you instead — **Settings → General → +Updates**. It is **off by default**, and nothing about it runs until you switch it on. + +Set-up is three steps, once: + +1. **Automatic Updates → On.** Chrome asks for permission to download from this repository's releases. Refusing + leaves the switch off. +2. **Choose Extension Folder** → pick the folder you loaded as an unpacked extension. Chrome remembers it. +3. **Install Update** when one is offered. + +After that it is one button. It downloads the ~6 MB update archive, writes it over that folder and reloads the +extension — the same *extract in place* described above, so your extension id survives and native engines keep +working. Reload any game tab you had open afterwards. + +Once all three are in place you don't have to come back here at all: the panel's own update notice becomes the +button. It reads *"Update available — v… — click to install"* and does the whole thing. With anything missing it +stays what it always was, a link to the releases page, because there would be nothing to click that would work. + +What it will not do: + +| | | +|---|---| +| Install anything by itself | It checks and it tells you. Files are only written when you press **Install Update**. | +| Touch the bundled engines | The update archive doesn't contain them, so `lib/engine` and `lib/ort` are left alone. | +| Write into the wrong folder | A folder is rejected unless its `manifest.json` is this extension's. | +| Apply a broken download | The whole archive is unpacked and checked in memory first. If anything is off — a bad path, a version that disagrees with the release, a missing file the extension needs to boot — nothing is written at all. | +| Anything at all, while switched off | Every button is disabled, the panel stops offering one click, and the installer refuses outright. Switching off records that choice and keeps it, whether or not Chrome agrees to hand the permission back. | + +> The permission is scoped to this repository's release downloads, not to github.com. You can see it, and take it +> back, on `chrome://extensions` — or just switch Automatic Updates off, which hands it back for you. + +Updating by hand still works exactly as before, and is still the whole story if you'd rather not grant anything. + +--- + +## Engines + +Everything runs locally via WebAssembly — no server, no account, nothing leaves your machine. + +| Engine | Notes | +| --- | --- | +| **Stockfish dev NNUE** | Latest development build. Default. | +| **Stockfish 18 / 18 Small NNUE** | Full dual-net build (large net ships split and is stitched at load), or the lighter net. | +| **Stockfish 11 HCE** | Classical eval, no NNUE — light and fast. | +| **Fairy-Stockfish 14 NNUE** | Required for [variants](#variants); each variant has its own bundled net. | +| **Maia-3** | Human-*like*, not throttled: a transformer conditioned on a rating you set live, **600–2600**. | +| **Maia** | The original Maia-1 nets, one per band (**1100–1900**, plus a **2200**). | +| **Tetrarch (4-player)** | Four-player chess only — see [four-player chess](#four-player-chess). Needs a one-time install. | +| **Remote / native** | A real engine binary outside the browser — see [full-power engines](#full-power-native-engines-optional). | + +Maia-3 with the 600-2600 rating slider Atomic on Lichess, analysed by Fairy-Stockfish + +*Maia-3's live rating slider · Atomic analysed by Fairy-Stockfish* + +Illegal scraped positions (missing king, wrong side in check, back-rank pawns) are blocked before they can crash the +engine, and a crashed engine auto-restarts, capped at 3 attempts. + +**Strength cap** — limit any Stockfish/Fairy engine to a target Elo with an engine-aware slider whose stops follow +that engine's real `UCI_Elo` range. Both ends mean full strength. + +### Variants + +**Chess960** works on every mainline Stockfish via `UCI_Chess960`, including every castling case. Fairy-Stockfish +adds all of Lichess's variants (Crazyhouse, King of the Hill, Three-Check, Antichess, Atomic, Horde, Racing Kings) +plus Chess.com's **Duck, Minihouse, Seirawan and Chaturanga**. The ↻ button beside the variant selector detects the +variant and switches engine for you. + +Duck, Minihouse, Seirawan and Chaturanga have nets but the bundled chess.js can't replay them — the panel says so +instead of analysing the wrong position. + +--- + +## Features + +### Analysis + +- **Multiple lines** — top 1–5 candidates (MultiPV), each drawn with its evaluation. +- **Eval bar** — vertical bar beside the board, from your perspective, plus an **eval history graph** shaped like + Lichess's, marking where the opening, middlegame and endgame begin (ported from scalachess's `Divider`). +- **Threat analysis** — the opponent's strongest reply, so you see what they're threatening. +- **Move confidence** — how much better the best move is than the second: `clearly best (+3.7)`, `+0.35 over #2`, + `several equal`, `only move`. Read off the MultiPV lines already on screen, so it costs no extra search. +- **Explain moves** — names the tactic behind the choice (fork, promotion, winning capture, mate). Deliberately + conservative: pins, skewers and discovered attacks can't be established from the position alone, so it stays quiet + rather than guessing. +- **Opening Explorer** — how humans played this opening (Lichess database): the name, the most-played replies with + their win/draw/loss split, and coloured arrows. Masters, all Lichess, or a club band. Lichess requires a personal + API token on this endpoint now — see the setting of that name; Game Review names openings without it, from its own + bundled table. +- **Read a position off the screen** — the camera button captures the tab, finds the board and loads it. Any site: a + video, a diagram, an image. Nothing is uploaded. **Follow screen** re-reads twice a second so a board playing + elsewhere keeps the panel in step. +- **Playable panel board** — click or drag to walk a line, with underpromotion. Every move is kept as a line you can + click back into. + +Three candidate lines, each with its own coloured arrow The opening explorer, with each book move drawn on the board + +*Three candidate lines, each its own arrow · the explorer's book moves on the board* + +![Reading a position straight off a YouTube video](docs/read-from-screen.png) + +*Reading a position straight off a YouTube video — a board reading is a guess and says so, naming its least-confident +squares (`least sure: e4 pawn 62%`).* + +### Game review + +Analyse finished games on the extension's own page — **Settings → Game Review**. Paste a PGN, load a +`.pgn`, or fetch a player's recent games from Chess.com's public archive. Nothing is uploaded: the text +stays in the tab and the search runs in the extension's own engine. + +- **Any engine, at your budget** — the bundled WASM Stockfishes, or a native host at full power. A + **depth** is reproducible (the same depth is the same answer on any machine) and is the default at 16; + a **time per move** defaults to 1s. Native hosts take either. 1–10 candidate lines, your own thread and + hash counts. +- **What you actually gave up** — every position is searched once, so the score before a move and the + score after it come from the same search at the same budget, and the played move's rank in the engine's + own list is exact. +- **Accuracy and move quality** — Lichess's win% and accuracy formulas, and the same 30/20/10 bands the + panel judges live moves by, so a review agrees with what the panel said at the time. Best, Excellent, + Good, Book, Forced, Inaccuracy, Mistake, Blunder. +- **Eval graph** with the **opening / middlegame / endgame** boundaries marked on Lichess's own divider. + Click anywhere on it to jump the board there; blunders and mistakes are dotted. +- **Openings named offline** from a bundled copy of [lichess-org/chess-openings](https://github.com/lichess-org/chess-openings) + (CC0) — 3,810 lines keyed by *position*, so a transposition is named correctly and nothing is fetched. +- **Think time** read from the `[%clk ...]` comments Chess.com and Lichess both write, and **titles and + ratings** from the PGN's own tags: `GM Carlsen (2839)`. +- **Human model (optional)** — a second pass with Maia, which predicts what a *human* of a chosen rating + plays rather than what is best. Maia 1 across its bands (1100–2200) or Maia 3 on a rating dial. It + reports where your move sat in Maia's **own ranking**, not a yes/no. +- **Human likeness (optional, off)** — the whole game read by that second judge instead: how expected each + move was rather than how good, and the moves the engine ranked first that the human model never saw + coming. +- **Across games** — switch **Review every game** on and the whole file is analysed against one engine + load, with each player's numbers pooled over all of it. One game cannot answer a fair-play question; a + season of them starts to. +- **Fair-play indicators** — an **overall estimate** per player, then the lines it is drawn from: the + engine-match rate over the moves that were a real choice (book, forced and recapture moves excluded), + the rate in sharp positions and per phase, the longest unbroken engine streak, how uniform the accuracy + is, whether the longer thinks went to the harder positions, and how far the human model was from the + played move. Four levels with a key that says what each means. **Measurements, never a verdict** — the + page says so, and the estimate says what it is worth as well as what it says. +- **Export** — the report exactly as it looks on the page: same markup, same stylesheets inlined, board + and pieces embedded, the full move table and the PGN. One file, no scripts, nothing to fetch, opens + anywhere. + +![The game review page](docs/game-review.png) + +### Automated play + +- **Autoplay** — plays the engine's move for you. **Help Mode** draws the arrows instead and overrides it. +- **Safe Premove** — while the opponent thinks, certifies a reply to their *predicted* move: the same move at + depth 13, depth 14 and the latest depth. An exact match fires instantly; anything else searches normally, so a + wrong guess costs nothing. + Forced moves and true recaptures queue as a real site premove, and an illegal one auto-cancels. On Chess.com, a + line forced *two* moves deep queues both replies at once. +- **Pondering** — searches the opponent's whole think at full threads over their top 5 replies. Off, their turn is + capped at two threads (not one: premove certification needs depth 14). +- **Play Book Moves** — plays the opening from the Explorer, weighted-random among popular replies. Needs 20+ games + and within 40cp of the engine's best, so variety never costs you a worse move. +- **Endgame tablebase** — at 7 pieces or fewer the position is *solved*, so it asks Lichess's Syzygy tables for the + perfect move and outranks both engine and book. Off by default: it sends the position to a third party. +- **Manual Mode** — thinks indefinitely and plays nothing until you press the play key. +- **Background Play** (off by default) — moves fire only while the tab is focused and visible; a move that comes due + while you're away is deferred and re-issued when you return. + +### Humanize + +![The move mix and move-quality thresholds, with live accuracy estimates](docs/humanize.png) + +Seven shares set how often it plays the **top move**, a **2nd/3rd/4th line**, an **inaccuracy**, a **mistake** or a +**blunder**; separate thresholds set how far each may stray in centipawns, with a live [Lichess +accuracy](https://lichess.org/page/accuracy) estimate of the win-chance drop. Defaults sit on Lichess's own +boundaries — 110cp inaccuracy, 230cp mistake, 377cp blunder. Nothing past the blunder threshold is played, and +blunders never fire in a decided game. + +Timing follows: quick on obvious moves and openings, long thinks in critical positions, and an instant reflex *only* +for true recaptures and forced moves — snapping off a piece that merely moved in to attack looked suspiciously fast. +A countdown shows what kind of move is coming. + +**Clock Mode** budgets each move off the page clock (~time/30 + 60% of the increment); **Mirror Time** paces to the +opponent's last spend −10%. Both size the search to the time they'll spend, so the wait becomes a deeper move. + +**Pace to Clock** is separate and off by default. Clock Mode paces the *search*; this paces the *simulated* delay — +the think pause and the cursor travel — which is what actually costs you time in a scramble. With clock to spare +your settings are used exactly as they are: it only ever makes a move shorter, never slower, and never below the +point where the click stops looking like a hand moved it. + +> **Priority** — *Time:* Mirror ▸ Clock ▸ Humanize ▸ Search Time. *Move:* Book ▸ Humanize ▸ engine best. + +### Puzzles + +3999 — as high as the Lichess puzzle rating goes The hotkeys page, each action rebindable + +*3999 is the ceiling — there is no higher number Lichess will show you · every action rebindable* + +![Hardest (+600) puzzles solved back to back, from the database rather than searched](docs/puzzle-database.gif) + +*Hardest (+600) puzzles back to back, from the database rather than searched. +[The full clip](docs/puzzle-database.mp4) runs a minute and a half at higher quality.* + +**Puzzle Mode** optimises for solving speed — every move is one it actually searched, and the opponent's scripted +reply is never analysed. A puzzle page ships no move list, so the position is rebuilt from the pieces alone: en +passant is recovered from the last-move highlight and castling rights from the king and rook still at home, because +without them an ep capture is illegal and nobody can castle in *any* puzzle. + +**Puzzle database** — a searched move is not always the puzzle's answer; a puzzle has one line that scores, and an +objectively stronger move still fails it. Import Lichess's database and the panel looks the position up instead: on a +hit the whole solution is known, so it plays it with **no search at all**. Works on Training, Storm and Racer. + +Lichess only for now, and it doesn't even ask elsewhere — that file is built from Lichess games, so a Chess.com +position would be a guaranteed miss. + +**Chess.com puzzles.** The reader shipped in v3.1.207 — the same settings page, the same import button, and the +format is detected from the file, so there is nothing extra to choose. Importing both databases gives you both: they +key on the position, so neither overwrites the other. A database of **620,000+ Chess.com puzzles with their +solutions** will be published once [the upstream pull request](https://github.com/AlexPetrusca/Mephisto/pull/37) is +merged; it covers rated tactics and the daily archive. + +
+Building your own Chess.com puzzle CSV — the exact format the importer accepts + +**The header row is required and must begin with `fen3`.** That is the only thing that tells the importer this is a +Chess.com file rather than a Lichess one — without it the rows are read as Lichess and every one is discarded. + +``` +fen3,id,rating,initialFen,tcnMoveList,colorOfUser,pgn,passRate,averageSeconds,gameLiveId,gameId +``` + +| # | column | required | meaning | +|---|---|---|---| +| 0 | `fen3` | **yes** | board + side to move + castling. Only the first two fields are used as the key. | +| 1 | `id` | **yes** | puzzle id, or `daily-N` for archive puzzles — the prefix switches the move format | +| 2 | `rating` | no | ignored on import | +| 3 | `initialFen` | daily only | full 6-field FEN; used to replay the SAN of a `daily-` row | +| 4 | `tcnMoveList` | **yes** | solution in Chess.com TCN — **or SAN for `daily-` rows** | +| 5 | `colorOfUser` | tactics | `white`/`black`, the side solving. Empty for daily. | +| 6+ | `pgn`, `passRate`, `averageSeconds`, `gameLiveId`, `gameId` | no | never read, but the columns must be in this order | + +**Whose move comes first differs by row type**, and getting it wrong shifts every solution by a ply: + +- **Rated tactic** — `fen3` is the *opponent* to move and `colorOfUser` is the solver, so the first move is the + opponent's setup move. The importer applies it and keys on the position after it, exactly as it does for Lichess. +- **`daily-` row** — no setup move and no `colorOfUser`. The side to move in `fen3` **is** the solver and the line + starts immediately. + +**TCN** is two characters per move over this alphabet, index `0` = `a1` and `63` = `h8`: + +``` +abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?{~}(^)[_]@#$,./&-*++= +``` + +A promotion pushes the destination past index 63: the piece is `"qnrbkp"[(to - 64) / 3]` and the real destination is +`from ± 8 + ((to - 64) % 3) - 1`, the remainder carrying the file shift (capture left, straight, capture right). + +**Three rules your generator must respect:** + +1. **Write real CSV.** The `pgn` column contains literal newlines and doubled `""` quotes. The importer reads these + rows with a proper streaming parser, so quoting must be correct — but that also means a naive line-per-row + generator will produce a file it cannot read. +2. **Key on the first three FEN fields only.** Halfmove and fullmove counters vary between sources for the same + position; they are not part of what a puzzle *is*. +3. **Branch on `id` before choosing an encoding.** A `daily-` row holding TCN, or a rated row holding SAN, is + silently dropped rather than mis-decoded. + +Rows the importer cannot make sense of are skipped, not fatal — the status line reports how many of the rows read +were kept. +
+ +
+Importing the puzzle database — about a gigabyte, roughly half an hour, once + +Not bundled: the release zip is large enough already. Download `lichess_db_puzzle.csv.zst` from +[database.lichess.org](https://database.lichess.org/#puzzles), decompress it (`unzstd lichess_db_puzzle.csv.zst` — +browsers have no zstd decoder, which is why this step is yours), then pick the `.csv` under **Settings → General → +Puzzle Database**. About six million positions, with a live count as it goes. Nothing is sent anywhere; it lives in +the extension's own IndexedDB. If the import is interrupted nothing is lost — run it again and it fills in the rest. +
+ +### The panel + +Drag by the title bar, close with ✕. **Compact (▣)** collapses it to the status line, move and score; **minimize +(–)** hides it entirely behind a badge while autoplay keeps running. Quick Settings edits every setting inline. +**Re-detect (↻)** rescans the page. **Copy FEN / PGN** — a game that began from a custom start exports with +`SetUp`/`FEN` tags, so it reads back as the same game. A **grid button** takes a pasted FEN to analyse any position; +**⧉** opens the position on Lichess. An **engine health dot** shows whether a native host answered, because a missing +host otherwise just looks like a panel that never evaluates. + +--- + +## Supported sites + +![TakeTakeTake, whose board is a WebGPU canvas with no DOM to scrape](docs/taketaketake.png) + +*TakeTakeTake, whose board is a WebGPU canvas with no DOM to scrape.* + +| Site | Analysis | Autoplay | Premove | Puzzles | Online | Variants | +|---|:---:|:---:|:---:|:---:|:---:|---| +| **Chess.com** | ✅ | ✅ incl. Play Bots | ✅ | ✅ Rush / Storm | ✅ | 3-Check, KotH, Crazyhouse, Antichess, Atomic, Horde, Racing Kings, **Duck, Minihouse, Seirawan, Chaturanga** + Chess960, **4-player** | +| **Lichess** | ✅ | ✅ incl. AI & From Position | ✅ | ✅ Storm · Racer · Training | ✅ live & correspondence | All Lichess variants + Chess960 | +| **TakeTakeTake** | ✅ | ✅ bot games | ✅ | — | ✅ Lichess-backed | — | +| **BlitzTactics** | ✅ | ✅ | — | ✅ puzzle streams | — | — | +| **ChessBase Tactics** | ✅ | — | — | ✅ Solve / Sprint | — | — | + +--- + +## Full-power native engines (optional) + +**You don't need this.** The bundled WASM engines work with zero setup. But WASM is sandboxed — it can't use all your +cores or much RAM, so it runs **5–70× slower** than a native binary. Point Mephisto at a native Stockfish and Chrome +**auto-launches** it; there is no server to run. Two extra engines appear in the dropdown, running at all cores and +up to 2 GB hash. + +
+Setup — macOS, Linux, Windows + +You need a native **Stockfish** binary (optionally **Fairy-Stockfish** for variants), **Python 3** with +`python-chess`, and your **extension ID** — open `chrome://extensions` with Developer mode on and copy the long id +under *Mephisto*. + +> ⚠️ An unpacked extension's id **changes when you reload it**. If native engines stop working after a reload, re-run +> the install command with the new id. + +**macOS** +```bash +brew install stockfish fairy-stockfish +python3 -m pip install chess +native-host/install-native.sh --ext-id YOUR_EXTENSION_ID +``` +A binary downloaded from the web is quarantined by Gatekeeper — the installer clears that for its own copy. + +**Linux** +```bash +sudo apt install stockfish +python3 -m pip install chess +native-host/install-native.sh --ext-id YOUR_EXTENSION_ID +``` +For Fairy-Stockfish, install it or pass `--fairy /path/to/binary`. + +**Windows** — the shell installer is macOS/Linux only; native messaging needs a registry key, so this is manual: +install Python and `pip install chess`, download `stockfish.exe`, copy `native-host/uci-native-host.py` somewhere +stable with a `sf-native.path` file next to it holding the full path to the exe, write a host manifest +`com.sf_native.host.json` (underscores — Chrome rejects hyphens) pointing at a `.bat` that runs the host script with +`"allowed_origins": ["chrome-extension://YOUR_EXTENSION_ID/"]`, and add registry key +`HKCU\Software\Google\Chrome\NativeMessagingHosts\com.sf_native.host` = the manifest path. Prefer the bundled WASM +engines unless you're comfortable with the registry. + +The installer registers the host for **Chrome, Brave, Edge, Chromium and Vivaldi**. Firefox isn't supported for +native engines. Any native build unlocks full speed — pick the one matching your CPU (Apple Silicon, AVX2, BMI2); +the gap between native builds is small, the jump from WASM to any of them is huge. +
+ +--- + +## Four-player chess + +Chess.com's **4-player chess** (`/variants/4-player-chess`), analysed by +[Tetrarch](https://github.com/IchNukeDichWeg/Tetrarch) — a purpose-built engine for 14×14 four-seat boards, because +no two-player engine can be bent into one. Pick **Tetrarch (4-player)** in the engine dropdown; the panel switches to +it on a four-player board and back to Stockfish when you leave. + +![Four-player chess on Chess.com, with the 14x14 panel board and the suggested move drawn on it](docs/four-player.png) + +*Teams mode on Chess.com — the panel's own 14×14 board, rotated so you sit at the bottom, with the engine's move +drawn on it and the evaluation bar in team colours.* + +The panel swaps its own board for a 14×14 one with the corners cut, rotated so **you** sit at the bottom whichever +seat you drew, and draws the suggested move as an arrow. The evaluation is normalised to **your team** (Red+Yellow +against Blue+Green), so it means one thing all game instead of flipping sign every seat. Autoplay works. + +> **Teams mode only, for now.** Tetrarch does not search free-for-all, so FFA games are detected and shown but +> not analysed. + +Promotions are played in full: the picker Chess.com opens over the board is found by its shape — a small +panel of four pieces in two rows — rather than by a class name, so a generated class changing cannot make +it click the wrong piece. If nothing matches that shape it plays the move and leaves the piece to you, +which is what it always did. Confirmed from every seat: unlike the board, the picker is *not* rotated per +player, so one reading order serves all four. With **Multiple Lines** above 1 you get an arrow per line on the page board +and on the panel's own 14×14 board, with a colour-matched list of scores beneath it. + +The mode is read from Chess.com's own mode label, which is a guess about someone else's markup — and it decides the +rules the search runs under, since promotion is the 8th rank in free-for-all and the 11th in Teams. When that guess +is wrong, **Mode** in the panel (it takes the Variant row's place for Tetrarch) sets it by hand: *Auto-detect*, +*Teams* or *Free-for-all*. Changing it re-analyses the position already on screen rather than waiting for the next +move. Autoplay also works on the **analysis board**, not just in a game — it's your own board, so playing a line out +on it affects nobody. The lobby and setup pages stay excluded. + +
+Setup — macOS, Linux, Windows + +Tetrarch is the one engine with nothing bundled behind it: it needs a checkout and one run of the installer. Until +then the panel says so under the board rather than pretending to analyse. + +You need **Python 3**, a C compiler, and your **extension ID** — `chrome://extensions` with Developer mode on, copy +the long id under *Mephisto*. + +**macOS and Linux** + +```bash +git clone https://github.com/IchNukeDichWeg/Tetrarch +``` + +```bash +cd Tetrarch && ./setup.sh +``` + +`setup.sh` builds the C core and installs what it needs (Homebrew, apt, dnf or yum). Then, from the Mephisto folder: + +```bash +native-host/install-native.sh --ext-id YOUR_EXTENSION_ID --tetrarch /path/to/Tetrarch +``` + +Drop `--tetrarch` if the Tetrarch checkout sits beside Mephisto's parent folder — that's where the installer looks by +default. It prints `-> tetrarch: ` when it found it and `-- tetrarch: no uci.py at ` when it didn't. + +**Windows** + +Two differences from the above: the C core has to be built as a DLL, and Chrome finds native-messaging hosts through +the **registry** rather than a folder of manifests — so there's a PowerShell installer instead of the shell one. + +Install [MSYS2](https://www.msys2.org), then from its **MINGW64** shell: + +```bash +pacman -S --needed mingw-w64-x86_64-gcc +``` + +```bash +cd /c/path/to/Tetrarch && ./setup.sh +``` + +That produces `build\tetrarch.dll`. Then, from PowerShell in the Mephisto folder: + +```powershell +powershell -ExecutionPolicy Bypass -File native-host\install-tetrarch.ps1 -ExtId YOUR_EXTENSION_ID +``` + +Add `-Tetrarch C:\path\to\Tetrarch` if the checkout isn't beside Mephisto's parent folder. The installer copies the +host into `%LOCALAPPDATA%\Mephisto` and registers it for Chrome, Chromium, Edge, Brave and Vivaldi under `HKCU` — no +administrator rights needed. Python 3 must be on `PATH`. + +> The Windows path is **built and symbol-checked but not yet run on a real Windows machine** — the DLL is +> cross-compiled and verified in CI-style by `win-crosscheck.sh` in the Tetrarch repo, which is not the same as +> someone having played a game on it. If something misbehaves, +> [please open an issue](https://github.com/IchNukeDichWeg/Mephisto/issues/new/choose) — see +> [Contributing](#contributing) for the four stages worth reporting. **WSL** works today with no +> extra steps, since it's the Linux path above. +
+ +--- + +## Languages + +**Settings → Appearance → Language**, applied immediately without a reload. + +English, Deutsch, Español, Français, Português, Italiano, Nederlands, Polski, Türkçe, Русский, 中文, हिन्दी, 日本語, +한국어 — each listed in its own language, because a list written in English doesn't help someone looking for theirs. + +Deliberately **not** Chrome's `chrome.i18n`, which follows the browser's UI locale with no way to override it. One +flat JSON per language under `src/i18n/locales/`, English underneath every other as the fallback. Every string is +translated including the long settings tooltips — the ones explaining what a setting actually does are the ones worth +having in your own language. Engine names, board and piece themes, and chess notation are left alone on purpose. + +--- + +## Settings reference + +The options page — right-click the toolbar icon → **Options**, or the gear in the panel. Quick Settings in the panel +is a subset writing to the same storage. Everything applies to the next move without a reload unless noted. + +
+Engine + +| Setting | What it does | +| --- | --- | +| **Engine** | Which engine analyses the position. The WASM builds need nothing installed; "(local, full power)" entries talk to a real binary and only appear once the native host is installed. Switching reloads the panel — the net and UCI options have to be rebuilt. | +| **Elo** | Caps strength via `UCI_LimitStrength` + `UCI_Elo`. The range follows the engine; out-of-range values are ignored rather than clamped. `0` means no cap. | +| **Variant** | How the position is read and analysed. Auto-detected on variant pages. Chess960 is the exception: every mainline Stockfish plays it, so it survives an engine switch. | +| **Search Time** | How long the engine thinks when nothing else sets the pace. Clock Mode, Mirror Time and Humanize all override it; recaptures and forced moves ignore it entirely. | +| **Fallback Poll Interval** | Position changes are event-driven and instant; this is only a slow safety net that repairs a missed update. Lowering it buys nothing. | +| **Multiple Lines** | How many candidates the engine reports. The search splits across them, so depth drops — 1 is strongest. Humanize raises it automatically when it needs alternatives. | +| **Threads** | The default leaves one core for the browser. Capped at 2 on the opponent's turn unless Pondering is on. | +| **Memory** | Transposition-table size. In-browser engines are clamped to 512 MB whatever the slider says — that's the WebAssembly heap limit, not a choice. Native engines get the full value. | +| **Panel Style** | **Floating panel** is the draggable window; it lives in the page, so a site can detect it more easily, and Autoplay and Premove need it. **Toolbar popup** renders in the browser's chrome and leaves no trace in the page, but closes when you click the board — analysis only. | +
+ +
+Analysis and display + +| Setting | What it does | +| --- | --- | +| **Show Computer Evaluation** | Score, depth, nps and the win/draw/loss split under the panel board. | +| **Show Threat Analysis** | A red arrow for the opponent's best reply. Costs a second search per position. | +| **"Hand & Brain" Mode** | Mephisto plays the *Brain* — names only the piece type. It deliberately withholds the move, so Autoplay does nothing while it's on. | +| **Explain Moves** | Names the tactic behind the choice; silent when nothing is certain. | +| **Hide Opponent Name** | Blurs their username and avatar so a screenshot doesn't expose a real person. Local and cosmetic — but it's the one option that adds a style element to the page, which is why it's off by default. | +| **Opponent Mistake Alert** | A toast when the opponent plays an inaccuracy, mistake or blunder, by the same Lichess win% method the move mix uses. Only fires when both positions were searched deep enough to trust. | +
+ +
+Automated play + +| Setting | What it does | +| --- | --- | +| **Autoplay** | Plays the engine's move on the site's board by clicking. Everything else that plays a move needs this on. | +| **Premove** | Certifies a reply to the opponent's predicted move; an exact hit is instant. A reply that could never be legal after some other move is queued as a real site premove. | +| **Pondering** | Full threads during the opponent's turn across their top five replies. Costs CPU continuously — it pairs best with Premove. | +| **Endgame Tablebase** | Perfect play at ≤7 pieces, outranking engine and book. Off by default: it leaves your machine. Never delays a move. | +| **Lichess API token** | Lichess put the opening explorer behind OAuth — without a token it answers 401 and both Opening Explorer and Play Book Moves stop working. Make a personal token at [lichess.org/account/oauth/token/create](https://lichess.org/account/oauth/token/create) with **no scopes** ticked; the explorer only needs to know a request has an owner. Stored on your machine like any other setting, sent nowhere but lichess, and deliberately left out of Copy Diagnostics and of an exported settings file. | +| **Opening Explorer** / **Opening Database** | Human opening data and which games it comes from. *Masters* is the cleanest play; the Lichess sets look more like a normal opponent. Read-out only. | +| **Play Book Moves** | Plays from the book instead of the engine's pick — an engine that always opens the same way is itself a tell. 20-game floor, 40cp check. If the lookup is late the engine's move is played. | +| **Background Play** | Off, moves fire only while the tab is focused. On keeps everything running hidden — Chrome throttles silent background tabs, so the tab is marked as playing audio and shows a speaker icon. | +| **Help Mode** | Arrows on the site's board, plays nothing. Overrides Autoplay. | +| **Humanize** / **Clock Mode** / **Mirror Time** | Which move is played, and how long it takes. See [Humanize](#humanize). | +| **Pace to Clock** | Shrinks the simulated think pause and cursor travel when the clock gets short. Off by default; never lengthens a move. | +| **Manual Mode** | Thinks indefinitely; plays only when you press the play key. Overrides Clock/Mirror/Humanize. | +| **Puzzle Mode** / **Puzzle Database** | See [Puzzles](#puzzles). Puzzle Mode turns itself on when you open a puzzle page and off when you leave — unless you set it yourself, which is never overridden. | +| **Python Backend** | Moves the real pointer via a local Python helper instead of synthetic clicks. Needs `mephisto-clicker.py` and PyAutoGUI permissions. Almost nobody needs this. | +
+ +
+Humanize tuning, hotkeys, appearance + +| Setting | What it does | +| --- | --- | +| **Move Mix (%)** | Seven categories, must total 100. Giving any share to *Third line* or worse forces a wider search so a move that bad exists to pick — which costs depth. A pure Top + Second mix stays cheaper. | +| **Thresholds (cp)** | How much worse than best each category may be. Each value is the top of its band and the one above is the bottom, so bands tile without gaps. | +| **Think Time / Variance** | The minimum delay after the position is evaluated, plus a random extra. Constant identical timing is itself a tell. | +| **Move Time / Variance** | The *total* wall clock for one move, first click to last — promotions get a third leg and are budgeted for. | +| **Hotkeys** | One rebindable key per action, live on the game page while the panel is open. Click a key and the next press becomes the binding; **Esc** cancels, **Backspace** clears. Defaults are single letters, play-move is Space. Clashes with a site shortcut can be rebound to any Ctrl/Alt/Shift/Meta combination. | +| **Pieces / Board / Coordinates** | The panel's own board only — the site's board is never restyled. | +| **Dark Mode / Language** | Theme and language for the panel and the settings page. | +| **Four-player Mode** | Tetrarch only, in the Variant row's place. Which rules a four-player board is played under — *Auto-detect* reads Chess.com's mode label, *Teams* and *Free-for-all* override it. See [Four-player chess](#four-player-chess). | +| **Automatic Updates** | See [Automatic updates](#automatic-updates-opt-in). Off by default. On, it asks Chrome for permission to download this repository's releases, then updates the extension in place at the press of a button — the bundled engines are never touched. | +| **Verbose Logging · Copy Diagnostics** | Diagnostics, not play. The trace is quiet while the game tab is focused; this turns it on. **Copy Diagnostics** (panel → Engine, or **D**) copies version, engine, what was detected, why the last move was or was not played, and the recent trace — with no addresses and nothing identifying, so it can go straight into a bug report. It also carries the last five **worker cold starts**, timed and written to storage rather than traced, because the trace lives in the worker and a worker that was slow to start is exactly the case where it has nothing to say. | +| **Game Review** | Its own page. Analyse a PGN, a `.pgn` file, or a player's recent Chess.com games; see [Game review](#game-review). | +| **Restore Defaults · Export · Import** | Reset everything on the page (not the puzzle database or hotkeys); write every setting including hotkeys and tuning to JSON, and read one back. Values that no longer exist are ignored. | +
+ +--- + +## Page footprint + +**Toolbar popup** leaves **zero page footprint** — it renders in the browser's own chrome, so the page has no handle +to it at all. It closes when you click the board, so it's analysis only; Autoplay and Premove need the floating +panel. Switch under **Settings → General → Panel Style**. + +While the **floating panel** is in use, its footprint is minimised: + +- **No iframe.** An iframe is a *browsing context* — counted by `window.length`, throwing on cross-origin access, + which a closed shadow root cannot hide. The panel renders directly in the page's isolated world, and the WASM + engine moved to an **offscreen document** that still gets the cross-origin isolation the pthread builds need but + that the page cannot see or count. +- **No extension URLs reach the page.** `web_accessible_resources` is gone from the manifest. Markup, CSS, board + textures and piece images are fetched extension-side and injected as inlined bytes or `data:` URIs, so no + `chrome-extension://` URL appears in the DOM **or in Resource Timing**, and the id can't be read back. +- **Closed shadow root** under one attribute-less host node — `document.querySelector('[id^="mephisto-"]')` finds + nothing and `host.shadowRoot` is `null`. +- **No branded page globals** — MAIN-world probes for canvas boards set no `window.*` flag and talk over + per-session random event channels, so there's no fixed name to fingerprint. +- **Human-shaped clicks** — a bare *from → to*, no lead click on an empty square, randomised timings, landing on a + center-weighted distribution within each square, preceded by an eased jittered cursor path inside the Move Time + budget. +- **No config in the site's storage** — settings live in `chrome.storage.local`. Two values do sit in page storage + because they're read while the panel is built (panel geometry, a start-position cache); neither is named after the + extension nor holds a setting. + +These reduce *passive* fingerprinting only. See the [disclaimer](#fair-play--read-this-first). + +--- + +## Roadmap + +No schedule — added whenever I feel like it. Checked means shipped. + +### Planned + +- [ ] **More engines** — the lineup covers *strong* and *human-like* and not much between. Variety of character, not + more strength. **lc0 (Leela)** in WASM would be for comparing styles, not for strength. +- [ ] **Duck Chess autoplay** — detection and analysis work; the duck-placement step doesn't. +- [ ] **Four-player chess, the rest of it** — Teams mode works, promotions are played and eliminations are + handled. What is left: free-for-all needs engine support, and no real game has yet been seen past an + elimination, so that path is pinned by synthetic positions rather than by having happened. Chaturaji, + 4P Giveaway and Self Partnering are untouched. +- [ ] **Four-player chess on Windows, confirmed** — built and symbol-checked, never run on a real Windows machine. + See [Contributing](#contributing) for the four stages worth reporting. +- [ ] **Short videos and more screenshots** — a premove firing, Humanize pacing a move, the screen reader following a + board. Some of this only makes sense in motion. +- [ ] **Translate the README** — the interface speaks fourteen languages; the documentation still speaks one. +- [ ] **Shrink the footprint further** — what's left is hardening the one rendezvous the MAIN-world probes need and + tightening how scraped positions are sanitised. Being straight about the ceiling: the client side is nearly + exhausted, and it was never the thing that catches people. +- [ ] **ChessBase Tactics arrows + autoplay** — analysis works; drawing and clicking don't. ChessBase renders its own + board with no class to match, and finding it by shape was slow and unreliable. +- [ ] **Bug fixes**, open-ended. Several of the sharpest bugs so far were invisible rather than loud: autoplay that + skipped a move with nothing logged, an engine that never loaded, a veto inverted only for Black. Reports of *"it + did nothing"* are worth more than they sound. +- [ ] **Whatever you want it to do** — most of what's here arrived because something was annoying in a real game. + +**Blocked upstream** — no engine supports these, so there's nothing to build against: Fog of War (imperfect +information), Setup Chess, Spell Chess, Bughouse and Chess-with-Checkers. + +**Looked at and dropped** — *Lichess cloud evaluation.* It's a crowdsourced cache of positions other people's +browsers have already analysed, not a server-side engine, and its coverage is the problem: deep on openings and +popular lines, absent on ordinary middlegames. That's the inverse of where extra depth would change a move, and the +openings are already covered by the [Opening Explorer](#analysis) and book play. Might be worth revisiting for +post-game review, where the hit rate is higher and the eval is context rather than a move to play. + +### Shipped + +- [x] **[Game review](#game-review)** (v3.1.218) — a finished game analysed on the extension's own page: accuracy, + move quality, alternate lines, an eval graph, think time from the clock comments, an optional Maia pass, and + fair-play measurements that deliberately stop short of a verdict. Exports as one self-contained HTML file. + +- [x] **[Automatic updates](#automatic-updates-opt-in)** (v3.1.214, one-click from the panel v3.1.215) — opt-in: + fetches the ~6 MB update archive from this repository and writes it into the extension's own folder in place, so + the id and the native hosts survive. Once it is set up the panel's own update notice installs it. Off by default; + nothing is installed without pressing the button. +- [x] **[Four-player chess](#four-player-chess)** (v3.1.199) — chess.com's 4-player variant, driven by + [Tetrarch](https://github.com/IchNukeDichWeg/Tetrarch); 14×14 panel board, team-relative eval, autoplay. + Teams mode only. +- [x] **Panel and settings rework** (v3.1.199) — two tabs instead of a wall of rows, the game and engine status + moved into the title bar, `−`/`+` steppers for threads, lines and move time, uniform control heights, one + typeface per column, and a settings page grouped into sections. +- [x] **Four-player chess on Windows** (v3.1.200) — DLL build, `.bat` host shim and a PowerShell installer that + registers under `HKCU`. Unconfirmed on real hardware, hence the open item above. +- [x] **Fourteen languages** (v3.1.160) — every string, switchable live in Settings → Appearance. +- [x] **Puzzle database** (v3.1.140) — the Lichess puzzle CSV in IndexedDB; known solutions play with no search. +- [x] **Endgame tablebase**, **move confidence**, **eval history graph** (v3.1.135). +- [x] **Read a position off the screen** and the **playable panel board** (v3.1.124). +- [x] **From-Position capture** and **on-demand nets** (v3.1.125) — an unbundled net downloads on first use; a full + install still works offline. +- [x] **Opening Explorer + book play**, **set up a position**, **auto-recover on DOM changes** (v3.1.119) — if a + site renames its move-list tags, the list is found structurally. +- [x] **Pondering** and **double premove** (v3.1.107). +- [x] **Maia-3** (v3.1.95) — 600–2600 slider, one transformer conditioned on rating; reproduces the + [CSSLab reference](https://github.com/CSSLab/maia3) exactly (~60% move-match to human play). +- [x] **Maia** (v3.1.93) — the original nets, 1100–1900 plus a community-trained 2200. Matches the lc0 reference. +- [x] **Instant reopen with a warm engine**, the **turn switch** (v3.1.92), **human cursor travel** (v3.1.90). +- [x] **Manual mode**, **configurable hotkeys**, **opponent mistake alert**, **self-test button** (v3.1.84). +- [x] **Copy FEN/PGN, compact panel, export/import** (v3.1.73); **native health badge, smart default threads** + (v3.1.55). + +--- + +## Contributing + +**[Open an issue](https://github.com/IchNukeDichWeg/Mephisto/issues/new/choose) for anything** — a bug, a site that +stopped being scraped correctly, an engine that misbehaves, a feature you want, or just an idea. You don't need a +diagnosis or a reproduction; "it stopped playing moves on lichess this morning" is a perfectly good issue. PRs are +welcome too. + +**If the Windows four-player setup fails, an issue is especially useful** — it is built and symbol-checked but has +never been run on a real Windows machine, and native-messaging failures there are silent: Chrome reports the host as +unavailable and says nothing about why. Testing it in stages turns that into something actionable, so please say +which one broke: + +1. `./setup.sh` under MSYS2 produces `build\tetrarch.dll` +2. `python -c "from tetrarch import core"` imports without raising +3. `python uci.py` answers `go` in a plain terminal +4. the panel finds the engine in Chrome + +A report of "stage 3 hangs" is worth far more than "it doesn't work", because each stage has a different cause. + +## License & credits + +This project's own source (and the original [Mephisto](https://github.com/AlexPetrusca/Mephisto) by Alexandru +Petrusca) is **MIT** ([`LICENSE`](LICENSE)). It **bundles copyleft components** — GPL-3.0 engines and nets, and the +**AGPL-3.0** Maia-3 model — so the **combined distribution is governed by AGPL-3.0**. Before redistributing, read +[`LICENSING.md`](LICENSING.md) and [`THIRD-PARTY-NOTICES.md`](THIRD-PARTY-NOTICES.md); full texts in +[`licenses/`](licenses/). + +Built on the work of others, with thanks: + +- **[Stockfish](https://github.com/official-stockfish/Stockfish)** & **[Fairy-Stockfish](https://github.com/fairy-stockfish/Fairy-Stockfish)** (GPL-3.0), run in the browser via the [Lichess Stockfish-web](https://github.com/lichess-org) builds. +- **[Maia](https://github.com/CSSLab/maia-chess) / [Maia-3](https://github.com/CSSLab/maia3)** (CSSLab, University of Toronto; GPL-3.0 / AGPL-3.0) and the **[Maia 2200](https://github.com/CallOn84/LeelaNets)** net (CallOn84; GPL-3.0); **[Leela Chess Zero](https://github.com/LeelaChessZero/lc0)** (GPL-3.0) for the input/policy encoding. +- **Board recognition** — two models from [Chess_diagram_to_FEN](https://github.com/tsoj/Chess_diagram_to_FEN) by Jost Triller (MIT), converted to ONNX; see `lib/engine/vision/`. +- **[ONNX Runtime Web](https://github.com/microsoft/onnxruntime)** (Microsoft; MIT) — in-browser inference. +- **[chess.js](https://github.com/jhlywa/chess.js)** (BSD-2), **[chessboard.js](https://github.com/oakmac/chessboardjs)**, **[jQuery](https://jquery.com)**, **[Materialize](https://materializecss.com)** and `lru` (all MIT). diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md new file mode 100644 index 00000000..a2a7a9bb --- /dev/null +++ b/THIRD-PARTY-NOTICES.md @@ -0,0 +1,99 @@ +# Third-Party Notices + +This project (a browser chess extension) redistributes the third-party software and neural-network +models listed below. Each is the property of its respective authors and is used under the license +shown. See [`LICENSING.md`](LICENSING.md) for how these licenses combine, and [`licenses/`](licenses/) +for the full GPL-3.0 and AGPL-3.0 texts. + +For each entry: **Component — License — Copyright/authors — Source (corresponding source).** + +--- + +## Base project + +- **Mephisto (original)** — MIT — Copyright (c) 2022 Alexandru Petrusca — + . This fork retains the original MIT license + ([`LICENSE`](LICENSE)) for that code and this fork's own source changes. + +## Chess engines (copyleft — GPL-3.0) + +- **Stockfish** — used in the WebAssembly builds shipped under + `lib/engine/stockfish-dev`, `stockfish-18`, `stockfish-18-small`, and `stockfish-11-hce` — + **GPL-3.0-or-later** — Copyright (c) The Stockfish developers — + . + The WebAssembly builds are produced by / obtained via the Lichess Stockfish-in-the-browser work + (`@lichess-org/stockfish-web`, and related repos). + Corresponding source: the Stockfish C++ source at the URL above, plus the WebAssembly build tooling + from the Lichess repositories. + +- **Fairy-Stockfish** — `lib/engine/fairy-stockfish-14` — **GPL-3.0-or-later** — + Copyright (c) Fabian Fichter and the Fairy-Stockfish contributors — + . Corresponding source at that URL. + +## Neural networks — engine evaluation (GPL-3.0) + +- **Stockfish NNUE networks** — the `.nnue` files under `lib/engine/stockfish-*/` — **GPL-3.0** as + distributed with Stockfish — © the Stockfish project — and + . + +- **Fairy-Stockfish NNUE networks** (one per variant) — the `.nnue` files under + `lib/engine/fairy-stockfish-14/nnue/` — **GPL-3.0** as distributed with Fairy-Stockfish — + © the Fairy-Stockfish project — . + +## Neural networks — human-like play (Maia) + +- **Maia (Maia-1) networks 1100–1900** — `lib/engine/maia/maia-1100.onnx … maia-1900.onnx` — + **GPL-3.0** — Copyright (c) the Computational Social Science Lab (CSSLab), University of Toronto — + . Converted to ONNX from the upstream `.pb.gz` weights using + `lc0 leela2onnx`; the original weights and training code are at that URL. + +- **Maia 2200 network** — `lib/engine/maia/maia-2200.onnx` — **GPL-3.0** — © CallOn84 — + . A Maia-architecture network extending the CSSLab rating + range; converted to ONNX from the upstream `.pb.gz`. + +- **Maia-3 model** — `lib/engine/maia3/maia3-23m.onnx` — **AGPL-3.0** — Copyright (c) the CSSLab, + University of Toronto — (weights also at + ). Exported to ONNX from the upstream PyTorch model; the model + code and weights are at those URLs. + +## Code derived from Maia sources + +- **Maia-3 input encoder / decoder** — `src/offscreen/maia3.js` — is a **derivative work of + CSSLab/maia3** (its board tokenization, Elo conditioning, move vocabulary and output handling were + reimplemented from that project's Python source) and is therefore distributed under **AGPL-3.0**. + © the CSSLab (original) and this project's contributors (the JavaScript port) — + . + +- **Maia-1 encoder / policy index** — `src/offscreen/maia.js` and + `lib/engine/maia/lc0_policy_index.json` — implement the **Leela Chess Zero (lc0)** "classic" input + planes and 1858-move policy ordering (the policy index was harvested from lc0's own output). These + conventions originate with **Leela Chess Zero** (**GPL-3.0**) — + . + +## Runtime & libraries (permissive) + +- **ONNX Runtime Web** (`lib/ort/`) — **MIT** — Copyright (c) Microsoft Corporation — + . The MIT license is included at + [`lib/ort/LICENSE`](lib/ort/LICENSE), and ONNX Runtime's own notices for the components it bundles + are included at [`lib/ort/ThirdPartyNotices.txt`](lib/ort/ThirdPartyNotices.txt). + +- **chess.js** (`lib/chess.js`) — **BSD-2-Clause** — Copyright (c) 2023 Jeff Hlywa + (jhlywa@gmail.com) — . (License header retained in the file.) + +- **chessboard.js** (`lib/chessboard/`) — **MIT** — Copyright (c) 2019 Chris Oakman — + . (Header retained.) + +- **jQuery** (`lib/jquery.min.js`) — **MIT** — Copyright (c) OpenJS Foundation and other + contributors — . (Header retained.) + +- **Materialize CSS** (`lib/materialize/`) — **MIT** — Copyright 2014-2017 Materialize — + . (Header retained.) + +- **lru** (`lib/lru.min.js`) — **MIT** — appears to be the `lru` package by Chris O'Hara + (); attribution inferred from its API because the minified file + carries no header. *(Please verify the exact source/license, or add the upstream header.)* + +--- + +*If any attribution here is incomplete or incorrect, please open an issue. This notice is provided in +good faith to comply with the licenses above; it is not legal advice.* diff --git a/docs/analysis-lines.png b/docs/analysis-lines.png new file mode 100644 index 00000000..adc6fca5 Binary files /dev/null and b/docs/analysis-lines.png differ diff --git a/docs/four-player.png b/docs/four-player.png new file mode 100644 index 00000000..e208c968 Binary files /dev/null and b/docs/four-player.png differ diff --git a/docs/game-review.png b/docs/game-review.png new file mode 100644 index 00000000..0f286b7b Binary files /dev/null and b/docs/game-review.png differ diff --git a/docs/hotkeys.png b/docs/hotkeys.png new file mode 100644 index 00000000..38607a73 Binary files /dev/null and b/docs/hotkeys.png differ diff --git a/docs/humanize.png b/docs/humanize.png new file mode 100644 index 00000000..1d987c8c Binary files /dev/null and b/docs/humanize.png differ diff --git a/docs/maia3.png b/docs/maia3.png new file mode 100644 index 00000000..91db136c Binary files /dev/null and b/docs/maia3.png differ diff --git a/docs/multiple-lines.png b/docs/multiple-lines.png new file mode 100644 index 00000000..cc55692a Binary files /dev/null and b/docs/multiple-lines.png differ diff --git a/docs/opening-explorer.png b/docs/opening-explorer.png new file mode 100644 index 00000000..5d9f6410 Binary files /dev/null and b/docs/opening-explorer.png differ diff --git a/docs/puzzle-database.gif b/docs/puzzle-database.gif new file mode 100644 index 00000000..76eb51ec Binary files /dev/null and b/docs/puzzle-database.gif differ diff --git a/docs/puzzle-database.mp4 b/docs/puzzle-database.mp4 new file mode 100644 index 00000000..d57a58ad Binary files /dev/null and b/docs/puzzle-database.mp4 differ diff --git a/docs/puzzle-database.png b/docs/puzzle-database.png new file mode 100644 index 00000000..7f461b92 Binary files /dev/null and b/docs/puzzle-database.png differ diff --git a/docs/read-from-screen.png b/docs/read-from-screen.png new file mode 100644 index 00000000..c9ae05df Binary files /dev/null and b/docs/read-from-screen.png differ diff --git a/docs/taketaketake.png b/docs/taketaketake.png new file mode 100644 index 00000000..ed832319 Binary files /dev/null and b/docs/taketaketake.png differ diff --git a/docs/variants.png b/docs/variants.png new file mode 100644 index 00000000..e81613bc Binary files /dev/null and b/docs/variants.png differ diff --git a/lib/chess.js b/lib/chess.js index 4cd5d74d..3a0fc979 100644 --- a/lib/chess.js +++ b/lib/chess.js @@ -1,3 +1,9 @@ +// Loaded as a CLASSIC script (content script + popup page), not an ES module: content scripts +// can't be modules, and dynamic-importing this from the isolated world would need +// web_accessible_resources and would leak the extension id via Resource Timing (issue #35 §3.4). +// Wrapped in an IIFE so only `Chess` is exposed -- its module consts must not collide with the +// content-script's globals. +(function () { /** * @license * Copyright (c) 2023, Jeff Hlywa (jhlywa@gmail.com) @@ -27,25 +33,25 @@ * POSSIBILITY OF SUCH DAMAGE. */ -export const WHITE = 'w'; -export const BLACK = 'b'; - -export const PAWN = 'p'; -export const KNIGHT = 'n'; -export const BISHOP = 'b'; -export const ROOK = 'r'; -export const QUEEN = 'q'; -export const KING = 'k'; - -export const CHESS = 'chess'; -export const CHESS960 = 'fischerandom'; -export const CRAZYHOUSE = 'crazyhouse'; -export const KING_OF_THE_HILL = 'kingofthehill'; -export const THREE_CHECK = '3check'; -export const ANTICHESS = 'antichess'; -export const ATOMIC = 'atomic'; -export const HORDE = 'horde'; -export const RACING_KINGS = 'racingkings'; +const WHITE = 'w'; +const BLACK = 'b'; + +const PAWN = 'p'; +const KNIGHT = 'n'; +const BISHOP = 'b'; +const ROOK = 'r'; +const QUEEN = 'q'; +const KING = 'k'; + +const CHESS = 'chess'; +const CHESS960 = 'fischerandom'; +const CRAZYHOUSE = 'crazyhouse'; +const KING_OF_THE_HILL = 'kingofthehill'; +const THREE_CHECK = '3check'; +const ANTICHESS = 'antichess'; +const ATOMIC = 'atomic'; +const HORDE = 'horde'; +const RACING_KINGS = 'racingkings'; const EMPTY = -1; @@ -60,7 +66,7 @@ const FLAGS = { DROP: 'd', }; -export const SQUARES = [ +const SQUARES = [ 'a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8', 'a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7', 'a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6', @@ -304,7 +310,7 @@ function trimFen(fen) { return fen.split(' ').slice(0, 4).join(' '); } -export class Chess { +class Chess { _board = new Array(128); // 0x88 board representation _turn = WHITE; // what side is to move _kings = {w: EMPTY, b: EMPTY}; // positions of kings @@ -550,8 +556,8 @@ export class Chess { const attackers = [currentSquare + 1, currentSquare - 1]; if ( - this._board[startSquare] !== null || - this._board[this._epSquare] !== null || + this._board[startSquare] != null || // != so an `undefined` empty slot matches too (L3) + this._board[this._epSquare] != null || this._board[currentSquare]?.color !== swapColor(this._turn) || this._board[currentSquare]?.type !== PAWN ) { @@ -758,10 +764,6 @@ export class Chess { return this.isCheckmate() || this.isStalemate() || this.isDraw(); } - _isLegaLMove(move) { - - } - moves({verbose = false, square = undefined, piece = undefined,} = {}) { const moves = this._moves({square, piece}); if (verbose) { @@ -802,9 +804,11 @@ export class Chess { const promotion = PROMOTIONS[i]; moves.push({color, from, to, piece, captured, promotion, flags: flags | BITS.PROMOTION}); } - // In Antichess, pawns may be promoted to kings. + // In Antichess, pawns may be promoted to kings. NOTE: `promotion: KING` -- object + // shorthand (`KING`) would name the property "KING" and leave `promotion` undefined, + // so _makeMove would never replace the pawn and the SAN would drop the "=K". if (this._variant === ANTICHESS) { - moves.push({color, from, to, piece, captured, KING, flags: flags | BITS.PROMOTION}); + moves.push({color, from, to, piece, captured, promotion: KING, flags: flags | BITS.PROMOTION}); } } else { moves.push({color, from, to, piece, captured, flags}); @@ -954,7 +958,7 @@ export class Chess { const kingTo = (us === WHITE) ? Ox88.c1 : Ox88.c8; const rookFrom = this._getRookInitialSquare(us, BITS.QSIDE_CASTLE); - const rookTo = kingTo - 1; + const rookTo = kingTo + 1; // queenside rook lands on the d-file (kingTo is c-file) let obstructed = false; // king is obstructed? @@ -1100,6 +1104,19 @@ export class Chess { moveObj = moves[i]; break; } + // Chess960: engines run with UCI_Chess960 encode castling as king-takes-rook + // (e.g. d1a1), but castling moves are generated with the king's standard + // destination (c1/g1). Accept the king-onto-rook coordinate as an alias so an + // engine's castling UCI validates and applies here. + const castleBit = moves[i].flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE); + if ( + castleBit && + move.from === algebraic(moves[i].from) && + move.to === algebraic(this._getRookInitialSquare(moves[i].color, castleBit)) + ) { + moveObj = moves[i]; + break; + } } } @@ -1179,21 +1196,19 @@ export class Chess { if (this._board[move.to]?.type === KING) { this._kings[us] = move.to; - // if we castled, move the rook next to the king - if (move.flags & BITS.KSIDE_CASTLE) { - const rookFrom = this._getRookInitialSquare(us, BITS.KSIDE_CASTLE); - const rookTo = move.to - 1; - if (rookTo !== rookFrom) { - this._board[rookTo] = this._board[rookFrom]; - delete this._board[rookFrom]; - } - } else if (move.flags & BITS.QSIDE_CASTLE) { - const rookFrom = this._getRookInitialSquare(us, BITS.QSIDE_CASTLE); - const rookTo = move.to + 1; - if (rookTo !== rookFrom) { - this._board[rookTo] = this._board[rookFrom]; - delete this._board[rookFrom]; - } + // if we castled, move the rook next to the king. Chess960: the king's origin and the + // rook's origin/destination can coincide with each other's squares (e.g. the king + // starts on the rook's post-castle square, or the rook starts on the king's destination + // -- a king/rook swap). Clear both origins, then place king+rook on their final squares + // last, so no collision can clobber a piece we still need. + const castleBit = move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE); + if (castleBit) { + const rookFrom = this._getRookInitialSquare(us, castleBit); + const rookTo = (move.flags & BITS.KSIDE_CASTLE) ? move.to - 1 : move.to + 1; + delete this._board[move.from]; + delete this._board[rookFrom]; + this._board[move.to] = {color: us, type: KING}; + this._board[rookTo] = {color: us, type: ROOK}; } // turn off castling @@ -1315,20 +1330,18 @@ export class Chess { } } - if (move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE)) { - let rookFrom, rookTo; - if (move.flags & BITS.KSIDE_CASTLE) { - rookFrom = this._getRookInitialSquare(us, BITS.KSIDE_CASTLE); - rookTo = move.to - 1; - } else { - rookFrom = this._getRookInitialSquare(us, BITS.QSIDE_CASTLE); - rookTo = move.to + 1; - } - - if (rookFrom !== rookTo) { - this._board[rookFrom] = this._board[rookTo]; - delete this._board[rookTo]; - } + const castleBit = move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE); + if (castleBit) { + const rookFrom = this._getRookInitialSquare(us, castleBit); + const rookTo = (move.flags & BITS.KSIDE_CASTLE) ? move.to - 1 : move.to + 1; + // Chess960: the king's origin (move.from) can equal the rook's post-castle square, or + // the rook's origin can equal the king's destination. The generic restore above put the + // king back on move.from -- which may be rookTo -- so a positional swap here would clobber + // it. Clear both post-castle squares, then place king+rook on their origins last. + delete this._board[move.to]; + delete this._board[rookTo]; + this._board[move.from] = {color: us, type: KING}; + this._board[rookFrom] = {color: us, type: ROOK}; } return move; @@ -1443,7 +1456,7 @@ export class Chess { let overlyDisambiguated = false; - matches = cleanMove.match(/([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/); + matches = cleanMove.match(/([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnkQRBNK])?/); if (matches) { piece = matches[1]; from = matches[2]; @@ -1459,7 +1472,7 @@ export class Chess { * there is one legal knight move to e7). In this case, the value of * 'from' variable will be a rank or file, not a square. */ - matches = cleanMove.match(/([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnQRBN])?/); + matches = cleanMove.match(/([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnkQRBNK])?/); if (matches) { piece = matches[1]; from = matches[2]; @@ -1735,3 +1748,6 @@ export class Chess { } } } + +self.Chess = Chess; +})(); diff --git a/lib/engine/fairy-stockfish-14/fsf14.js b/lib/engine/fairy-stockfish-14/fsf14.js deleted file mode 100644 index 5b82ba47..00000000 --- a/lib/engine/fairy-stockfish-14/fsf14.js +++ /dev/null @@ -1,51 +0,0 @@ - -var Fsf14Web = (() => { - var _scriptName = import.meta.url; - - return ( -function(moduleArg = {}) { - var moduleRtn; - -function aa(){h.buffer!=k.buffer&&l();return k}function n(){h.buffer!=k.buffer&&l();return ba}function p(){h.buffer!=k.buffer&&l();return ca}function q(){h.buffer!=k.buffer&&l();return da}function ea(){h.buffer!=k.buffer&&l();return fa}var r=moduleArg,t,u,ha=new Promise((a,b)=>{t=a;u=b}),ia="object"==typeof window,v="function"==typeof importScripts,ja="object"==typeof process&&"object"==typeof process.fa&&"string"==typeof process.fa.node,x=v&&"em-pthread"==self.name;r.listen||(r.listen=a=>console.log(a)); -r.onError||(r.onError=a=>console.error(a));r.getRecommendedNnue=(a=0)=>ka(la(a));r.setNnueBuffer=function(a,b=0){if(!a)throw Error("buf is null");if(0>=a.byteLength)throw Error(`${a.byteLength} bytes?`);const c=y(a.byteLength);if(!c)throw Error(`could not allocate ${a.byteLength} bytes`);r.HEAPU8.set(a,c);ma(c,a.byteLength,b)};r.uci=function(a){const b=na(a)+1,c=y(b);if(!c)throw Error(`Could not allocate ${b} bytes`);z(a,c,b);oa(c)};r.print=a=>r.listen?.(a);r.printErr=a=>r.onError?.(a); -var pa=Object.assign({},r),qa=[],A="",ra,B; -if(ia||v)v?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptName&&(A=_scriptName),A.startsWith("blob:")?A="":A=A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1),v&&(B=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),ra=a=>fetch(a,{credentials:"same-origin"}).then(b=>b.ok?b.arrayBuffer():Promise.reject(Error(b.status+" : "+b.url))); -var sa=r.print||console.log.bind(console),C=r.printErr||console.error.bind(console);Object.assign(r,pa);pa=null; -if(x){var ta,ua=!1;function a(...c){console.error(c.join(" "))}r.printErr||(C=a);self.alert=function(...c){postMessage({ba:"alert",text:c.join(" "),ja:D()})};r.instantiateWasm=(c,d)=>new Promise(f=>{ta=e=>{e=new WebAssembly.Instance(e,va());d(e);f()}});self.onunhandledrejection=c=>{throw c.reason||c;};function b(c){try{var d=c.data,f=d.cmd;if("load"===f){let e=[];self.onmessage=g=>e.push(g);self.startWorker=()=>{postMessage({cmd:"loaded"});for(let g of e)b(g);self.onmessage=b};for(const g of d.handlers)if(!r[g]|| -r[g].proxy)r[g]=(...m)=>{postMessage({ba:"callHandler",ia:g,ha:m})},"print"==g&&(sa=r[g]),"printErr"==g&&(C=r[g]);h=d.wasmMemory;l();ta(d.wasmModule)}else if("run"===f){E(d.pthread_ptr,0,0,1,0,0);F(d.pthread_ptr);wa();xa();ua||=!0;try{ya(d.start_routine,d.arg)}catch(e){if("unwind"!=e)throw e;}}else"cancel"===f?D()&&G(-1):"setimmediate"!==d.target&&("checkMailbox"===f?ua&&H():f&&(C(`worker: received unknown command ${f}`),C(d)))}catch(e){throw za(),e;}}self.onmessage=b}var h,Aa,I=!1,J,k,ba,ca,da,fa; -function l(){var a=h.buffer;k=new Int8Array(a);new Int16Array(a);r.HEAPU8=ba=new Uint8Array(a);new Uint16Array(a);ca=new Int32Array(a);da=new Uint32Array(a);new Float32Array(a);fa=new Float64Array(a)} -if(!x){if(r.wasmMemory)h=r.wasmMemory;else if(h=new WebAssembly.Memory({initial:1024,maximum:32768,shared:!0}),!(h.buffer instanceof SharedArrayBuffer))throw C("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),ja&&C("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory"); -l()}var Ba=[],K=[],Ca=[],Da=[],Ea=[],Fa=!1,L=0,Ga=null,M=null;function Ha(){L--;if(0==L&&(null!==Ga&&(clearInterval(Ga),Ga=null),M)){var a=M;M=null;a()}}function Ia(a){a="Aborted("+a+")";C(a);I=!0;J=1;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");u(a);throw a;}var Ja=a=>a.startsWith("data:application/octet-stream;base64,"),Ka; -function La(a){return ra(a).then(b=>new Uint8Array(b),()=>{if(B)var b=B(a);else throw"both async and sync fetching of the wasm failed";return b})}function Ma(a,b,c){return La(a).then(d=>WebAssembly.instantiate(d,b)).then(c,d=>{C(`failed to asynchronously prepare wasm: ${d}`);Ia(d)})} -function Na(a,b){var c=Ka;return"function"!=typeof WebAssembly.instantiateStreaming||Ja(c)||"function"!=typeof fetch?Ma(c,a,b):fetch(c,{credentials:"same-origin"}).then(d=>WebAssembly.instantiateStreaming(d,a).then(b,function(f){C(`wasm streaming compile failed: ${f}`);C("falling back to ArrayBuffer instantiation");return Ma(c,a,b)}))} -function va(){Oa={A:Pa,e:Qa,u:Ra,w:Sa,n:Ta,B:Ua,j:Va,z:Wa,C:Xa,q:Ya,f:Za,i:F,h:$a,r:ab,s:bb,g:cb,m:db,b:eb,y:fb,v:gb,k:hb,l:ib,c:N,d:jb,t:kb,o:lb,x:mb,a:h,p:nb};return{a:Oa}}function ob(a){this.name="ExitStatus";this.message=`Program terminated with exit(${a})`;this.status=a} -var pb=a=>{a.terminate();a.onmessage=()=>{}},sb=a=>{0==O.length&&(qb(),rb(O[0]));var b=O.pop();if(!b)return 6;P.push(b);Q[a.$]=b;b.$=a.$;b.postMessage({cmd:"run",start_routine:a.da,arg:a.ca,pthread_ptr:a.$},a.ea);return 0},R=0,gb=()=>0{for(var d=c.length,f=tb(),e=S(8*d),g=e>>3,m=0;m{if(!(a instanceof ob||"unwind"==a))throw a;}; -function Ab(a){if(x)return T(1,0,a);--R;N(a)}var N=a=>{J=a;if(x)throw Ab(a),"unwind";0{L++;Hb(()=>Ha())})}var wb=()=>{for(var a of P)pb(a);for(a of O)pb(a);O=[];P=[];Q=[]},Jb=a=>{var b=a.$;delete Q[b];O.push(a);P.splice(P.indexOf(a),1);a.$=0;Ib(b)};function xa(){Fb.forEach(a=>a())} -var rb=a=>new Promise(b=>{a.onmessage=e=>{e=e.data;var g=e.cmd;if(e.targetThread&&e.targetThread!=D()){var m=Q[e.targetThread];m?m.postMessage(e,e.transferList):C(`Internal error! Worker sent a message "${g}" to target pthread ${e.targetThread}, but that thread no longer exists!`)}else if("checkMailbox"===g)H();else if("spawnThread"===g)sb(e);else if("cleanupThread"===g)Jb(Q[e.thread]);else if("killThread"===g)e=e.thread,g=Q[e],delete Q[e],pb(g),Ib(e),P.splice(P.indexOf(g),1),g.$=0;else if("cancelThread"=== -g)Q[e.thread].postMessage({cmd:"cancel"});else if("loaded"===g)a.loaded=!0,b(a);else if("alert"===g)alert(`Thread ${e.threadId}: ${e.text}`);else if("setimmediate"===e.target)a.postMessage(e);else if("callHandler"===g)r[e.handler](...e.args);else g&&C(`worker sent an unknown command ${g}`)};a.onerror=e=>{C(`${"worker sent an error!"} ${e.filename}:${e.lineno}: ${e.message}`);throw e;};var c=[],d=["print","printErr"],f;for(f of d)r.propertyIsEnumerable(f)&&c.push(f);a.postMessage({cmd:"load",handlers:c, -wasmMemory:h,wasmModule:Aa})});function Hb(a){x?a():Promise.all(O.map(rb)).then(a)}function qb(){var a=new Worker(new URL("fsf14.js",import.meta.url),{type:"module",name:"em-pthread"});O.push(a)}var U=a=>{for(;0{var a=D(),b=q()[a+52>>2];a=q()[a+56>>2];Kb(b,b-a);vb(b)},V=[],Lb,ya=(a,b)=>{R=0;var c=V[a];c||(a>=V.length&&(V.length=a+1),V[a]=c=Lb.get(a));a=c(b);0{if("undefined"==typeof SharedArrayBuffer)return C("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var f=[];if(x&&0===f.length)return Mb(a,b,c,d);a={da:c,$:a,ca:d,ea:f};return x?(a.ba="spawnThread",postMessage(a,f),0):sb(a)},Nb="undefined"!=typeof TextDecoder?new TextDecoder:void 0,Ob=(a,b,c)=>{var d=b+c;for(c=b;a[c]&&!(c>=d);)++c;if(16f?d+=String.fromCharCode(f):(f-=65536,d+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else d+=String.fromCharCode(f)}return d},ka=(a,b)=>a?Ob(n(),a,b):"";function Qa(a,b,c){return x?T(3,1,a,b,c):0}function Ra(a,b,c){return x?T(4,1,a,b,c):0}function Sa(a,b,c,d){if(x)return T(5,1,a,b,c,d)} -var Ta=()=>{Ia("")},Ua=()=>1,Va=a=>{E(a,!v,1,!ia,2097152,!1);xa()},Pb=a=>{if(!Fa&&!I)try{if(a(),!(Fa||0{"function"===typeof Atomics.ga&&(Atomics.ga(p(),a>>2,a).value.then(H),a+=128,Atomics.store(p(),a>>2,1))},H=()=>{var a=D();a&&(F(a),Pb(Qb))},Wa=(a,b)=>{a==b?setTimeout(H):x?postMessage({targetThread:a,cmd:"checkMailbox"}):(a=Q[a])&&a.postMessage({cmd:"checkMailbox"})},Rb=[],Xa=(a,b,c,d,f)=>{Rb.length=d;b=f>>3;for(c=0;c{x?postMessage({cmd:"cleanupThread",thread:a}):Jb(Q[a])},$a=()=>{},W={},eb;eb=()=>performance.timeOrigin+performance.now();function ab(a,b){if(x)return T(7,1,a,b);W[a]&&(clearTimeout(W[a].id),delete W[a]);if(!b)return 0;var c=setTimeout(()=>{delete W[a];Pb(()=>Tb(a,eb()))},b);W[a]={id:c,ka:b};return 0} -var z=(a,b,c)=>{var d=n();if(0=g){var m=a.charCodeAt(++e);g=65536+((g&1023)<<10)|m&1023}if(127>=g){if(b>=c)break;d[b++]=g}else{if(2047>=g){if(b+1>=c)break;d[b++]=192|g>>6}else{if(65535>=g){if(b+2>=c)break;d[b++]=224|g>>12}else{if(b+3>=c)break;d[b++]=240|g>>18;d[b++]=128|g>>12&63}d[b++]=128|g>>6&63}d[b++]=128|g&63}}d[b]=0;a=b-f}else a=0;return a},bb=(a,b,c,d)=>{var f=(new Date).getFullYear(),e=(new Date(f,0,1)).getTimezoneOffset(); -f=(new Date(f,6,1)).getTimezoneOffset();var g=Math.max(e,f);q()[a>>2]=60*g;p()[b>>2]=Number(e!=f);b=m=>{var w=Math.abs(m);return`UTC${0<=m?"-":"+"}${String(Math.floor(w/60)).padStart(2,"0")}${String(w%60).padStart(2,"0")}`};a=b(e);b=b(f);f{X.aa||(X.aa={});X.aa["Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"]||(X.aa["Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"]= -1,C("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"))},cb=()=>{v||(X(),Ia("Blocking on the main thread is not allowed by default. See https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"))},db=()=>{R+=1;throw"unwind";},fb=a=>{var b=n().length;a>>>=0;if(a<=b||2147483648=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(2147483648,65536* -Math.ceil(Math.max(a,d)/65536))-h.buffer.byteLength+65535)/65536;try{h.grow(d);l();var f=1;break a}catch(e){}f=void 0}if(f)return!0}return!1},Ub={},Wb=()=>{if(!Vb){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"},b;for(b in Ub)void 0===Ub[b]?delete a[b]:a[b]=Ub[b];var c=[];for(b in a)c.push(`${b}=${a[b]}`);Vb=c}return Vb},Vb; -function hb(a,b){if(x)return T(8,1,a,b);var c=0;Wb().forEach((d,f)=>{var e=b+c;f=q()[a+4*f>>2]=e;for(e=0;e>2]=c.length;var d=0;c.forEach(f=>d+=f.length+1);q()[b>>2]=d;return 0}function jb(a){return x?T(10,1,a):52}function kb(a,b,c,d){return x?T(11,1,a,b,c,d):52}function lb(a,b,c,d,f){return x?T(12,1,a,b,c,d,f):70} -var Db=[null,[],[]],Eb=(a,b)=>{var c=Db[a];0===b||10===b?((1===a?sa:C)(Ob(c,0)),c.length=0):c.push(b)};function mb(a,b,c,d){if(x)return T(13,1,a,b,c,d);for(var f=0,e=0;e>2],m=q()[b+4>>2];b+=8;for(var w=0;w>2]=f;return 0}var na=a=>{for(var b=0,c=0;c=d?b++:2047>=d?b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=3}return b};x||Gb(); -var Sb=[nb,Ab,Mb,Qa,Ra,Sa,Ya,ab,hb,ib,jb,kb,lb,mb],Oa,Y=function(){function a(c,d){Y=c.exports;Fb.push(Y.J);Lb=Y.M;K.unshift(Y.D);Aa=d;Ha();return Y}var b=va();L++;if(r.instantiateWasm)try{return r.instantiateWasm(b,a)}catch(c){C(`Module.instantiateWasm callback failed with error: ${c}`),u(c)}Ka||=r.locateFile?Ja("fsf14.wasm")?"fsf14.wasm":r.locateFile?r.locateFile("fsf14.wasm",A):A+"fsf14.wasm":(new URL("fsf14.wasm",import.meta.url)).href;Na(b,function(c){a(c.instance,c.module)}).catch(u); -return{}}();r._main=(a,b)=>(r._main=Y.E)(a,b);r.__Z10js_getlinev=a=>(r.__Z10js_getlinev=Y.F)(a); -var oa=r._uci=a=>(oa=r._uci=Y.G)(a),ma=r._setNnueBuffer=(a,b,c)=>(ma=r._setNnueBuffer=Y.H)(a,b,c),la=r._getRecommendedNnue=a=>(la=r._getRecommendedNnue=Y.I)(a),D=()=>(D=Y.K)(),Xb=r.__emscripten_proxy_main=(a,b)=>(Xb=r.__emscripten_proxy_main=Y.L)(a,b),Bb=()=>(Bb=Y.N)(),E=(a,b,c,d,f,e)=>(E=Y.O)(a,b,c,d,f,e),za=()=>(za=Y.P)(),Cb=a=>(Cb=Y.Q)(a),y=r._malloc=a=>(y=r._malloc=Y.R)(a),ub=(a,b,c,d,f)=>(ub=Y.S)(a,b,c,d,f),Ib=a=>(Ib=Y.T)(a),G=a=>(G=Y.U)(a),Tb=(a,b)=>(Tb=Y.V)(a,b),Qb=()=>(Qb=Y.W)(),Kb=(a,b)=> -(Kb=Y.X)(a,b),vb=a=>(vb=Y.Y)(a),S=a=>(S=Y.Z)(a),tb=()=>(tb=Y._)();r.UTF8ToString=ka;r.stringToUTF8=z;var Z;M=function Yb(){Z||Zb();Z||(M=Yb)};function $b(a=[]){var b=Xb;R+=1;a.unshift("./this.program");var c=a.length,d=S(4*(c+1)),f=d;a.forEach(g=>{var m=q(),w=f>>2,yb=na(g)+1,zb=S(yb);z(g,zb,yb);m[w]=zb;f+=4});q()[f>>2]=0;try{var e=b(c,d);N(e,!0)}catch(g){xb(g)}} -function Zb(){0console.log(a)); +h.onError||(h.onError=a=>console.error(a));h.getRecommendedNnue=(a=0)=>fa(ha(a))||void 0;h.setNnueBuffer=function(a,b=0){if(!a)throw Error("buf is null");if(a.byteLength<=0)throw Error(`${a.byteLength} bytes?`);var c=ia(a.byteLength);if(!c)throw Error(`could not allocate ${a.byteLength} bytes`);q();h.HEAPU8.set(a,c);ja(c,a.byteLength,b)};h.uci=function(a){var b=ka(a)+1,c=ia(b);if(!c)throw Error(`Could not allocate ${b} bytes`);t(a,c,b);la(c)};h.print=a=>h.listen?.(a);h.printErr=a=>h.onError?.(a); +var ma=[],na="./this.program",oa=(a,b)=>{throw b;},pa=import.meta.url,qa="",ra,sa; +if(l){var fs=require("node:fs");pa.startsWith("file:")&&(qa=require("node:path").dirname(require("node:url").fileURLToPath(pa))+"/");sa=a=>{a=ta(a)?new URL(a):a;return fs.readFileSync(a)};ra=async a=>{a=ta(a)?new URL(a):a;return fs.readFileSync(a,void 0)};process.argv.length>1&&(na=process.argv[1].replace(/\\/g,"/"));ma=process.argv.slice(2);oa=(a,b)=>{process.exitCode=a;throw b;}}else if(ea||k){try{qa=(new URL(".",pa)).href}catch{}l||(k&&(sa=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType= +"arraybuffer";b.send(null);return new Uint8Array(b.response)}),ra=async a=>{a=await fetch(a,{credentials:"same-origin"});if(a.ok)return a.arrayBuffer();throw Error(a.status+" : "+a.url);})}var ua=console.log.bind(console),va=console.error.bind(console);if(l){var wa=require("node:util"),xa=a=>typeof a=="object"?wa.inspect(a):a;ua=(...a)=>fs.writeSync(1,a.map(xa).join(" ")+"\n");va=(...a)=>fs.writeSync(2,a.map(xa).join(" ")+"\n")}var ya=ua,u=va,v,za=!1,w,ta=a=>a.startsWith("file://"); +function q(){x.buffer!=y.buffer&&Aa()}var Ba,Ca;if(l&&m){globalThis.self=globalThis;var Da=worker_threads.parentPort;globalThis.postMessage||(Da.on("message",a=>globalThis.onmessage?.({data:a})),globalThis.postMessage=a=>Da.postMessage(a));process.on("uncaughtException",a=>{postMessage({ga:8,error:a});process.exit(1)})}var Ea; +if(m){var Fa=!1;self.onunhandledrejection=b=>{throw b.reason||b;};function a(b){try{var c=b.data,d=c.ga;if(d==1){let e=[];self.onmessage=f=>e.push(f);Ea=()=>{postMessage({ga:3});for(let f of e)a(f);self.onmessage=a};for(let f of c.Ia)if(!h[f]||h[f].proxy)h[f]=(...g)=>{postMessage({ga:9,Ha:f,args:g})},f=="print"&&(ya=h[f]),f=="printErr"&&(u=h[f]);x=c.Va;Aa();v=c.Wa;Ga();Ha()}else if(d==2){Ia(c.ja);Ja(c.ja,0,0,1,0,0);Ka();La(c.ja);Fa||=!0;try{Ma(c.Qa,c.sa)}catch(e){if(e!="unwind")throw e;}}else d== +4?Fa&&Na():d&&(u(`worker: received unknown command ${d}`),u(c))}catch(e){throw Oa(),e;}}self.onmessage=a}var Pa=!1,Qa=!1;function Aa(){var a=x.buffer;y=new Int8Array(a);Ra=new Int16Array(a);h.HEAPU8=Sa=new Uint8Array(a);new Uint16Array(a);A=new Int32Array(a);B=new Uint32Array(a);new Float32Array(a);Ta=new Float64Array(a);C=new BigInt64Array(a);new BigUint64Array(a)} +function Ua(){Pa=!0;m?Ea():(h.noFSInit||Va||(Va=!0,Wa("/dev/tty","/dev/stdin"),Wa("/dev/tty","/dev/stdout"),Wa("/dev/tty1","/dev/stderr"),Xa("/dev/stdin",0),Xa("/dev/stdout",1),Xa("/dev/stderr",1)),D.D(),Ya=!1)}function Za(a){a=`Aborted(${a})`;u(a);za=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");Ca?.(a);throw a;}var $a; +async function ab(a){try{var b=await ra(a);return new Uint8Array(b)}catch{}if(sa)a=sa(a);else throw"both async and sync fetching of the wasm failed";return a}async function bb(a,b){try{var c=await ab(a);return await WebAssembly.instantiate(c,b)}catch(d){u(`failed to asynchronously prepare wasm: ${d}`),Za(d)}} +async function cb(a){var b=$a;if(!l)try{var c=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(c,a)}catch(d){u(`wasm streaming compile failed: ${d}`),u("falling back to ArrayBuffer instantiation")}return bb(b,a)}function db(){eb={B:fb,e:gb,x:hb,y:ib,o:jb,k:kb,A:lb,h:mb,q:nb,f:ob,j:La,i:pb,r:qb,s:rb,C:sb,g:tb,n:ub,c:vb,z:wb,w:xb,l:yb,m:zb,b:Ab,d:Bb,v:Cb,t:Db,u:Eb,a:x,p:Fb};return{a:eb}} +async function Ga(){function a(d,e){D=d.exports;Gb.push(D.J);d=D;h.__Z10js_getlinev=d.E;h._main=d.F;la=h._uci=d.G;ja=h._setNnueBuffer=d.H;ha=h._getRecommendedNnue=d.I;Hb=d.K;Ib=h.__emscripten_proxy_main=d.L;Jb=d.N;Ja=d.O;Kb=d.P;Oa=d.Q;Lb=d.R;ia=h._malloc=d.S;Mb=d.T;Nb=d.U;Ob=d.V;Pb=d.W;Qb=d.X;Rb=d.Y;Sb=d.Z;Tb=d._;Ub=d.$;Vb=d.aa;Wb=d.M;v=e;return D}var b=db();if(h.instantiateWasm)return new Promise(d=>{h.instantiateWasm(b,(e,f)=>{d(a(e,f))})});if(m){var c=new WebAssembly.Instance(v,db());return a(c, +v)}$a??=h.locateFile?h.locateFile?h.locateFile("fsf_14.wasm",qa):qa+"fsf_14.wasm":(new URL("fsf_14.wasm",import.meta.url)).href;return function(d){return a(d.instance,d.module)}(await cb(b))}class Xb{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}} +var Ra,A,C,y,Ta,B,Sa,Yb=a=>{a.terminate();a.onmessage=()=>{}},Zb=[],ac=a=>{if(E.length==0){if(h.mainScriptUrlOrBlob){var b=h.mainScriptUrlOrBlob;typeof b!="string"&&(b=URL.createObjectURL(b));b=new Worker(b,{type:"module",workerData:"em-pthread",name:"em-pthread"})}else b=new Worker(new URL("fsf_14.js",import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});E.push(b);$b(b)}b=E.pop();if(!b)return 6;H[a.ja]=b;b.ja=a.ja;b.postMessage({ga:2,Qa:a.Pa,sa:a.sa,ja:a.ja},a.Ta); +return 0},I=0,xb=()=>I>0,J=(a,b,...c)=>{var d=8*c.length*2,e=Vb(),f=Ub(d),g=f>>3,n;for(n of c)typeof n=="bigint"?((q(),C)[g++]=1n,(q(),C)[g++]=n):((q(),C)[g++]=0n,(q(),Ta)[g++]=n);a=Nb(a,0,d,f,b);Tb(e);return a};function Fb(a){if(m)return J(0,1,a);w=a;I>0||(bc(),h.onExit?.(a),za=!0);oa(a,new Xb(a))}function cc(a){if(m)return J(1,0,a);--I;Ab(a)} +var Ab=a=>{w=a;if(m)throw cc(a),"unwind";if(!(I>0)){Jb();Va=!1;Lb(0);for(var b of K)b&&dc(b);for(var c of Object.values(L))clearTimeout(c.id);bc();b=Hb();Kb(0,0,0,1);ec||Atomics.notify((q(),A),b>>2);Qa=!0}Fb(a)},ec=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2])<91,E=[],Gb=[],H={},bc=()=>{for(var a of Object.values(H))Yb(a);for(a of E)Yb(a);E=[];H={}},fc=a=>{var b=a.ja;delete H[b];E.push(a);a.ja=0;l&&a.unref();Ob(b)}; +function Ka(){Gb.forEach(a=>a())} +var $b=a=>{new Promise(b=>{a.onmessage=f=>{var g=f.data;f=g.ga;if(g.Fa)H[g.Fa]?.postMessage(g);else if(g==="setimmediate"||g==="_si")a.postMessage(g);else switch(f){case 4:Na();break;case 5:ac(g);break;case 6:hc(()=>{fc(H[g.Sa])});break;case 3:l&&!a.Ra&&a.unref();b(a);break;case 8:a.onerror(g.error);break;case 9:h[g.Ha](...g.args);break;default:f&&u(`worker sent an unknown command ${f}`)}};a.onerror=f=>{u(`worker sent an error! ${f.filename}:${f.lineno}: ${f.message}`);throw f;};l&&(a.on("message", +f=>a.onmessage({data:f})),a.on("error",f=>a.onerror(f)));var c=[],d=["onExit","print","printErr"],e;for(e of d)h.propertyIsEnumerable(e)&&c.push(e);a.postMessage({ga:1,Ia:c,Va:x,Wa:v})})};function Ia(a){var b=(q(),B)[a+48>>2];a=(q(),B)[a+52>>2];Sb(b,b-a);Tb(b)}var ic=[],Ma=(a,b)=>{I=0;var c=ic[a];c||(ic[a]=c=Wb.get(a));a=c(b);I>0?w=a:Pb(a)},x;function jc(a,b,c,d){return m?J(2,1,a,b,c,d):fb(a,b,c,d)} +var fb=(a,b,c,d)=>{if(!globalThis.SharedArrayBuffer)return 6;var e=[];if(m&&e.length===0)return jc(a,b,c,d);a={Pa:c,ja:a,sa:d,Ta:e};return m?(a.ga=5,postMessage(a,e),0):ac(a)},O=()=>{var a=(q(),A)[+M>>2];M+=4;return a},kc=(a,b)=>{for(var c=0,d=a.length-1;d>=0;d--){var e=a[d];e==="."?a.splice(d,1):e===".."?(a.splice(d,1),c++):c&&(a.splice(d,1),c--)}if(b)for(;c;c--)a.unshift("..");return a},lc=a=>{var b=a.charAt(0)==="/",c=a.slice(-1)==="/";(a=kc(a.split("/").filter(d=>!!d),!b).join("/"))||b||(a="."); +a&&c&&(a+="/");return(b?"/":"")+a},mc=a=>{var b=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1);a=b[0];b=b[1];if(!a&&!b)return".";b&&=b.slice(0,-1);return a+b},nc=()=>{if(l){var a=require("node:crypto");return b=>a.randomFillSync(b)}return b=>(b.set(crypto.getRandomValues(new Uint8Array(b.byteLength))),0)},oc=a=>(oc=nc())(a),pc=(...a)=>{for(var b="",c=!1,d=a.length-1;d>=-1&&!c;d--){c=d>=0?a[d]:"/";if(typeof c!="string")throw new TypeError("Arguments to path.resolve must be strings"); +if(!c)return"";b=c+"/"+b;c=c.charAt(0)==="/"}b=kc(b.split("/").filter(e=>!!e),!c).join("/");return(c?"/":"")+b||"."},qc=globalThis.TextDecoder&&new TextDecoder,P=(a,b=0,c,d)=>{var e=b;c=e+c;if(d)d=c;else{for(;a[e]&&!(e>=c);)++e;d=e}if(d-b>16&&a.buffer&&qc)return qc.decode(a.buffer instanceof ArrayBuffer?a.subarray(b,d):a.slice(b,d));for(e="";b>10,56320|c&1023))}}else e+=String.fromCharCode(c);return e},rc=[],ka=a=>{for(var b=0,c=0;c=55296&&d<=57343?(b+=4,++c):b+=3}return b},sc=(a,b,c,d)=>{if(!(d>0))return 0;var e=c;d=c+d-1;for(var f=0;f=d)break;b[c++]=g}else if(g<=2047){if(c+1>=d)break;b[c++]=192|g>>6;b[c++]=128|g&63}else if(g<= +65535){if(c+2>=d)break;b[c++]=224|g>>12;b[c++]=128|g>>6&63;b[c++]=128|g&63}else{if(c+3>=d)break;b[c++]=240|g>>18;b[c++]=128|g>>12&63;b[c++]=128|g>>6&63;b[c++]=128|g&63;f++}}b[c]=0;return c-e},tc=[];function uc(a,b){tc[a]={input:[],output:[],la:b};vc(a,wc)} +var wc={open(a){var b=tc[a.node.rdev];if(!b)throw new Q(43);a.tty=b;a.seekable=!1},close(a){a.tty.la.fsync(a.tty)},fsync(a){a.tty.la.fsync(a.tty)},read(a,b,c,d){if(!a.tty||!a.tty.la.Aa)throw new Q(60);for(var e=0,f=0;f0&&(a=b.slice(0,c).toString("utf-8"))}else globalThis.window?.prompt&&(a=window.prompt("Input: "),a!==null&&(a+="\n"));if(!a){a=null;break a}b=Array(ka(a)+1);a=sc(a,b,0,b.length);b.length=a;rc=b}a=rc.shift()}return a},xa(a,b){b===null||b===10?(ya(P(a.output)),a.output= +[]):b!=0&&a.output.push(b)},fsync(a){a.output?.length>0&&(ya(P(a.output)),a.output=[])},Ka(){return{$a:25856,bb:5,Za:191,ab:35387,Ya:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},La(){return 0},Ma(){return[24,80]}},yc={xa(a,b){b===null||b===10?(u(P(a.output)),a.output=[]):b!=0&&a.output.push(b)},fsync(a){a.output?.length>0&&(u(P(a.output)),a.output=[])}},R={ia:null,ka(){return R.createNode(null,"/",16895,0)},createNode(a,b,c,d){if((c&61440)===24576||(c&61440)===4096)throw new Q(63); +R.ia||(R.ia={dir:{node:{oa:R.da.oa,ma:R.da.ma,lookup:R.da.lookup,qa:R.da.qa,rename:R.da.rename,unlink:R.da.unlink,rmdir:R.da.rmdir,readdir:R.da.readdir,symlink:R.da.symlink},stream:{ha:R.ba.ha}},file:{node:{oa:R.da.oa,ma:R.da.ma},stream:{ha:R.ba.ha,read:R.ba.read,write:R.ba.write,Ca:R.ba.Ca,Ea:R.ba.Ea}},link:{node:{oa:R.da.oa,ma:R.da.ma,readlink:R.da.readlink},stream:{}},za:{node:{oa:R.da.oa,ma:R.da.ma},stream:zc}});c=Ac(a,b,c,d);(c.mode&61440)===16384?(c.da=R.ia.dir.node,c.ba=R.ia.dir.stream,c.ea= +{}):(c.mode&61440)===32768?(c.da=R.ia.file.node,c.ba=R.ia.file.stream,c.fa=0,c.ea=R.Ga??(R.Ga=new Uint8Array(0))):(c.mode&61440)===40960?(c.da=R.ia.link.node,c.ba=R.ia.link.stream):(c.mode&61440)===8192&&(c.da=R.ia.za.node,c.ba=R.ia.za.stream);c.atime=c.mtime=c.ctime=Date.now();a&&(a.ea[b]=c,a.atime=a.mtime=a.ctime=c.atime);return c},da:{oa(a){var b={};b.dev=(a.mode&61440)===8192?a.id:1;b.ino=a.id;b.mode=a.mode;b.nlink=1;b.uid=0;b.gid=0;b.rdev=a.rdev;(a.mode&61440)===16384?b.size=4096:(a.mode&61440)=== +32768?b.size=a.fa:(a.mode&61440)===40960?b.size=a.link.length:b.size=0;b.atime=new Date(a.atime);b.mtime=new Date(a.mtime);b.ctime=new Date(a.ctime);b.blksize=4096;b.blocks=Math.ceil(b.size/b.blksize);return b},ma(a,b){for(var c of["mode","atime","mtime","ctime"])b[c]!=null&&(a[c]=b[c]);b.size!==void 0&&(b=b.size,a.fa!=b&&(c=a.ea,a.ea=new Uint8Array(b),a.ea.set(c.subarray(0,Math.min(b,a.fa))),a.fa=b))},lookup(){R.ta||(R.ta=new Q(44),R.ta.stack="");throw R.ta;},qa(a,b,c,d){return R.createNode(a, +b,c,d)},rename(a,b,c){try{var d=Bc(b,c)}catch(f){}if(d){if((a.mode&61440)===16384)for(var e in d.ea)throw new Q(55);e=Cc(d.parent.id,d.name);if(S[e]===d)S[e]=d.pa;else for(e=S[e];e;){if(e.pa===d){e.pa=d.pa;break}e=e.pa}}delete a.parent.ea[a.name];b.ea[c]=a;a.name=c;b.ctime=b.mtime=a.parent.ctime=a.parent.mtime=Date.now()},unlink(a,b){delete a.ea[b];a.ctime=a.mtime=Date.now()},rmdir(a,b){var c=Bc(a,b),d;for(d in c.ea)throw new Q(55);delete a.ea[b];a.ctime=a.mtime=Date.now()},readdir(a){return[".", +"..",...Object.keys(a.ea)]},symlink(a,b,c){a=R.createNode(a,b,41471,0);a.link=c;return a},readlink(a){if((a.mode&61440)!==40960)throw new Q(28);return a.link}},ba:{read(a,b,c,d,e){if(e>=a.node.fa)return 0;d=Math.min(a.node.fa-e,d);b.set(a.node.ea.subarray(e,e+d),c);return d},write(a,b,c,d,e,f){b.buffer===(q(),y).buffer&&(f=!1);if(!d)return 0;a=a.node;a.mtime=a.ctime=Date.now();if(f)a.ea=b.subarray(c,c+d),a.fa=d;else if(a.fa===0&&e===0)a.ea=b.slice(c,c+d),a.fa=d;else{f=e+d;var g=a.ea.length;g>=f|| +(f=Math.max(f,g*(g<1048576?2:1.125)>>>0),g&&(f=Math.max(f,256)),g=a.ea.subarray(0,a.fa),a.ea=new Uint8Array(f),a.ea.set(g));a.ea.set(b.subarray(c,c+d),e);a.fa=Math.max(a.fa,e+d)}return d},ha(a,b,c){c===1?b+=a.position:c===2&&(a.node.mode&61440)===32768&&(b+=a.node.fa);if(b<0)throw new Q(28);return b},Ca(a,b,c,d,e){if((a.node.mode&61440)!==32768)throw new Q(43);a=a.node.ea;if(e&2||a.buffer!==(q(),y).buffer){d=!0;Za();e=void 0;if(!e)throw new Q(48);if(a){if(c>0||c+b{var b=0;a&&(b|=365);return b},Ec=0,Fc=null,Gc={},K=[],Hc=1,S=null,Va=!1,Ya=!0,Q=class{name="ErrnoError";constructor(a){this.na=a}},Ic=class{shared={};node=null;get flags(){return this.shared.flags}set flags(a){this.shared.flags=a}get position(){return this.shared.position}set position(a){this.shared.position=a}},Jc=class{da={};ba={};ra=null;constructor(a, +b,c,d){a||=this;this.parent=a;this.ka=a.ka;this.id=Hc++;this.name=b;this.mode=c;this.rdev=d;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&365)===365}set read(a){a?this.mode|=365:this.mode&=-366}get write(){return(this.mode&146)===146}set write(a){a?this.mode|=146:this.mode&=-147}}; +function U(a,b={}){if(!a)throw new Q(44);b.va??(b.va=!0);a.charAt(0)==="/"||(a="//"+a);var c=0;a:for(;c<40;c++){a=a.split("/").filter(n=>!!n);for(var d=Fc,e="/",f=0;f>>0)%S.length}function Bc(a,b){var c=(a.mode&61440)===16384?(c=Kc(a,"x"))?c:a.da.lookup?0:2:54;if(c)throw new Q(c);for(c=S[Cc(a.id,b)];c;c=c.pa){var d=c.name;if(c.parent.id===a.id&&d===b)return c}return a.da.lookup(a,b)} +function Ac(a,b,c,d){a=new Jc(a,b,c,d);b=Cc(a.parent.id,a.name);a.pa=S[b];return S[b]=a}function Kc(a,b){return Ya?0:b.includes("r")&&!(a.mode&292)||b.includes("w")&&!(a.mode&146)||b.includes("x")&&!(a.mode&73)?2:0}function Lc(a,b){if((a.mode&61440)!==16384)return 54;try{return Bc(a,b),20}catch(c){}return Kc(a,"wx")}function V(a){a=K[a];if(!a)throw new Q(8);return a} +function Mc(a,b=-1){a=Object.assign(new Ic,a);if(b==-1)a:{for(b=0;b<=4096;b++)if(!K[b])break a;throw new Q(33);}a.fd=b;return K[b]=a}function Nc(a,b=-1){a=Mc(a,b);a.ba?.eb?.(a);return a}function Oc(a,b){var c=void 0,d=c?null:a;c??=a.da.ma;if(!c)throw new Q(63);try{c(d,b)}catch(e){if(e instanceof RangeError)throw new Q(22);throw e;}}var zc={open(a){a.ba=Gc[a.node.rdev].ba;a.ba.open?.(a)},ha(){throw new Q(70);}};function vc(a,b){Gc[a]={ba:b}} +function Pc(a,b){var c=b==="/";if(c&&Fc)throw new Q(10);if(!c&&b){var d=U(b,{va:!1});b=d.path;d=d.node;if(d.ra)throw new Q(10);if((d.mode&61440)!==16384)throw new Q(54);}b={type:a,fb:{},Da:b,Na:[]};a=a.ka(b);a.ka=b;b.root=a;c?Fc=a:d&&(d.ra=b,d.ka&&d.ka.Na.push(b))}function Qc(a,b,c){var d=U(a,{parent:!0}).node;a=a&&a.match(/([^\/]+|\/)\/*$/)[1];if(!a)throw new Q(28);if(a==="."||a==="..")throw new Q(20);var e=Lc(d,a);if(e)throw new Q(e);if(!d.da.qa)throw new Q(63);return d.da.qa(d,a,b,c)} +function W(a){return Qc(a,16895,0)}function Rc(a,b,c){typeof c=="undefined"&&(c=b,b=438);Qc(a,b|8192,c)}function Wa(a,b){if(!pc(a))throw new Q(44);var c=U(b,{parent:!0}).node;if(!c)throw new Q(44);b=b&&b.match(/([^\/]+|\/)\/*$/)[1];var d=Lc(c,b);if(d)throw new Q(d);if(!c.da.symlink)throw new Q(63);c.da.symlink(c,b,a)} +function Xa(a,b,c=438){if(a==="")throw new Q(44);if(typeof b=="string"){var d={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[b];if(typeof d=="undefined")throw Error(`Unknown file open mode: ${b}`);b=d}c=b&64?c&4095|32768:0;if(typeof a=="object")d=a;else{var e=a.endsWith("/");var f=U(a,{ua:!(b&131072),Oa:!0});d=f.node;a=f.path}f=!1;if(b&64)if(d){if(b&128)throw new Q(20);}else{if(e)throw new Q(31);d=Qc(a,c|511,0);f=!0}if(!d)throw new Q(44);(d.mode&61440)===8192&&(b&=-513);if(b&65536&&(d.mode&61440)!== +16384)throw new Q(54);if(!f&&(d?(d.mode&61440)===40960?e=32:(e=["r","w","rw"][b&3],b&512&&(e+="w"),e=(d.mode&61440)===16384&&(e!=="r"||b&576)?31:Kc(d,e)):e=44,e))throw new Q(e);if(b&512&&!f){e=d;e=typeof e=="string"?U(e,{ua:!0}).node:e;if((e.mode&61440)===16384)throw new Q(31);if((e.mode&61440)!==32768)throw new Q(28);if(a=Kc(e,"w"))throw new Q(a);Oc(e,{size:0,timestamp:Date.now()})}a:{for(e=d;;){if(e===e.parent){e=e.ka.Da;var g=g?e[e.length-1]!=="/"?`${e}/${g}`:e+g:e;break a}g=g?`${e.name}/${g}`: +e.name;e=e.parent}g=void 0}b=Mc({node:d,path:g,flags:b&-131713,seekable:!0,position:0,ba:d.ba,Ua:[],error:!1});b.ba.open&&b.ba.open(b);f&&(c&=511,d=typeof d=="string"?U(d,{ua:!0}).node:d,Oc(d,{mode:c&4095|d.mode&-4096,ctime:Date.now(),cb:void 0}));return b}function dc(a){if(a.fd===null)throw new Q(8);a.wa&&(a.wa=null);try{a.ba.close&&a.ba.close(a)}catch(b){throw b;}finally{K[a.fd]=null}a.fd=null} +function Sc(a,b,c){if(a.fd===null)throw new Q(8);if(!a.seekable||!a.ba.ha)throw new Q(70);if(c!=0&&c!=1&&c!=2)throw new Q(28);a.position=a.ba.ha(a,b,c);a.Ua=[]} +function X(a,b){a=lc("/dev/"+a);var c=Dc(!!b);X.Ba??(X.Ba=64);var d=X.Ba++<<8|0;vc(d,{open(e){e.seekable=!1},close(){},read(e,f,g,n){for(var r=0,p=0;pa?P((q(),Sa),a,b,c):"",Tc=18,M=void 0;function gb(a,b,c){if(m)return J(3,1,a,b,c);M=c;try{var d=V(a);switch(b){case 0:var e=O();if(e<0)break;for(;K[e];)e++;return Nc(d,e).fd;case 1:case 2:return 0;case 3:return d.flags;case 4:return e=O(),d.flags=d.flags&-289793|e&289792,0;case 12:return e=O(),(q(),Ra)[e+0>>1]=2,0;case 13:case 14:return 0}return-28}catch(f){if(typeof Y=="undefined"||f.name!=="ErrnoError")throw f;return-f.na}} +function hb(a,b,c){if(m)return J(4,1,a,b,c);M=c;try{var d=V(a);switch(b){case 21509:return d.tty?0:-59;case 21505:if(!d.tty)return-59;if(d.tty.la.Ka){a=[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var e=O();(q(),A)[e>>2]=25856;(q(),A)[e+4>>2]=5;(q(),A)[e+8>>2]=191;(q(),A)[e+12>>2]=35387;for(var f=0;f<32;f++)(q(),y)[e+f+17]=a[f]||0}return 0;case 21510:case 21511:case 21512:return d.tty?0:-59;case 21506:case 21507:case 21508:if(!d.tty)return-59;if(d.tty.la.La)for(e=O(), +q(),q(),q(),q(),a=[],f=0;f<32;f++)a.push((q(),y)[e+f+17]);return 0;case 21519:if(!d.tty)return-59;e=O();return(q(),A)[e>>2]=0;case 21520:return d.tty?-28:-59;case 21537:case 21531:e=O();if(!d.ba.Ja)throw new Q(59);return d.ba.Ja(d,b,e);case 21523:if(!d.tty)return-59;d.tty.la.Ma&&(f=[24,80],e=O(),(q(),Ra)[e>>1]=f[0],(q(),Ra)[e+2>>1]=f[1]);return 0;case 21524:return d.tty?0:-59;case 21515:return d.tty?0:-59;default:return-28}}catch(g){if(typeof Y=="undefined"||g.name!=="ErrnoError")throw g;return-g.na}} +function ib(a,b,c,d){if(m)return J(5,1,a,b,c,d);M=d;try{b=fa(b);var e=b;if(e.charAt(0)==="/")b=e;else{var f=a===-100?"/":V(a).path;if(e.length==0)throw new Q(44);b=f+"/"+e}var g=d?O():0;c&64&&(g&=~Tc);return Xa(b,c,g).fd}catch(n){if(typeof Y=="undefined"||n.name!=="ErrnoError")throw n;return-n.na}} +var jb=()=>Za(""),kb=a=>{var b=!ea;try{Atomics.wait((q(),A),0,0,0),b=!0}catch(c){}Ja(a,!k,1,b,3145728,!1);Ka()},Uc=a=>{a instanceof Xb||a=="unwind"||oa(1,a)},hc=a=>{if(!Qa&&!za)try{a()}catch(b){Uc(b)}finally{if(!(Qa||I>0))try{m?Hb()&&Pb(w):Ab(w)}catch(b){Uc(b)}}},La=a=>{ec||(Atomics.waitAsync((q(),A),a>>2,a).value.then(Na),a+=112,Atomics.store((q(),A),a>>2,1))},Na=()=>{var a=Hb();a&&hc(()=>{La(a);Rb()})},lb=(a,b)=>{a==b?setTimeout(Na):m?postMessage({Fa:a,ga:4}):(a=H[a])&&a.postMessage({ga:4})},Vc= +[],mb=(a,b,c,d,e,f,g)=>{Vc.length=0;b=e>>3;for(d=e+d>>3;bMb(f,g,r));else return a},nb=()=>{I=0},ob=a=>{m?postMessage({ga:6,Sa:a}):fc(H[a])},pb=a=>{l&&(a=H[a],a.ref(),a.Ra=1)},L={},vb=()=>performance.timeOrigin+performance.now(); +function qb(a,b){if(m)return J(6,1,a,b);L[a]&&(clearTimeout(L[a].id),delete L[a]);if(!b)return 0;var c=setTimeout(()=>{delete L[a];hc(()=>Qb(a,performance.timeOrigin+performance.now()))},b);L[a]={id:c,hb:b};return 0} +var t=(a,b,c)=>sc(a,(q(),Sa),b,c),rb=(a,b,c,d)=>{var e=(new Date).getFullYear(),f=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();var g=Math.max(f,e);(q(),B)[a>>2]=g*60;(q(),A)[b>>2]=Number(f!=e);b=n=>{var r=Math.abs(n);return`UTC${n>=0?"-":"+"}${String(Math.floor(r/60)).padStart(2,"0")}${String(r%60).padStart(2,"0")}`};a=b(f);b=b(e);e=0&&a<=3))return 28;if(a===0)a=Date.now();else if(Xc)a=performance.timeOrigin+performance.now();else return 52;a=Math.round(a*1E3*1E3);(q(),C)[c>>3]=BigInt(a);return 0} +var Z=()=>{var a="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";Z.ya||(Z.ya={});Z.ya[a]||(Z.ya[a]=1,l&&(a="warning: "+a),u(a))},tb=()=>{l||k||(Z(),Za("Blocking on the main thread is not allowed by default. See https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"))},ub=()=>{I+=1;throw"unwind";},wb=a=>{var b=(q(),Sa).length;a>>>=0;if(a<=b||a>2147483648)return!1;for(var c=1;c<= +4;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(2147483648,Math.ceil(Math.max(a,d)/65536)*65536)-x.buffer.byteLength+65535)/65536|0;try{x.grow(d);Aa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1},Yc={},$c=()=>{if(!Zc){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:na},b;for(b in Yc)Yc[b]===void 0?delete a[b]:a[b]=Yc[b];var c=[];for(b in a)c.push(`${b}=${a[b]}`); +Zc=c}return Zc},Zc;function yb(a,b){if(m)return J(7,1,a,b);var c=0,d=0,e;for(e of $c()){var f=b+c;(q(),B)[a+d>>2]=f;c+=t(e,f,Infinity)+1;d+=4}return 0}function zb(a,b){if(m)return J(8,1,a,b);var c=$c();(q(),B)[a>>2]=c.length;a=0;for(var d of c)a+=ka(d)+1;(q(),B)[b>>2]=a;return 0}function Bb(a){if(m)return J(9,1,a);try{var b=V(a);dc(b);return 0}catch(c){if(typeof Y=="undefined"||c.name!=="ErrnoError")throw c;return c.na}} +function Cb(a,b,c,d){if(m)return J(10,1,a,b,c,d);try{a:{var e=V(a);a=b;for(var f,g=b=0;g>2],r=(q(),B)[a+4>>2];a+=8;var p=e,z=(q(),y),T=n,aa=r,F=f;if(aa<0||F<0)throw new Q(28);if(p.fd===null)throw new Q(8);if((p.flags&2097155)===1)throw new Q(8);if((p.node.mode&61440)===16384)throw new Q(31);if(!p.ba.read)throw new Q(28);var ba=typeof F!="undefined";if(!ba)F=p.position;else if(!p.seekable)throw new Q(70);var ca=p.ba.read(p,z,T,aa,F);ba||(p.position+=ca);var G=ca;if(G<0){var da= +-1;break a}b+=G;if(G>2]=da;return 0}catch(N){if(typeof Y=="undefined"||N.name!=="ErrnoError")throw N;return N.na}}function Db(a,b,c,d){if(m)return J(11,1,a,b,c,d);b=b<-9007199254740992||b>9007199254740992?NaN:Number(b);try{if(isNaN(b))return 22;var e=V(a);Sc(e,b,c);(q(),C)[d>>3]=BigInt(e.position);e.wa&&b===0&&c===0&&(e.wa=null);return 0}catch(f){if(typeof Y=="undefined"||f.name!=="ErrnoError")throw f;return f.na}} +function Eb(a,b,c,d){if(m)return J(12,1,a,b,c,d);try{a:{var e=V(a);a=b;for(var f,g=b=0;g>2],r=(q(),B)[a+4>>2];a+=8;var p=e,z=(q(),y),T=n,aa=r,F=f;if(aa<0||F<0)throw new Q(28);if(p.fd===null)throw new Q(8);if((p.flags&2097155)===0)throw new Q(8);if((p.node.mode&61440)===16384)throw new Q(31);if(!p.ba.write)throw new Q(28);p.seekable&&p.flags&1024&&Sc(p,0,2);var ba=typeof F!="undefined";if(!ba)F=p.position;else if(!p.seekable)throw new Q(70);var ca=p.ba.write(p,z,T,aa,F,void 0); +ba||(p.position+=ca);var G=ca;if(G<0){var da=-1;break a}b+=G;if(G>2]=da;return 0}catch(N){if(typeof Y=="undefined"||N.name!=="ErrnoError")throw N;return N.na}}S=Array(4096);Pc(R,"/");W("/tmp");W("/home");W("/home/web_user"); +(function(){W("/dev");vc(259,{read:()=>0,write:(d,e,f,g)=>g,ha:()=>0});Rc("/dev/null",259);uc(1280,xc);uc(1536,yc);Rc("/dev/tty",1280);Rc("/dev/tty1",1536);var a=new Uint8Array(1024),b=0,c=()=>{b===0&&(oc(a),b=a.byteLength);return a[--b]};X("random",c);X("urandom",c);W("/dev/shm");W("/dev/shm/tmp")})(); +(function(){W("/proc");var a=W("/proc/self");W("/proc/self/fd");Pc({ka(){var b=Ac(a,"fd",16895,73);b.ba={ha:R.ba.ha};b.da={lookup(c,d){c=+d;var e=V(c);c={parent:null,ka:{Da:"fake"},da:{readlink:()=>e.path},id:c+1};return c.parent=c},readdir(){return Array.from(K.entries()).filter(([,c])=>c).map(([c])=>c.toString())}};return b}},"/proc/self/fd")})();m||(h.wasmMemory?x=h.wasmMemory:x=new WebAssembly.Memory({initial:1024,maximum:32768,shared:!0}),Aa());h.print&&(ya=h.print);h.printErr&&(u=h.printErr); +h.UTF8ToString=fa;h.stringToUTF8=t;var Wc=[Fb,cc,jc,gb,hb,ib,qb,yb,zb,Bb,Cb,Db,Eb],la,ja,ha,Hb,Ib,Jb,Ja,Kb,Oa,Lb,ia,Mb,Nb,Ob,Pb,Qb,Rb,Sb,Tb,Ub,Vb,Wb,eb;function ad(a=[]){var b=Ib;I+=1;a.unshift(na);var c=a.length,d=Ub((c+1)*4),e=d,f;for(f of a){a=(q(),B);var g=e>>2,n=f,r=ka(n)+1,p=Ub(r);t(n,p,r);a[g]=p;e+=4}(q(),B)[e>>2]=0;try{var z=b(c,d);Ab(z,!0)}catch(T){Uc(T)}} +function Ha(){var a=ma;if(!(Ec>0))if(m)Ba?.(h),Ua();else{for(var b=Zb;b.length>0;)b.shift()(h);Ec>0||(h.calledRun=!0,za||(Ua(),Ba?.(h),ad(a)))}}var D;m||(D=await (Ga()),Ha());Pa?moduleRtn=h:moduleRtn=new Promise((a,b)=>{Ba=a;Ca=b}); +;return moduleRtn}export default Fsf_14_Web;var isPthread=globalThis.name=="em-pthread";var isNode=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(isNode)isPthread=(await import("node:worker_threads")).workerData==="em-pthread";isPthread&&Fsf_14_Web(); diff --git a/lib/engine/fairy-stockfish-14/fsf_14.wasm b/lib/engine/fairy-stockfish-14/fsf_14.wasm new file mode 100644 index 00000000..1a01be57 Binary files /dev/null and b/lib/engine/fairy-stockfish-14/fsf_14.wasm differ diff --git a/lib/engine/fairy-stockfish-14/nnue/chaturanga-1889e98f8d54.nnue b/lib/engine/fairy-stockfish-14/nnue/chaturanga-1889e98f8d54.nnue new file mode 100644 index 00000000..c68a6614 Binary files /dev/null and b/lib/engine/fairy-stockfish-14/nnue/chaturanga-1889e98f8d54.nnue differ diff --git a/lib/engine/lc0/weights/weights_32195.dat.gz b/lib/engine/fairy-stockfish-14/nnue/duck-ba21f91f5d81.nnue similarity index 77% rename from lib/engine/lc0/weights/weights_32195.dat.gz rename to lib/engine/fairy-stockfish-14/nnue/duck-ba21f91f5d81.nnue index f3669eb9..af1340ff 100644 Binary files a/lib/engine/lc0/weights/weights_32195.dat.gz and b/lib/engine/fairy-stockfish-14/nnue/duck-ba21f91f5d81.nnue differ diff --git a/lib/engine/fairy-stockfish-14/nnue/minihouse-d415b4dbfe2c.nnue b/lib/engine/fairy-stockfish-14/nnue/minihouse-d415b4dbfe2c.nnue new file mode 100644 index 00000000..4902b6fe Binary files /dev/null and b/lib/engine/fairy-stockfish-14/nnue/minihouse-d415b4dbfe2c.nnue differ diff --git a/lib/engine/fairy-stockfish-14/nnue/seirawan-432c65fe71fc.nnue b/lib/engine/fairy-stockfish-14/nnue/seirawan-432c65fe71fc.nnue new file mode 100644 index 00000000..716d966a Binary files /dev/null and b/lib/engine/fairy-stockfish-14/nnue/seirawan-432c65fe71fc.nnue differ diff --git a/lib/engine/lc0/lc0.html b/lib/engine/lc0/lc0.html deleted file mode 100644 index 6afac123..00000000 --- a/lib/engine/lc0/lc0.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Title - - - - - - - -This is lc0! - - - \ No newline at end of file diff --git a/lib/engine/lc0/lc0.js b/lib/engine/lc0/lc0.js deleted file mode 100644 index 6569390c..00000000 --- a/lib/engine/lc0/lc0.js +++ /dev/null @@ -1,7911 +0,0 @@ -var Module = typeof Module !== "undefined" ? Module : {}; - -var Network = (function () { - const kNumOutputPolicies = 1858; - const kInputPlanes = 112; - - function Network() { - this.backend = tf.getBackend(); - this.log("Tensorflow backend: " + this.backend); - var format = "channelsFirst"; - if (this.backend == "cpu") format = "channelsLast"; - this.setDataFormat(format); - this.log("Default data format: " + format); - this.input_channels = kInputPlanes; - this.num_output_policy = kNumOutputPolicies; - this.block = 0; - this.channels = 0; - this.num_value_input_planes = 0; - this.num_policy_input_planes = 0; - this.num_value_channels = 0 - } - - Network.prototype = { - setDataFormat: (function (format) { - this.dataFormat = format; - this.isChannelsFirst = format == "channelsFirst"; - this.isChannelsLast = format == "channelsLast" - }), load: (function (name, weights) { - var decoder = name.match(/^.*\.txt\.gz$/) ? this.decodeText : this.decodeProtobuf; - return decoder.bind(this)(weights) - }), loadProto: (function (proto) { - // not implemented - }), decodeText: (function (bytearray) { - var text = window.pako.inflate(bytearray, {to: "string"}); - var lines = text.split(/\r\n|\n/); - var len = lines.length; - this.log("Network text file has " + len + " lines"); - if (lines < 19) throw "Bad network file"; - var index = 0; - if (lines[index++] != "2") throw "Bad network file"; - this.blocks = (len - 19) / 8; - this.log("Network blocks: " + this.blocks); - if (len != 19 + 8 * this.blocks) throw "Bad network file"; - this.data = {}; - this.data.input = this.decodeTextConv(lines, index, 3); - index += 4; - this.filters = this.data.input.biases.length; - this.log("Network filters: " + this.filters); - this.data.tower = new Array(this.blocks); - for (let block = 0; block < this.blocks; block++) { - var conv1 = this.decodeTextConv(lines, index, 3); - index += 4; - var conv2 = this.decodeTextConv(lines, index, 3); - index += 4; - this.data.tower[block] = {conv1: conv1, conv2: conv2} - } - var policy_conv1 = this.decodeTextConv(lines, index, 1); - index += 4; - this.num_policy_input_planes = policy_conv1.weights.length / this.filters; - this.log("Network num_policy_input_planes: " + this.num_policy_input_planes); - var policy_fc = this.decodeTextFC(lines, index); - index += 2; - this.data.policy_head = {conv1: policy_conv1, fc: policy_fc}; - var value_conv1 = this.decodeTextConv(lines, index, 1); - index += 4; - this.num_value_input_planes = value_conv1.weights.length / this.filters; - this.log("Network num_value_input_planes: " + this.num_value_input_planes); - var value_fc1 = this.decodeTextFC(lines, index); - index += 2; - this.num_value_channels = value_fc1.biases.length; - this.log("Network num_value_channels: " + this.num_value_channels); - const value_fc2 = this.decodeTextFC(lines, index); - index += 2; - this.data.value_head = {conv1: value_conv1, fc1: value_fc1, fc2: value_fc2}; - this.build() - }), decodeTextConv: (function (lines, index, filtersize) { - var conv = {}; - conv.filtersize = filtersize; - conv.weights = lines[index++].split(" "); - conv.biases = lines[index++].split(" "); - conv.bn_means = lines[index++].split(" "); - conv.bn_stddivs = lines[index++].split(" "); - conv.outputs = conv.biases.length; - conv.inputs = conv.weights.length / (filtersize * filtersize * conv.outputs); - return conv - }), decodeTextFC: (function (lines, index) { - var fc = {}; - fc.weights = lines[index++].split(" "); - fc.biases = lines[index++].split(" "); - fc.outputs = fc.biases.length; - fc.inputs = fc.weights.length / fc.outputs; - return fc - }), decodeProtobuf: (function (arraybuffer) { - var byteArray = window.pako.inflate(arraybuffer); - // return window.protobuf.load("pb.proto").then((function (root) { - // var type = root.lookupType("pblczero.Net"); - // var net = type.decode(byteArray); - // this.decodeBin(net) - // }).bind(this)) - var protoString = `syntax = "proto2"; - -package pblczero; - -message EngineVersion { - optional uint32 major = 1; - optional uint32 minor = 2; - optional uint32 patch = 3; -} - -message Weights { - message Layer { - optional float min_val = 1; - optional float max_val = 2; - optional bytes params = 3; - } - - message ConvBlock { - optional Layer weights = 1; - optional Layer biases = 2; - optional Layer bn_means = 3; - optional Layer bn_stddivs = 4; - } - - message Residual { - optional ConvBlock conv1 = 1; - optional ConvBlock conv2 = 2; - } - - // Input convnet. - optional ConvBlock input = 1; - - // Residual tower. - repeated Residual residual = 2; - - // Policy head - optional ConvBlock policy = 3; - optional Layer ip_pol_w = 4; - optional Layer ip_pol_b = 5; - - // Value head - optional ConvBlock value = 6; - optional Layer ip1_val_w = 7; - optional Layer ip1_val_b = 8; - optional Layer ip2_val_w = 9; - optional Layer ip2_val_b = 10; -} - -message TrainingParams { - optional uint32 training_steps = 1; - optional float learning_rate = 2; - optional float mse_loss = 3; - optional float policy_loss = 4; - optional float accuracy = 5; - optional string lc0_params = 6; -} - -message Format { - enum Encoding { - UNKNOWN = 0; - LINEAR16 = 1; - ZFP = 2; - } - - optional Encoding weights_encoding = 1; -} - -message Net { - optional fixed32 magic = 1; - optional string license = 2; - optional EngineVersion min_version = 3; - optional Format format = 4; - optional TrainingParams training_params = 5; - optional Weights weights = 10; -} -`; - var pbRoot = window.protobuf.parse(protoString).root; - var type = pbRoot.lookupType("pblczero.Net"); - var net = type.decode(byteArray); - this.decodeBin(net) - }), decodeBin: (function (net) { - var weights = net.weights; - this.data = {}; - this.data.input = this.decodeBinConv(weights.input, 3); - this.filters = this.data.input.biases.length; - var residuals = weights.residual; - this.blocks = residuals.length; - this.log("Network blocks: " + this.blocks); - this.log("Network filters: " + this.filters); - this.data.tower = new Array(this.blocks); - for (let block = 0; block < this.blocks; block++) { - var residual = residuals[block]; - var conv1 = this.decodeBinConv(residual.conv1, 3); - var conv2 = this.decodeBinConv(residual.conv2, 3); - this.data.tower[block] = {conv1: conv1, conv2: conv2} - } - var policy_conv1 = this.decodeBinConv(weights.policy, 1); - var policy_fc = this.decodeBinFC(weights.ipPolW, weights.ipPolB); - this.data.policy_head = {conv1: policy_conv1, fc: policy_fc}; - var value_conv1 = this.decodeBinConv(weights.value, 1); - var value_fc1 = this.decodeBinFC(weights.ip1ValW, weights.ip1ValB); - var value_fc2 = this.decodeBinFC(weights.ip2ValW, weights.ip2ValB); - this.data.value_head = {conv1: value_conv1, fc1: value_fc1, fc2: value_fc2}; - this.build() - }), decodeBinConv: (function (convBlock, filtersize) { - var conv = {}; - conv.filtersize = filtersize; - conv.weights = this.decodeBinLayer(convBlock.weights); - conv.biases = this.decodeBinLayer(convBlock.biases); - conv.bn_means = this.decodeBinLayer(convBlock.bnMeans); - conv.bn_stddivs = this.decodeBinLayer(convBlock.bnStddivs); - conv.outputs = conv.biases.length; - conv.inputs = conv.weights.length / (filtersize * filtersize * conv.outputs); - return conv - }), decodeBinFC: (function (weights, biases) { - var fc = {}; - fc.weights = this.decodeBinLayer(weights); - fc.biases = this.decodeBinLayer(biases); - fc.outputs = fc.biases.length; - fc.inputs = fc.weights.length / fc.outputs; - return fc - }), decodeBinLayer: (function (layer) { - var alpha = layer.minVal; - var beta = (layer.maxVal - layer.minVal) / 65535; - var bytes = layer.params; - var len = bytes.length / 2; - var array = new Float32Array(len); - for (var i = 0; i < len; i++) { - var word = bytes[2 * i] + 256 * bytes[2 * i + 1]; - array[i] = alpha + beta * word - } - return array - }), loadFCWeights: (function (fc) { - var weights = fc.weights; - var inputs = fc.inputs; - var outputs = fc.outputs; - var biases = fc.biases; - var size = inputs * outputs; - var warray = new Float32Array(size); - var index = 0; - for (var input = 0; input < inputs; input++) { - for (var output = 0; output < outputs; output++) { - warray[index++] = weights[input + inputs * output] - } - } - var tw = tf.tensor2d(warray, [fc.inputs, fc.outputs]); - var tb = tf.tensor1d(new Float32Array(biases)); - return [tw, tb] - }), createDenseLayer: (function (fc, activation) { - return tf.layers.dense({ - units: fc.outputs, - weights: this.loadFCWeights(fc), - activation: activation, - useBias: true - }) - }), loadConvWeights: (function (conv) { - var weights = conv.weights; - var inputs = conv.inputs; - var outputs = conv.outputs; - var biases = conv.biases; - var filtersize = conv.filtersize; - var filterarea = filtersize * filtersize; - var size = filterarea * inputs * outputs; - var warray = new Float32Array(size); - var index = 0; - for (var filter = 0; filter < filterarea; filter++) { - for (var input = 0; input < inputs; input++) { - for (var output = 0; output < outputs; output++) { - warray[index++] = weights[filter + filterarea * (input + inputs * output)] - } - } - } - var tw = tf.tensor4d(warray, [filtersize, filtersize, inputs, outputs]); - var tb = tf.tensor1d(new Float32Array(biases)); - return [tw, tb] - }), applyConvolution: (function (flow, conv, skip) { - var conv_layer = tf.layers.conv2d({ - dataFormat: this.dataFormat, - kernelSize: [conv.filtersize, conv.filtersize], - weights: this.loadConvWeights(conv), - padding: "same", - filters: conv.outputs, - useBias: true - }); - flow = conv_layer.apply(flow); - var tm = tf.tensor1d(new Float32Array(conv.bn_means)); - var ts = tf.tensor1d(new Float32Array(conv.bn_stddivs)); - var bn_layer = tf.layers.batchNormalization({ - axis: this.isChannelsFirst ? 1 : -1, - epsilon: 1e-5, - scale: false, - center: false, - weights: [tm, ts] - }); - flow = bn_layer.apply(flow); - if (skip) { - var add_layer = tf.layers.add(); - flow = add_layer.apply([flow, skip]) - } - const relu = tf.layers.reLU(); - flow = relu.apply(flow); - return flow - }), build: (function () { - this.log("Building network..."); - this.log("Network format: " + this.dataFormat); - var batchShape = this.isChannelsFirst ? [null, kInputPlanes, 8, 8] : [null, 8, 8, kInputPlanes]; - this.input = tf.input({batchShape: batchShape}); - var flow = this.input; - flow = this.applyConvolution(flow, this.data.input); - for (var block = 0; block < this.blocks; block++) { - var skip = flow; - var res = this.data.tower[block]; - flow = this.applyConvolution(flow, res.conv1); - flow = this.applyConvolution(flow, res.conv2, skip) - } - var policy_head = this.data.policy_head; - var p_flow = this.applyConvolution(flow, policy_head.conv1); - let layer; - if (this.isChannelsLast) { - layer = tf.layers.permute({dims: [3, 1, 2]}); - p_flow = layer.apply(p_flow) - } - layer = tf.layers.flatten(); - p_flow = layer.apply(p_flow); - layer = this.createDenseLayer(policy_head.fc); - p_flow = layer.apply(p_flow); - var value_head = this.data.value_head; - var v_flow = this.applyConvolution(flow, value_head.conv1); - if (this.isChannelsLast) { - layer = tf.layers.permute({dims: [3, 1, 2]}); - v_flow = layer.apply(v_flow) - } - layer = tf.layers.flatten(); - v_flow = layer.apply(v_flow); - layer = this.createDenseLayer(value_head.fc1, "relu"); - v_flow = layer.apply(v_flow); - layer = this.createDenseLayer(value_head.fc2); - v_flow = layer.apply(v_flow); - this.model = tf.model({inputs: this.input, outputs: [p_flow, v_flow]}); - this.log("Network successfully built!") - }), loadTest: (function () { - readFile("test.txt.gz").then(this.decodeTest.bind(this)) - }), decodeTest: (function (bytearray) { - var text = window.pako.inflate(bytearray, {to: "string"}); - var lines = text.split(/\r\n|\n/); - var line1 = lines[0].split(" "); - var line2 = lines[1].split(" "); - var line3 = lines[2].split(" "); - this.test_x = tf.tensor4d(new Float32Array(line1), [1, kInputPlanes, 8, 8]); - if (this.isChannelsLast) { - this.test_x = tf.transpose(this.test_x, [0, 2, 3, 1]) - } - this.test_y = line2[0]; - this.test_z = tf.tensor1d(new Float32Array(line3)); - this.log("Loaded test data!"); - var predict = this.model.predict(this.test_x); - this.log("p: " + predict[0]); - this.log("v: " + predict[1]) - }), forward: (function (batch_size, input, policy, value) { - var self = this; - - function work() { - var x = tf.tensor4d(input, [batch_size, kInputPlanes, 8, 8]); - if (self.isChannelsLast) { - x = tf.transpose(x, [0, 2, 3, 1]) - } - var predict = self.model.predict(x); - var p_data = predict[0].dataSync(); - for (var i = 0; i < policy.length; i++) policy[i] = p_data[i]; - var v_data = predict[1].dataSync(); - for (var i = 0; i < value.length; i++) value[i] = v_data[i] - } - - tf.tidy(work) - }), log: (function (text) { - self.console.info(text) - }) - }; - return Network -})(), future; -var Future = (function () { - Future = (function () { - this.resolves = []; - this.value = undefined - }); - Future.prototype = { - get: (function () { - future = this; - return new Promise((function (resolve, reject) { - future.resolves.push(resolve); - if (future.value) resolve(future.value) - })) - }), set: (function (value) { - if (this.value) return; - this.value = value; - for (var i = 0; i < this.resolves.length; i++) { - this.resolves[i](this.value) - } - }) - }; - return Future -})(); -var engine = undefined; -var network = null; -var network_is_loaded = false; -var started = false; -onmessage = (function (e) { - console.log("Received Message:", e); - try { - const message = e.data; - if (message.hasOwnProperty("type")) { - if (message.type === "weights" && !started) { - load_network(message.data.name, message.data.weights); - } - } else { - engine.Send(message); - loop() - } - } catch (exc) { - console.error("Exception: " + exc, exc.stack) - } -}); - -function module_ready() { - engine = new Module.Engine; - if (!network_is_loaded) return; - start_engine() -} - -function network_loaded() { - network_is_loaded = true; - if (!engine) return; - start_engine() -} - -function start_engine() { - started = true; - // engine.Send("uci") -} - -function load_network(name, weights) { - network = new Network(); - network.load.bind(network)(name, weights); - network_loaded(); -} - -Module["onRuntimeInitialized"] = module_ready; - -function lczero_forward(batch_size, input, policy, value) { - var input_array = new Float32Array(Module.HEAPU8.buffer, input, 112 * 64 * batch_size); - var policy_array = new Float32Array(Module.HEAPU8.buffer, policy, 1858 * batch_size); - var value_array = new Float32Array(Module.HEAPU8.buffer, value, batch_size); - network.forward(batch_size, input_array, policy_array, value_array) -} - -var loop_id; - -function stop_loop() { - if (!loop_id) return; - clearInterval(loop_id); - loop_id = undefined -} - -function start_loop() { - if (loop_id) return; - loop_id = setInterval(step, 1) -} - -function loop() { - if (!engine.CanStep()) { - engine.Step(); - stop_loop(); - return - } - start_loop(); - engine.Step() -} - -function step() { - if (!engine.CanStep()) { - stop_loop(); - return - } - engine.Step() -} - -var moduleOverrides = {}; -var key; -for (key in Module) { - if (Module.hasOwnProperty(key)) { - moduleOverrides[key] = Module[key] - } -} -Module["arguments"] = []; -Module["thisProgram"] = "./this.program"; -Module["quit"] = (function (status, toThrow) { - throw toThrow -}); -Module["preRun"] = []; -Module["postRun"] = []; -var ENVIRONMENT_IS_WEB = false; -var ENVIRONMENT_IS_WORKER = false; -var ENVIRONMENT_IS_NODE = false; -var ENVIRONMENT_IS_SHELL = false; -ENVIRONMENT_IS_WEB = typeof window === "object"; -ENVIRONMENT_IS_WORKER = typeof importScripts === "function"; -ENVIRONMENT_IS_NODE = typeof process === "object" && typeof require === "function" && !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER; -ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; -var scriptDirectory = ""; - -function locateFile(path) { - if (Module["locateFile"]) { - return Module["locateFile"](path, scriptDirectory) - } else { - return scriptDirectory + path - } -} - -if (ENVIRONMENT_IS_NODE) { - scriptDirectory = __dirname + "/"; - var nodeFS; - var nodePath; - Module["read"] = function shell_read(filename, binary) { - var ret; - if (!nodeFS) nodeFS = require("fs"); - if (!nodePath) nodePath = require("path"); - filename = nodePath["normalize"](filename); - ret = nodeFS["readFileSync"](filename); - return binary ? ret : ret.toString() - }; - Module["readBinary"] = function readBinary(filename) { - var ret = Module["read"](filename, true); - if (!ret.buffer) { - ret = new Uint8Array(ret) - } - assert(ret.buffer); - return ret - }; - if (process["argv"].length > 1) { - Module["thisProgram"] = process["argv"][1].replace(/\\/g, "/") - } - Module["arguments"] = process["argv"].slice(2); - if (typeof module !== "undefined") { - module["exports"] = Module - } - process["on"]("uncaughtException", (function (ex) { - if (!(ex instanceof ExitStatus)) { - throw ex - } - })); - process["on"]("unhandledRejection", abort); - Module["quit"] = (function (status) { - process["exit"](status) - }); - Module["inspect"] = (function () { - return "[Emscripten Module object]" - }) -} else if (ENVIRONMENT_IS_SHELL) { - if (typeof read != "undefined") { - Module["read"] = function shell_read(f) { - return read(f) - } - } - Module["readBinary"] = function readBinary(f) { - var data; - if (typeof readbuffer === "function") { - return new Uint8Array(readbuffer(f)) - } - data = read(f, "binary"); - assert(typeof data === "object"); - return data - }; - if (typeof scriptArgs != "undefined") { - Module["arguments"] = scriptArgs - } else if (typeof arguments != "undefined") { - Module["arguments"] = arguments - } - if (typeof quit === "function") { - Module["quit"] = (function (status) { - quit(status) - }) - } -} else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = self.location.href - } else if (document.currentScript) { - scriptDirectory = document.currentScript.src - } - if (scriptDirectory.indexOf("blob:") !== 0) { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf("/") + 1) - } else { - scriptDirectory = "" - } - Module["read"] = function shell_read(url) { - var xhr = new XMLHttpRequest; - xhr.open("GET", url, false); - xhr.send(null); - return xhr.responseText - }; - if (ENVIRONMENT_IS_WORKER) { - Module["readBinary"] = function readBinary(url) { - var xhr = new XMLHttpRequest; - xhr.open("GET", url, false); - xhr.responseType = "arraybuffer"; - xhr.send(null); - return new Uint8Array(xhr.response) - } - } - Module["readAsync"] = function readAsync(url, onload, onerror) { - var xhr = new XMLHttpRequest; - xhr.open("GET", url, true); - xhr.responseType = "arraybuffer"; - xhr.onload = function xhr_onload() { - if (xhr.status == 200 || xhr.status == 0 && xhr.response) { - onload(xhr.response); - return - } - onerror() - }; - xhr.onerror = onerror; - xhr.send(null) - }; - Module["setWindowTitle"] = (function (title) { - document.title = title - }) -} else { -} -var out = Module["print"] || (typeof console !== "undefined" ? console.log.bind(console) : typeof print !== "undefined" ? print : null); -var err = Module["printErr"] || (typeof printErr !== "undefined" ? printErr : typeof console !== "undefined" && console.warn.bind(console) || out); -for (key in moduleOverrides) { - if (moduleOverrides.hasOwnProperty(key)) { - Module[key] = moduleOverrides[key] - } -} -moduleOverrides = undefined; -var STACK_ALIGN = 16; - -function staticAlloc(size) { - var ret = STATICTOP; - STATICTOP = STATICTOP + size + 15 & -16; - return ret -} - -function dynamicAlloc(size) { - var ret = HEAP32[DYNAMICTOP_PTR >> 2]; - var end = ret + size + 15 & -16; - HEAP32[DYNAMICTOP_PTR >> 2] = end; - if (end >= TOTAL_MEMORY) { - var success = enlargeMemory(); - if (!success) { - HEAP32[DYNAMICTOP_PTR >> 2] = ret; - return 0 - } - } - return ret -} - -function alignMemory(size, factor) { - if (!factor) factor = STACK_ALIGN; - var ret = size = Math.ceil(size / factor) * factor; - return ret -} - -function getNativeTypeSize(type) { - switch (type) { - case"i1": - case"i8": - return 1; - case"i16": - return 2; - case"i32": - return 4; - case"i64": - return 8; - case"float": - return 4; - case"double": - return 8; - default: { - if (type[type.length - 1] === "*") { - return 4 - } else if (type[0] === "i") { - var bits = parseInt(type.substr(1)); - assert(bits % 8 === 0); - return bits / 8 - } else { - return 0 - } - } - } -} - -var asm2wasmImports = { - "f64-rem": (function (x, y) { - return x % y - }), "debugger": (function () { - debugger - }) -}; -var functionPointers = new Array(0); -var tempRet0 = 0; -var setTempRet0 = (function (value) { - tempRet0 = value -}); -var getTempRet0 = (function () { - return tempRet0 -}); -var GLOBAL_BASE = 1024; -var ABORT = false; -var EXITSTATUS = 0; - -function assert(condition, text) { - if (!condition) { - abort("Assertion failed: " + text) - } -} - -function setValue(ptr, value, type, noSafe) { - type = type || "i8"; - if (type.charAt(type.length - 1) === "*") type = "i32"; - switch (type) { - case"i1": - HEAP8[ptr >> 0] = value; - break; - case"i8": - HEAP8[ptr >> 0] = value; - break; - case"i16": - HEAP16[ptr >> 1] = value; - break; - case"i32": - HEAP32[ptr >> 2] = value; - break; - case"i64": - tempI64 = [value >>> 0, (tempDouble = value, +Math_abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math_min(+Math_floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math_ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0)], HEAP32[ptr >> 2] = tempI64[0], HEAP32[ptr + 4 >> 2] = tempI64[1]; - break; - case"float": - HEAPF32[ptr >> 2] = value; - break; - case"double": - HEAPF64[ptr >> 3] = value; - break; - default: - abort("invalid type for setValue: " + type) - } -} - -var ALLOC_NORMAL = 0; -var ALLOC_STATIC = 2; -var ALLOC_NONE = 4; - -function allocate(slab, types, allocator, ptr) { - var zeroinit, size; - if (typeof slab === "number") { - zeroinit = true; - size = slab - } else { - zeroinit = false; - size = slab.length - } - var singleType = typeof types === "string" ? types : null; - var ret; - if (allocator == ALLOC_NONE) { - ret = ptr - } else { - ret = [typeof _malloc === "function" ? _malloc : staticAlloc, stackAlloc, staticAlloc, dynamicAlloc][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length)) - } - if (zeroinit) { - var stop; - ptr = ret; - assert((ret & 3) == 0); - stop = ret + (size & ~3); - for (; ptr < stop; ptr += 4) { - HEAP32[ptr >> 2] = 0 - } - stop = ret + size; - while (ptr < stop) { - HEAP8[ptr++ >> 0] = 0 - } - return ret - } - if (singleType === "i8") { - if (slab.subarray || slab.slice) { - HEAPU8.set(slab, ret) - } else { - HEAPU8.set(new Uint8Array(slab), ret) - } - return ret - } - var i = 0, type, typeSize, previousType; - while (i < size) { - var curr = slab[i]; - type = singleType || types[i]; - if (type === 0) { - i++; - continue - } - if (type == "i64") type = "i32"; - setValue(ret + i, curr, type); - if (previousType !== type) { - typeSize = getNativeTypeSize(type); - previousType = type - } - i += typeSize - } - return ret -} - -function getMemory(size) { - if (!staticSealed) return staticAlloc(size); - if (!runtimeInitialized) return dynamicAlloc(size); - return _malloc(size) -} - -function Pointer_stringify(ptr, length) { - if (length === 0 || !ptr) return ""; - var hasUtf = 0; - var t; - var i = 0; - while (1) { - t = HEAPU8[ptr + i >> 0]; - hasUtf |= t; - if (t == 0 && !length) break; - i++; - if (length && i == length) break - } - if (!length) length = i; - var ret = ""; - if (hasUtf < 128) { - var MAX_CHUNK = 1024; - var curr; - while (length > 0) { - curr = String.fromCharCode.apply(String, HEAPU8.subarray(ptr, ptr + Math.min(length, MAX_CHUNK))); - ret = ret ? ret + curr : curr; - ptr += MAX_CHUNK; - length -= MAX_CHUNK - } - return ret - } - return UTF8ToString(ptr) -} - -var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : undefined; - -function UTF8ArrayToString(u8Array, idx) { - var endPtr = idx; - while (u8Array[endPtr]) ++endPtr; - if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) { - return UTF8Decoder.decode(u8Array.subarray(idx, endPtr)) - } else { - var u0, u1, u2, u3, u4, u5; - var str = ""; - while (1) { - u0 = u8Array[idx++]; - if (!u0) return str; - if (!(u0 & 128)) { - str += String.fromCharCode(u0); - continue - } - u1 = u8Array[idx++] & 63; - if ((u0 & 224) == 192) { - str += String.fromCharCode((u0 & 31) << 6 | u1); - continue - } - u2 = u8Array[idx++] & 63; - if ((u0 & 240) == 224) { - u0 = (u0 & 15) << 12 | u1 << 6 | u2 - } else { - u3 = u8Array[idx++] & 63; - if ((u0 & 248) == 240) { - u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | u3 - } else { - u4 = u8Array[idx++] & 63; - if ((u0 & 252) == 248) { - u0 = (u0 & 3) << 24 | u1 << 18 | u2 << 12 | u3 << 6 | u4 - } else { - u5 = u8Array[idx++] & 63; - u0 = (u0 & 1) << 30 | u1 << 24 | u2 << 18 | u3 << 12 | u4 << 6 | u5 - } - } - } - if (u0 < 65536) { - str += String.fromCharCode(u0) - } else { - var ch = u0 - 65536; - str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023) - } - } - } -} - -function UTF8ToString(ptr) { - return UTF8ArrayToString(HEAPU8, ptr) -} - -function stringToUTF8Array(str, outU8Array, outIdx, maxBytesToWrite) { - if (!(maxBytesToWrite > 0)) return 0; - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) { - var u1 = str.charCodeAt(++i); - u = 65536 + ((u & 1023) << 10) | u1 & 1023 - } - if (u <= 127) { - if (outIdx >= endIdx) break; - outU8Array[outIdx++] = u - } else if (u <= 2047) { - if (outIdx + 1 >= endIdx) break; - outU8Array[outIdx++] = 192 | u >> 6; - outU8Array[outIdx++] = 128 | u & 63 - } else if (u <= 65535) { - if (outIdx + 2 >= endIdx) break; - outU8Array[outIdx++] = 224 | u >> 12; - outU8Array[outIdx++] = 128 | u >> 6 & 63; - outU8Array[outIdx++] = 128 | u & 63 - } else if (u <= 2097151) { - if (outIdx + 3 >= endIdx) break; - outU8Array[outIdx++] = 240 | u >> 18; - outU8Array[outIdx++] = 128 | u >> 12 & 63; - outU8Array[outIdx++] = 128 | u >> 6 & 63; - outU8Array[outIdx++] = 128 | u & 63 - } else if (u <= 67108863) { - if (outIdx + 4 >= endIdx) break; - outU8Array[outIdx++] = 248 | u >> 24; - outU8Array[outIdx++] = 128 | u >> 18 & 63; - outU8Array[outIdx++] = 128 | u >> 12 & 63; - outU8Array[outIdx++] = 128 | u >> 6 & 63; - outU8Array[outIdx++] = 128 | u & 63 - } else { - if (outIdx + 5 >= endIdx) break; - outU8Array[outIdx++] = 252 | u >> 30; - outU8Array[outIdx++] = 128 | u >> 24 & 63; - outU8Array[outIdx++] = 128 | u >> 18 & 63; - outU8Array[outIdx++] = 128 | u >> 12 & 63; - outU8Array[outIdx++] = 128 | u >> 6 & 63; - outU8Array[outIdx++] = 128 | u & 63 - } - } - outU8Array[outIdx] = 0; - return outIdx - startIdx -} - -function stringToUTF8(str, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite) -} - -function lengthBytesUTF8(str) { - var len = 0; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) u = 65536 + ((u & 1023) << 10) | str.charCodeAt(++i) & 1023; - if (u <= 127) { - ++len - } else if (u <= 2047) { - len += 2 - } else if (u <= 65535) { - len += 3 - } else if (u <= 2097151) { - len += 4 - } else if (u <= 67108863) { - len += 5 - } else { - len += 6 - } - } - return len -} - -var UTF16Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-16le") : undefined; - -function allocateUTF8(str) { - var size = lengthBytesUTF8(str) + 1; - var ret = _malloc(size); - if (ret) stringToUTF8Array(str, HEAP8, ret, size); - return ret -} - -function demangle(func) { - return func -} - -function demangleAll(text) { - var regex = /__Z[\w\d_]+/g; - return text.replace(regex, (function (x) { - var y = demangle(x); - return x === y ? x : y + " [" + x + "]" - })) -} - -function jsStackTrace() { - var err = new Error; - if (!err.stack) { - try { - throw new Error(0) - } catch (e) { - err = e - } - if (!err.stack) { - return "(no stack trace available)" - } - } - return err.stack.toString() -} - -function stackTrace() { - var js = jsStackTrace(); - if (Module["extraStackTrace"]) js += "\n" + Module["extraStackTrace"](); - return demangleAll(js) -} - -var PAGE_SIZE = 16384; -var WASM_PAGE_SIZE = 65536; -var ASMJS_PAGE_SIZE = 16777216; -var MIN_TOTAL_MEMORY = 16777216; - -function alignUp(x, multiple) { - if (x % multiple > 0) { - x += multiple - x % multiple - } - return x -} - -var buffer, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; - -function updateGlobalBuffer(buf) { - Module["buffer"] = buffer = buf -} - -function updateGlobalBufferViews() { - Module["HEAP8"] = HEAP8 = new Int8Array(buffer); - Module["HEAP16"] = HEAP16 = new Int16Array(buffer); - Module["HEAP32"] = HEAP32 = new Int32Array(buffer); - Module["HEAPU8"] = HEAPU8 = new Uint8Array(buffer); - Module["HEAPU16"] = HEAPU16 = new Uint16Array(buffer); - Module["HEAPU32"] = HEAPU32 = new Uint32Array(buffer); - Module["HEAPF32"] = HEAPF32 = new Float32Array(buffer); - Module["HEAPF64"] = HEAPF64 = new Float64Array(buffer) -} - -var STATIC_BASE, STATICTOP, staticSealed; -var STACK_BASE, STACKTOP, STACK_MAX; -var DYNAMIC_BASE, DYNAMICTOP_PTR; -STATIC_BASE = STATICTOP = STACK_BASE = STACKTOP = STACK_MAX = DYNAMIC_BASE = DYNAMICTOP_PTR = 0; -staticSealed = false; - -function abortOnCannotGrowMemory() { - abort("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value " + TOTAL_MEMORY + ", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ") -} - -if (!Module["reallocBuffer"]) Module["reallocBuffer"] = (function (size) { - var ret; - try { - var oldHEAP8 = HEAP8; - ret = new ArrayBuffer(size); - var temp = new Int8Array(ret); - temp.set(oldHEAP8) - } catch (e) { - return false - } - var success = _emscripten_replace_memory(ret); - if (!success) return false; - return ret -}); - -function enlargeMemory() { - var PAGE_MULTIPLE = Module["usingWasm"] ? WASM_PAGE_SIZE : ASMJS_PAGE_SIZE; - var LIMIT = 2147483648 - PAGE_MULTIPLE; - if (HEAP32[DYNAMICTOP_PTR >> 2] > LIMIT) { - return false - } - var OLD_TOTAL_MEMORY = TOTAL_MEMORY; - TOTAL_MEMORY = Math.max(TOTAL_MEMORY, MIN_TOTAL_MEMORY); - while (TOTAL_MEMORY < HEAP32[DYNAMICTOP_PTR >> 2]) { - if (TOTAL_MEMORY <= 536870912) { - TOTAL_MEMORY = alignUp(2 * TOTAL_MEMORY, PAGE_MULTIPLE) - } else { - TOTAL_MEMORY = Math.min(alignUp((3 * TOTAL_MEMORY + 2147483648) / 4, PAGE_MULTIPLE), LIMIT) - } - } - var replacement = Module["reallocBuffer"](TOTAL_MEMORY); - if (!replacement || replacement.byteLength != TOTAL_MEMORY) { - TOTAL_MEMORY = OLD_TOTAL_MEMORY; - return false - } - updateGlobalBuffer(replacement); - updateGlobalBufferViews(); - return true -} - -var byteLength; -try { - byteLength = Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get); - byteLength(new ArrayBuffer(4)) -} catch (e) { - byteLength = (function (buffer) { - return buffer.byteLength - }) -} -var TOTAL_STACK = Module["TOTAL_STACK"] || 5242880; -var TOTAL_MEMORY = Module["TOTAL_MEMORY"] || 16777216; -if (TOTAL_MEMORY < TOTAL_STACK) err("TOTAL_MEMORY should be larger than TOTAL_STACK, was " + TOTAL_MEMORY + "! (TOTAL_STACK=" + TOTAL_STACK + ")"); -if (Module["buffer"]) { - buffer = Module["buffer"] -} else { - if (typeof WebAssembly === "object" && typeof WebAssembly.Memory === "function") { - Module["wasmMemory"] = new WebAssembly.Memory({"initial": TOTAL_MEMORY / WASM_PAGE_SIZE}); - buffer = Module["wasmMemory"].buffer - } else { - buffer = new ArrayBuffer(TOTAL_MEMORY) - } - Module["buffer"] = buffer -} -updateGlobalBufferViews(); - -function getTotalMemory() { - return TOTAL_MEMORY -} - -function callRuntimeCallbacks(callbacks) { - while (callbacks.length > 0) { - var callback = callbacks.shift(); - if (typeof callback == "function") { - callback(); - continue - } - var func = callback.func; - if (typeof func === "number") { - if (callback.arg === undefined) { - Module["dynCall_v"](func) - } else { - Module["dynCall_vi"](func, callback.arg) - } - } else { - func(callback.arg === undefined ? null : callback.arg) - } - } -} - -var __ATPRERUN__ = []; -var __ATINIT__ = []; -var __ATMAIN__ = []; -var __ATEXIT__ = []; -var __ATPOSTRUN__ = []; -var runtimeInitialized = false; -var runtimeExited = false; - -function preRun() { - if (Module["preRun"]) { - if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]]; - while (Module["preRun"].length) { - addOnPreRun(Module["preRun"].shift()) - } - } - callRuntimeCallbacks(__ATPRERUN__) -} - -function ensureInitRuntime() { - if (runtimeInitialized) return; - runtimeInitialized = true; - callRuntimeCallbacks(__ATINIT__) -} - -function preMain() { - callRuntimeCallbacks(__ATMAIN__) -} - -function exitRuntime() { - callRuntimeCallbacks(__ATEXIT__); - runtimeExited = true -} - -function postRun() { - if (Module["postRun"]) { - if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]]; - while (Module["postRun"].length) { - addOnPostRun(Module["postRun"].shift()) - } - } - callRuntimeCallbacks(__ATPOSTRUN__) -} - -function addOnPreRun(cb) { - __ATPRERUN__.unshift(cb) -} - -function addOnPostRun(cb) { - __ATPOSTRUN__.unshift(cb) -} - -function writeArrayToMemory(array, buffer) { - HEAP8.set(array, buffer) -} - -function writeAsciiToMemory(str, buffer, dontAddNull) { - for (var i = 0; i < str.length; ++i) { - HEAP8[buffer++ >> 0] = str.charCodeAt(i) - } - if (!dontAddNull) HEAP8[buffer >> 0] = 0 -} - -var Math_abs = Math.abs; -var Math_ceil = Math.ceil; -var Math_floor = Math.floor; -var Math_min = Math.min; -var runDependencies = 0; -var runDependencyWatcher = null; -var dependenciesFulfilled = null; - -function getUniqueRunDependency(id) { - return id -} - -function addRunDependency(id) { - runDependencies++; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies) - } -} - -function removeRunDependency(id) { - runDependencies--; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies) - } - if (runDependencies == 0) { - if (runDependencyWatcher !== null) { - clearInterval(runDependencyWatcher); - runDependencyWatcher = null - } - if (dependenciesFulfilled) { - var callback = dependenciesFulfilled; - dependenciesFulfilled = null; - callback() - } - } -} - -Module["preloadedImages"] = {}; -Module["preloadedAudios"] = {}; -var dataURIPrefix = "data:application/octet-stream;base64,"; - -function isDataURI(filename) { - return String.prototype.startsWith ? filename.startsWith(dataURIPrefix) : filename.indexOf(dataURIPrefix) === 0 -} - -function integrateWasmJS() { - var wasmTextFile = "lc0.wast"; - var wasmBinaryFile = "lc0.wasm"; - var asmjsCodeFile = "lc0.temp.asm.js"; - if (!isDataURI(wasmTextFile)) { - wasmTextFile = locateFile(wasmTextFile) - } - if (!isDataURI(wasmBinaryFile)) { - wasmBinaryFile = locateFile(wasmBinaryFile) - } - if (!isDataURI(asmjsCodeFile)) { - asmjsCodeFile = locateFile(asmjsCodeFile) - } - var wasmPageSize = 64 * 1024; - var info = {"global": null, "env": null, "asm2wasm": asm2wasmImports, "parent": Module}; - var exports = null; - - function mergeMemory(newBuffer) { - var oldBuffer = Module["buffer"]; - if (newBuffer.byteLength < oldBuffer.byteLength) { - err("the new buffer in mergeMemory is smaller than the previous one. in native wasm, we should grow memory here") - } - var oldView = new Int8Array(oldBuffer); - var newView = new Int8Array(newBuffer); - newView.set(oldView); - updateGlobalBuffer(newBuffer); - updateGlobalBufferViews() - } - - function getBinary() { - try { - if (Module["wasmBinary"]) { - return new Uint8Array(Module["wasmBinary"]) - } - if (Module["readBinary"]) { - return Module["readBinary"](wasmBinaryFile) - } else { - throw "both async and sync fetching of the wasm failed" - } - } catch (err) { - abort(err) - } - } - - function getBinaryPromise() { - if (!Module["wasmBinary"] && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && typeof fetch === "function") { - return fetch(wasmBinaryFile, {credentials: "same-origin"}).then((function (response) { - if (!response["ok"]) { - throw "failed to load wasm binary file at '" + wasmBinaryFile + "'" - } - return response["arrayBuffer"]() - })).catch((function () { - return getBinary() - })) - } - return new Promise((function (resolve, reject) { - resolve(getBinary()) - })) - } - - function doNativeWasm(global, env, providedBuffer) { - if (typeof WebAssembly !== "object") { - err("no native wasm support detected"); - return false - } - if (!(Module["wasmMemory"] instanceof WebAssembly.Memory)) { - err("no native wasm Memory in use"); - return false - } - env["memory"] = Module["wasmMemory"]; - info["global"] = {"NaN": NaN, "Infinity": Infinity}; - info["global.Math"] = Math; - info["env"] = env; - - function receiveInstance(instance, module) { - exports = instance.exports; - if (exports.memory) mergeMemory(exports.memory); - Module["asm"] = exports; - Module["usingWasm"] = true; - removeRunDependency("wasm-instantiate") - } - - addRunDependency("wasm-instantiate"); - if (Module["instantiateWasm"]) { - try { - return Module["instantiateWasm"](info, receiveInstance) - } catch (e) { - err("Module.instantiateWasm callback failed with error: " + e); - return false - } - } - - function receiveInstantiatedSource(output) { - receiveInstance(output["instance"], output["module"]) - } - - function instantiateArrayBuffer(receiver) { - getBinaryPromise().then((function (binary) { - return WebAssembly.instantiate(binary, info) - })).then(receiver, (function (reason) { - err("failed to asynchronously prepare wasm: " + reason); - abort(reason) - })) - } - - if (!Module["wasmBinary"] && typeof WebAssembly.instantiateStreaming === "function" && !isDataURI(wasmBinaryFile) && typeof fetch === "function") { - WebAssembly.instantiateStreaming(fetch(wasmBinaryFile, {credentials: "same-origin"}), info).then(receiveInstantiatedSource, (function (reason) { - err("wasm streaming compile failed: " + reason); - err("falling back to ArrayBuffer instantiation"); - instantiateArrayBuffer(receiveInstantiatedSource) - })) - } else { - instantiateArrayBuffer(receiveInstantiatedSource) - } - return {} - } - - Module["asmPreload"] = Module["asm"]; - var asmjsReallocBuffer = Module["reallocBuffer"]; - var wasmReallocBuffer = (function (size) { - var PAGE_MULTIPLE = Module["usingWasm"] ? WASM_PAGE_SIZE : ASMJS_PAGE_SIZE; - size = alignUp(size, PAGE_MULTIPLE); - var old = Module["buffer"]; - var oldSize = old.byteLength; - if (Module["usingWasm"]) { - try { - var result = Module["wasmMemory"].grow((size - oldSize) / wasmPageSize); - if (result !== (-1 | 0)) { - return Module["buffer"] = Module["wasmMemory"].buffer - } else { - return null - } - } catch (e) { - return null - } - } - }); - Module["reallocBuffer"] = (function (size) { - if (finalMethod === "asmjs") { - return asmjsReallocBuffer(size) - } else { - return wasmReallocBuffer(size) - } - }); - var finalMethod = ""; - Module["asm"] = (function (global, env, providedBuffer) { - if (!env["table"]) { - var TABLE_SIZE = Module["wasmTableSize"]; - if (TABLE_SIZE === undefined) TABLE_SIZE = 1024; - var MAX_TABLE_SIZE = Module["wasmMaxTableSize"]; - if (typeof WebAssembly === "object" && typeof WebAssembly.Table === "function") { - if (MAX_TABLE_SIZE !== undefined) { - env["table"] = new WebAssembly.Table({ - "initial": TABLE_SIZE, - "maximum": MAX_TABLE_SIZE, - "element": "anyfunc" - }) - } else { - env["table"] = new WebAssembly.Table({"initial": TABLE_SIZE, element: "anyfunc"}) - } - } else { - env["table"] = new Array(TABLE_SIZE) - } - Module["wasmTable"] = env["table"] - } - if (!env["__memory_base"]) { - env["__memory_base"] = Module["STATIC_BASE"] - } - if (!env["__table_base"]) { - env["__table_base"] = 0 - } - var exports; - exports = doNativeWasm(global, env, providedBuffer); - assert(exports, "no binaryen method succeeded."); - return exports - }) -} - -integrateWasmJS(); -var ASM_CONSTS = [(function ($0, $1, $2, $3) { - lczero_forward($0, $1, $2, $3) -})]; - -function _emscripten_asm_const_iiiii(code, a0, a1, a2, a3) { - return ASM_CONSTS[code](a0, a1, a2, a3) -} - -STATIC_BASE = GLOBAL_BASE; -STATICTOP = STATIC_BASE + 78640; -__ATINIT__.push({ - func: (function () { - __GLOBAL__I_000101() - }) -}, { - func: (function () { - __GLOBAL__sub_I_bindings_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_configfile_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_commandline_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_bitboard_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_board_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_uciloop_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_network_random_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_network_blas_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_network_tsjs_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_network_check_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_network_mux_cc() - }) -}, { - func: (function () { - __GLOBAL__sub_I_bind_cpp() - }) -}, { - func: (function () { - ___emscripten_environ_constructor() - }) -}, { - func: (function () { - __GLOBAL__sub_I_iostream_cpp() - }) -}); -var STATIC_BUMP = 78640; -Module["STATIC_BASE"] = STATIC_BASE; -Module["STATIC_BUMP"] = STATIC_BUMP; -STATICTOP += 16; -var ENV = {}; - -function ___buildEnvironment(environ) { - var MAX_ENV_VALUES = 64; - var TOTAL_ENV_SIZE = 1024; - var poolPtr; - var envPtr; - if (!___buildEnvironment.called) { - ___buildEnvironment.called = true; - ENV["USER"] = ENV["LOGNAME"] = "web_user"; - ENV["PATH"] = "/"; - ENV["PWD"] = "/"; - ENV["HOME"] = "/home/web_user"; - ENV["LANG"] = "C.UTF-8"; - ENV["_"] = Module["thisProgram"]; - poolPtr = getMemory(TOTAL_ENV_SIZE); - envPtr = getMemory(MAX_ENV_VALUES * 4); - HEAP32[envPtr >> 2] = poolPtr; - HEAP32[environ >> 2] = envPtr - } else { - envPtr = HEAP32[environ >> 2]; - poolPtr = HEAP32[envPtr >> 2] - } - var strings = []; - var totalSize = 0; - for (var key in ENV) { - if (typeof ENV[key] === "string") { - var line = key + "=" + ENV[key]; - strings.push(line); - totalSize += line.length - } - } - if (totalSize > TOTAL_ENV_SIZE) { - throw new Error("Environment size exceeded TOTAL_ENV_SIZE!") - } - var ptrSize = 4; - for (var i = 0; i < strings.length; i++) { - var line = strings[i]; - writeAsciiToMemory(line, poolPtr); - HEAP32[envPtr + i * ptrSize >> 2] = poolPtr; - poolPtr += line.length + 1 - } - HEAP32[envPtr + strings.length * ptrSize >> 2] = 0 -} - -function ___cxa_allocate_exception(size) { - return _malloc(size) -} - -var EXCEPTIONS = { - last: 0, caught: [], infos: {}, deAdjust: (function (adjusted) { - if (!adjusted || EXCEPTIONS.infos[adjusted]) return adjusted; - for (var key in EXCEPTIONS.infos) { - var ptr = +key; - var info = EXCEPTIONS.infos[ptr]; - if (info.adjusted === adjusted) { - return ptr - } - } - return adjusted - }), addRef: (function (ptr) { - if (!ptr) return; - var info = EXCEPTIONS.infos[ptr]; - info.refcount++ - }), decRef: (function (ptr) { - if (!ptr) return; - var info = EXCEPTIONS.infos[ptr]; - assert(info.refcount > 0); - info.refcount--; - if (info.refcount === 0 && !info.rethrown) { - if (info.destructor) { - Module["dynCall_vi"](info.destructor, ptr) - } - delete EXCEPTIONS.infos[ptr]; - ___cxa_free_exception(ptr) - } - }), clearRef: (function (ptr) { - if (!ptr) return; - var info = EXCEPTIONS.infos[ptr]; - info.refcount = 0 - }) -}; - -function ___cxa_begin_catch(ptr) { - var info = EXCEPTIONS.infos[ptr]; - if (info && !info.caught) { - info.caught = true; - __ZSt18uncaught_exceptionv.uncaught_exception-- - } - if (info) info.rethrown = false; - EXCEPTIONS.caught.push(ptr); - EXCEPTIONS.addRef(EXCEPTIONS.deAdjust(ptr)); - return ptr -} - -function ___cxa_free_exception(ptr) { - try { - return _free(ptr) - } catch (e) { - } -} - -function ___cxa_end_catch() { - Module["setThrew"](0); - var ptr = EXCEPTIONS.caught.pop(); - if (ptr) { - EXCEPTIONS.decRef(EXCEPTIONS.deAdjust(ptr)); - EXCEPTIONS.last = 0 - } -} - -function ___cxa_find_matching_catch_2() { - return ___cxa_find_matching_catch.apply(null, arguments) -} - -function ___cxa_find_matching_catch_3() { - return ___cxa_find_matching_catch.apply(null, arguments) -} - -function ___cxa_rethrow() { - var ptr = EXCEPTIONS.caught.pop(); - ptr = EXCEPTIONS.deAdjust(ptr); - if (!EXCEPTIONS.infos[ptr].rethrown) { - EXCEPTIONS.caught.push(ptr); - EXCEPTIONS.infos[ptr].rethrown = true - } - EXCEPTIONS.last = ptr; - throw ptr -} - -function ___resumeException(ptr) { - if (!EXCEPTIONS.last) { - EXCEPTIONS.last = ptr - } - throw ptr -} - -function ___cxa_find_matching_catch() { - var thrown = EXCEPTIONS.last; - if (!thrown) { - return (setTempRet0(0), 0) | 0 - } - var info = EXCEPTIONS.infos[thrown]; - var throwntype = info.type; - if (!throwntype) { - return (setTempRet0(0), thrown) | 0 - } - var typeArray = Array.prototype.slice.call(arguments); - var pointer = Module["___cxa_is_pointer_type"](throwntype); - if (!___cxa_find_matching_catch.buffer) ___cxa_find_matching_catch.buffer = _malloc(4); - HEAP32[___cxa_find_matching_catch.buffer >> 2] = thrown; - thrown = ___cxa_find_matching_catch.buffer; - for (var i = 0; i < typeArray.length; i++) { - if (typeArray[i] && Module["___cxa_can_catch"](typeArray[i], throwntype, thrown)) { - thrown = HEAP32[thrown >> 2]; - info.adjusted = thrown; - return (setTempRet0(typeArray[i]), thrown) | 0 - } - } - thrown = HEAP32[thrown >> 2]; - return (setTempRet0(throwntype), thrown) | 0 -} - -function ___cxa_throw(ptr, type, destructor) { - EXCEPTIONS.infos[ptr] = { - ptr: ptr, - adjusted: ptr, - type: type, - destructor: destructor, - refcount: 0, - caught: false, - rethrown: false - }; - EXCEPTIONS.last = ptr; - if (!("uncaught_exception" in __ZSt18uncaught_exceptionv)) { - __ZSt18uncaught_exceptionv.uncaught_exception = 1 - } else { - __ZSt18uncaught_exceptionv.uncaught_exception++ - } - throw ptr -} - -function ___cxa_uncaught_exception() { - return !!__ZSt18uncaught_exceptionv.uncaught_exception -} - -function ___lock() { -} - -var ERRNO_CODES = { - EPERM: 1, - ENOENT: 2, - ESRCH: 3, - EINTR: 4, - EIO: 5, - ENXIO: 6, - E2BIG: 7, - ENOEXEC: 8, - EBADF: 9, - ECHILD: 10, - EAGAIN: 11, - EWOULDBLOCK: 11, - ENOMEM: 12, - EACCES: 13, - EFAULT: 14, - ENOTBLK: 15, - EBUSY: 16, - EEXIST: 17, - EXDEV: 18, - ENODEV: 19, - ENOTDIR: 20, - EISDIR: 21, - EINVAL: 22, - ENFILE: 23, - EMFILE: 24, - ENOTTY: 25, - ETXTBSY: 26, - EFBIG: 27, - ENOSPC: 28, - ESPIPE: 29, - EROFS: 30, - EMLINK: 31, - EPIPE: 32, - EDOM: 33, - ERANGE: 34, - ENOMSG: 42, - EIDRM: 43, - ECHRNG: 44, - EL2NSYNC: 45, - EL3HLT: 46, - EL3RST: 47, - ELNRNG: 48, - EUNATCH: 49, - ENOCSI: 50, - EL2HLT: 51, - EDEADLK: 35, - ENOLCK: 37, - EBADE: 52, - EBADR: 53, - EXFULL: 54, - ENOANO: 55, - EBADRQC: 56, - EBADSLT: 57, - EDEADLOCK: 35, - EBFONT: 59, - ENOSTR: 60, - ENODATA: 61, - ETIME: 62, - ENOSR: 63, - ENONET: 64, - ENOPKG: 65, - EREMOTE: 66, - ENOLINK: 67, - EADV: 68, - ESRMNT: 69, - ECOMM: 70, - EPROTO: 71, - EMULTIHOP: 72, - EDOTDOT: 73, - EBADMSG: 74, - ENOTUNIQ: 76, - EBADFD: 77, - EREMCHG: 78, - ELIBACC: 79, - ELIBBAD: 80, - ELIBSCN: 81, - ELIBMAX: 82, - ELIBEXEC: 83, - ENOSYS: 38, - ENOTEMPTY: 39, - ENAMETOOLONG: 36, - ELOOP: 40, - EOPNOTSUPP: 95, - EPFNOSUPPORT: 96, - ECONNRESET: 104, - ENOBUFS: 105, - EAFNOSUPPORT: 97, - EPROTOTYPE: 91, - ENOTSOCK: 88, - ENOPROTOOPT: 92, - ESHUTDOWN: 108, - ECONNREFUSED: 111, - EADDRINUSE: 98, - ECONNABORTED: 103, - ENETUNREACH: 101, - ENETDOWN: 100, - ETIMEDOUT: 110, - EHOSTDOWN: 112, - EHOSTUNREACH: 113, - EINPROGRESS: 115, - EALREADY: 114, - EDESTADDRREQ: 89, - EMSGSIZE: 90, - EPROTONOSUPPORT: 93, - ESOCKTNOSUPPORT: 94, - EADDRNOTAVAIL: 99, - ENETRESET: 102, - EISCONN: 106, - ENOTCONN: 107, - ETOOMANYREFS: 109, - EUSERS: 87, - EDQUOT: 122, - ESTALE: 116, - ENOTSUP: 95, - ENOMEDIUM: 123, - EILSEQ: 84, - EOVERFLOW: 75, - ECANCELED: 125, - ENOTRECOVERABLE: 131, - EOWNERDEAD: 130, - ESTRPIPE: 86 -}; - -function ___setErrNo(value) { - if (Module["___errno_location"]) HEAP32[Module["___errno_location"]() >> 2] = value; - return value -} - -function ___map_file(pathname, size) { - ___setErrNo(ERRNO_CODES.EPERM); - return -1 -} - -var ERRNO_MESSAGES = { - 0: "Success", - 1: "Not super-user", - 2: "No such file or directory", - 3: "No such process", - 4: "Interrupted system call", - 5: "I/O error", - 6: "No such device or address", - 7: "Arg list too long", - 8: "Exec format error", - 9: "Bad file number", - 10: "No children", - 11: "No more processes", - 12: "Not enough core", - 13: "Permission denied", - 14: "Bad address", - 15: "Block device required", - 16: "Mount device busy", - 17: "File exists", - 18: "Cross-device link", - 19: "No such device", - 20: "Not a directory", - 21: "Is a directory", - 22: "Invalid argument", - 23: "Too many open files in system", - 24: "Too many open files", - 25: "Not a typewriter", - 26: "Text file busy", - 27: "File too large", - 28: "No space left on device", - 29: "Illegal seek", - 30: "Read only file system", - 31: "Too many links", - 32: "Broken pipe", - 33: "Math arg out of domain of func", - 34: "Math result not representable", - 35: "File locking deadlock error", - 36: "File or path name too long", - 37: "No record locks available", - 38: "Function not implemented", - 39: "Directory not empty", - 40: "Too many symbolic links", - 42: "No message of desired type", - 43: "Identifier removed", - 44: "Channel number out of range", - 45: "Level 2 not synchronized", - 46: "Level 3 halted", - 47: "Level 3 reset", - 48: "Link number out of range", - 49: "Protocol driver not attached", - 50: "No CSI structure available", - 51: "Level 2 halted", - 52: "Invalid exchange", - 53: "Invalid request descriptor", - 54: "Exchange full", - 55: "No anode", - 56: "Invalid request code", - 57: "Invalid slot", - 59: "Bad font file fmt", - 60: "Device not a stream", - 61: "No data (for no delay io)", - 62: "Timer expired", - 63: "Out of streams resources", - 64: "Machine is not on the network", - 65: "Package not installed", - 66: "The object is remote", - 67: "The link has been severed", - 68: "Advertise error", - 69: "Srmount error", - 70: "Communication error on send", - 71: "Protocol error", - 72: "Multihop attempted", - 73: "Cross mount point (not really error)", - 74: "Trying to read unreadable message", - 75: "Value too large for defined data type", - 76: "Given log. name not unique", - 77: "f.d. invalid for this operation", - 78: "Remote address changed", - 79: "Can access a needed shared lib", - 80: "Accessing a corrupted shared lib", - 81: ".lib section in a.out corrupted", - 82: "Attempting to link in too many libs", - 83: "Attempting to exec a shared library", - 84: "Illegal byte sequence", - 86: "Streams pipe error", - 87: "Too many users", - 88: "Socket operation on non-socket", - 89: "Destination address required", - 90: "Message too long", - 91: "Protocol wrong type for socket", - 92: "Protocol not available", - 93: "Unknown protocol", - 94: "Socket type not supported", - 95: "Not supported", - 96: "Protocol family not supported", - 97: "Address family not supported by protocol family", - 98: "Address already in use", - 99: "Address not available", - 100: "Network interface is not configured", - 101: "Network is unreachable", - 102: "Connection reset by network", - 103: "Connection aborted", - 104: "Connection reset by peer", - 105: "No buffer space available", - 106: "Socket is already connected", - 107: "Socket is not connected", - 108: "Can't send after socket shutdown", - 109: "Too many references", - 110: "Connection timed out", - 111: "Connection refused", - 112: "Host is down", - 113: "Host is unreachable", - 114: "Socket already connected", - 115: "Connection already in progress", - 116: "Stale file handle", - 122: "Quota exceeded", - 123: "No medium (in tape drive)", - 125: "Operation canceled", - 130: "Previous owner died", - 131: "State not recoverable" -}; -var PATH = { - splitPath: (function (filename) { - var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; - return splitPathRe.exec(filename).slice(1) - }), normalizeArray: (function (parts, allowAboveRoot) { - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === ".") { - parts.splice(i, 1) - } else if (last === "..") { - parts.splice(i, 1); - up++ - } else if (up) { - parts.splice(i, 1); - up-- - } - } - if (allowAboveRoot) { - for (; up; up--) { - parts.unshift("..") - } - } - return parts - }), normalize: (function (path) { - var isAbsolute = path.charAt(0) === "/", trailingSlash = path.substr(-1) === "/"; - path = PATH.normalizeArray(path.split("/").filter((function (p) { - return !!p - })), !isAbsolute).join("/"); - if (!path && !isAbsolute) { - path = "." - } - if (path && trailingSlash) { - path += "/" - } - return (isAbsolute ? "/" : "") + path - }), dirname: (function (path) { - var result = PATH.splitPath(path), root = result[0], dir = result[1]; - if (!root && !dir) { - return "." - } - if (dir) { - dir = dir.substr(0, dir.length - 1) - } - return root + dir - }), basename: (function (path) { - if (path === "/") return "/"; - var lastSlash = path.lastIndexOf("/"); - if (lastSlash === -1) return path; - return path.substr(lastSlash + 1) - }), extname: (function (path) { - return PATH.splitPath(path)[3] - }), join: (function () { - var paths = Array.prototype.slice.call(arguments, 0); - return PATH.normalize(paths.join("/")) - }), join2: (function (l, r) { - return PATH.normalize(l + "/" + r) - }), resolve: (function () { - var resolvedPath = "", resolvedAbsolute = false; - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = i >= 0 ? arguments[i] : FS.cwd(); - if (typeof path !== "string") { - throw new TypeError("Arguments to path.resolve must be strings") - } else if (!path) { - return "" - } - resolvedPath = path + "/" + resolvedPath; - resolvedAbsolute = path.charAt(0) === "/" - } - resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter((function (p) { - return !!p - })), !resolvedAbsolute).join("/"); - return (resolvedAbsolute ? "/" : "") + resolvedPath || "." - }), relative: (function (from, to) { - from = PATH.resolve(from).substr(1); - to = PATH.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== "") break - } - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== "") break - } - if (start > end) return []; - return arr.slice(start, end - start + 1) - } - - var fromParts = trim(from.split("/")); - var toParts = trim(to.split("/")); - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break - } - } - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push("..") - } - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - return outputParts.join("/") - }) -}; -var TTY = { - ttys: [], init: (function () { - }), shutdown: (function () { - }), register: (function (dev, ops) { - TTY.ttys[dev] = {input: [], output: [], ops: ops}; - FS.registerDevice(dev, TTY.stream_ops) - }), stream_ops: { - open: (function (stream) { - var tty = TTY.ttys[stream.node.rdev]; - if (!tty) { - throw new FS.ErrnoError(ERRNO_CODES.ENODEV) - } - stream.tty = tty; - stream.seekable = false - }), close: (function (stream) { - stream.tty.ops.flush(stream.tty) - }), flush: (function (stream) { - stream.tty.ops.flush(stream.tty) - }), read: (function (stream, buffer, offset, length, pos) { - if (!stream.tty || !stream.tty.ops.get_char) { - throw new FS.ErrnoError(ERRNO_CODES.ENXIO) - } - var bytesRead = 0; - for (var i = 0; i < length; i++) { - var result; - try { - result = stream.tty.ops.get_char(stream.tty) - } catch (e) { - throw new FS.ErrnoError(ERRNO_CODES.EIO) - } - if (result === undefined && bytesRead === 0) { - throw new FS.ErrnoError(ERRNO_CODES.EAGAIN) - } - if (result === null || result === undefined) break; - bytesRead++; - buffer[offset + i] = result - } - if (bytesRead) { - stream.node.timestamp = Date.now() - } - return bytesRead - }), write: (function (stream, buffer, offset, length, pos) { - if (!stream.tty || !stream.tty.ops.put_char) { - throw new FS.ErrnoError(ERRNO_CODES.ENXIO) - } - var i = 0; - try { - if (offset === 0 && length === 0) { - stream.tty.ops.flush(stream.tty) - } else { - while (i < length) { - stream.tty.ops.put_char(stream.tty, buffer[offset + i]); - i++ - } - } - } catch (e) { - throw new FS.ErrnoError(ERRNO_CODES.EIO) - } - if (length) { - stream.node.timestamp = Date.now() - } - return i - }) - }, default_tty_ops: { - get_char: (function (tty) { - if (!tty.input.length) { - var result = null; - if (ENVIRONMENT_IS_NODE) { - var BUFSIZE = 256; - var buf = new Buffer(BUFSIZE); - var bytesRead = 0; - var isPosixPlatform = process.platform != "win32"; - var fd = process.stdin.fd; - if (isPosixPlatform) { - var usingDevice = false; - try { - fd = fs.openSync("/dev/stdin", "r"); - usingDevice = true - } catch (e) { - } - } - try { - bytesRead = fs.readSync(fd, buf, 0, BUFSIZE, null) - } catch (e) { - if (e.toString().indexOf("EOF") != -1) bytesRead = 0; else throw e - } - if (usingDevice) { - fs.closeSync(fd) - } - if (bytesRead > 0) { - result = buf.slice(0, bytesRead).toString("utf-8") - } else { - result = null - } - } else if (typeof window != "undefined" && typeof window.prompt == "function") { - result = window.prompt("Input: "); - if (result !== null) { - result += "\n" - } - } else if (typeof readline == "function") { - result = readline(); - if (result !== null) { - result += "\n" - } - } - if (!result) { - return null - } - tty.input = intArrayFromString(result, true) - } - return tty.input.shift() - }), put_char: (function (tty, val) { - if (val === null || val === 10) { - out(UTF8ArrayToString(tty.output, 0)); - tty.output = [] - } else { - if (val != 0) tty.output.push(val) - } - }), flush: (function (tty) { - if (tty.output && tty.output.length > 0) { - out(UTF8ArrayToString(tty.output, 0)); - tty.output = [] - } - }) - }, default_tty1_ops: { - put_char: (function (tty, val) { - if (val === null || val === 10) { - err(UTF8ArrayToString(tty.output, 0)); - tty.output = [] - } else { - if (val != 0) tty.output.push(val) - } - }), flush: (function (tty) { - if (tty.output && tty.output.length > 0) { - err(UTF8ArrayToString(tty.output, 0)); - tty.output = [] - } - }) - } -}; -var MEMFS = { - ops_table: null, mount: (function (mount) { - return MEMFS.createNode(null, "/", 16384 | 511, 0) - }), createNode: (function (parent, name, mode, dev) { - if (FS.isBlkdev(mode) || FS.isFIFO(mode)) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - if (!MEMFS.ops_table) { - MEMFS.ops_table = { - dir: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - lookup: MEMFS.node_ops.lookup, - mknod: MEMFS.node_ops.mknod, - rename: MEMFS.node_ops.rename, - unlink: MEMFS.node_ops.unlink, - rmdir: MEMFS.node_ops.rmdir, - readdir: MEMFS.node_ops.readdir, - symlink: MEMFS.node_ops.symlink - }, stream: {llseek: MEMFS.stream_ops.llseek} - }, - file: { - node: {getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr}, - stream: { - llseek: MEMFS.stream_ops.llseek, - read: MEMFS.stream_ops.read, - write: MEMFS.stream_ops.write, - allocate: MEMFS.stream_ops.allocate, - mmap: MEMFS.stream_ops.mmap, - msync: MEMFS.stream_ops.msync - } - }, - link: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - readlink: MEMFS.node_ops.readlink - }, stream: {} - }, - chrdev: { - node: {getattr: MEMFS.node_ops.getattr, setattr: MEMFS.node_ops.setattr}, - stream: FS.chrdev_stream_ops - } - } - } - var node = FS.createNode(parent, name, mode, dev); - if (FS.isDir(node.mode)) { - node.node_ops = MEMFS.ops_table.dir.node; - node.stream_ops = MEMFS.ops_table.dir.stream; - node.contents = {} - } else if (FS.isFile(node.mode)) { - node.node_ops = MEMFS.ops_table.file.node; - node.stream_ops = MEMFS.ops_table.file.stream; - node.usedBytes = 0; - node.contents = null - } else if (FS.isLink(node.mode)) { - node.node_ops = MEMFS.ops_table.link.node; - node.stream_ops = MEMFS.ops_table.link.stream - } else if (FS.isChrdev(node.mode)) { - node.node_ops = MEMFS.ops_table.chrdev.node; - node.stream_ops = MEMFS.ops_table.chrdev.stream - } - node.timestamp = Date.now(); - if (parent) { - parent.contents[name] = node - } - return node - }), getFileDataAsRegularArray: (function (node) { - if (node.contents && node.contents.subarray) { - var arr = []; - for (var i = 0; i < node.usedBytes; ++i) arr.push(node.contents[i]); - return arr - } - return node.contents - }), getFileDataAsTypedArray: (function (node) { - if (!node.contents) return new Uint8Array; - if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); - return new Uint8Array(node.contents) - }), expandFileStorage: (function (node, newCapacity) { - if (node.contents && node.contents.subarray && newCapacity > node.contents.length) { - node.contents = MEMFS.getFileDataAsRegularArray(node); - node.usedBytes = node.contents.length - } - if (!node.contents || node.contents.subarray) { - var prevCapacity = node.contents ? node.contents.length : 0; - if (prevCapacity >= newCapacity) return; - var CAPACITY_DOUBLING_MAX = 1024 * 1024; - newCapacity = Math.max(newCapacity, prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) | 0); - if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); - var oldContents = node.contents; - node.contents = new Uint8Array(newCapacity); - if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); - return - } - if (!node.contents && newCapacity > 0) node.contents = []; - while (node.contents.length < newCapacity) node.contents.push(0) - }), resizeFileStorage: (function (node, newSize) { - if (node.usedBytes == newSize) return; - if (newSize == 0) { - node.contents = null; - node.usedBytes = 0; - return - } - if (!node.contents || node.contents.subarray) { - var oldContents = node.contents; - node.contents = new Uint8Array(new ArrayBuffer(newSize)); - if (oldContents) { - node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))) - } - node.usedBytes = newSize; - return - } - if (!node.contents) node.contents = []; - if (node.contents.length > newSize) node.contents.length = newSize; else while (node.contents.length < newSize) node.contents.push(0); - node.usedBytes = newSize - }), node_ops: { - getattr: (function (node) { - var attr = {}; - attr.dev = FS.isChrdev(node.mode) ? node.id : 1; - attr.ino = node.id; - attr.mode = node.mode; - attr.nlink = 1; - attr.uid = 0; - attr.gid = 0; - attr.rdev = node.rdev; - if (FS.isDir(node.mode)) { - attr.size = 4096 - } else if (FS.isFile(node.mode)) { - attr.size = node.usedBytes - } else if (FS.isLink(node.mode)) { - attr.size = node.link.length - } else { - attr.size = 0 - } - attr.atime = new Date(node.timestamp); - attr.mtime = new Date(node.timestamp); - attr.ctime = new Date(node.timestamp); - attr.blksize = 4096; - attr.blocks = Math.ceil(attr.size / attr.blksize); - return attr - }), setattr: (function (node, attr) { - if (attr.mode !== undefined) { - node.mode = attr.mode - } - if (attr.timestamp !== undefined) { - node.timestamp = attr.timestamp - } - if (attr.size !== undefined) { - MEMFS.resizeFileStorage(node, attr.size) - } - }), lookup: (function (parent, name) { - throw FS.genericErrors[ERRNO_CODES.ENOENT] - }), mknod: (function (parent, name, mode, dev) { - return MEMFS.createNode(parent, name, mode, dev) - }), rename: (function (old_node, new_dir, new_name) { - if (FS.isDir(old_node.mode)) { - var new_node; - try { - new_node = FS.lookupNode(new_dir, new_name) - } catch (e) { - } - if (new_node) { - for (var i in new_node.contents) { - throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY) - } - } - } - delete old_node.parent.contents[old_node.name]; - old_node.name = new_name; - new_dir.contents[new_name] = old_node; - old_node.parent = new_dir - }), unlink: (function (parent, name) { - delete parent.contents[name] - }), rmdir: (function (parent, name) { - var node = FS.lookupNode(parent, name); - for (var i in node.contents) { - throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY) - } - delete parent.contents[name] - }), readdir: (function (node) { - var entries = [".", ".."]; - for (var key in node.contents) { - if (!node.contents.hasOwnProperty(key)) { - continue - } - entries.push(key) - } - return entries - }), symlink: (function (parent, newname, oldpath) { - var node = MEMFS.createNode(parent, newname, 511 | 40960, 0); - node.link = oldpath; - return node - }), readlink: (function (node) { - if (!FS.isLink(node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - return node.link - }) - }, stream_ops: { - read: (function (stream, buffer, offset, length, position) { - var contents = stream.node.contents; - if (position >= stream.node.usedBytes) return 0; - var size = Math.min(stream.node.usedBytes - position, length); - assert(size >= 0); - if (size > 8 && contents.subarray) { - buffer.set(contents.subarray(position, position + size), offset) - } else { - for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i] - } - return size - }), write: (function (stream, buffer, offset, length, position, canOwn) { - canOwn = false; - if (!length) return 0; - var node = stream.node; - node.timestamp = Date.now(); - if (buffer.subarray && (!node.contents || node.contents.subarray)) { - if (canOwn) { - node.contents = buffer.subarray(offset, offset + length); - node.usedBytes = length; - return length - } else if (node.usedBytes === 0 && position === 0) { - node.contents = new Uint8Array(buffer.subarray(offset, offset + length)); - node.usedBytes = length; - return length - } else if (position + length <= node.usedBytes) { - node.contents.set(buffer.subarray(offset, offset + length), position); - return length - } - } - MEMFS.expandFileStorage(node, position + length); - if (node.contents.subarray && buffer.subarray) node.contents.set(buffer.subarray(offset, offset + length), position); else { - for (var i = 0; i < length; i++) { - node.contents[position + i] = buffer[offset + i] - } - } - node.usedBytes = Math.max(node.usedBytes, position + length); - return length - }), llseek: (function (stream, offset, whence) { - var position = offset; - if (whence === 1) { - position += stream.position - } else if (whence === 2) { - if (FS.isFile(stream.node.mode)) { - position += stream.node.usedBytes - } - } - if (position < 0) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - return position - }), allocate: (function (stream, offset, length) { - MEMFS.expandFileStorage(stream.node, offset + length); - stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length) - }), mmap: (function (stream, buffer, offset, length, position, prot, flags) { - if (!FS.isFile(stream.node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.ENODEV) - } - var ptr; - var allocated; - var contents = stream.node.contents; - if (!(flags & 2) && (contents.buffer === buffer || contents.buffer === buffer.buffer)) { - allocated = false; - ptr = contents.byteOffset - } else { - if (position > 0 || position + length < stream.node.usedBytes) { - if (contents.subarray) { - contents = contents.subarray(position, position + length) - } else { - contents = Array.prototype.slice.call(contents, position, position + length) - } - } - allocated = true; - ptr = _malloc(length); - if (!ptr) { - throw new FS.ErrnoError(ERRNO_CODES.ENOMEM) - } - buffer.set(contents, ptr) - } - return {ptr: ptr, allocated: allocated} - }), msync: (function (stream, buffer, offset, length, mmapFlags) { - if (!FS.isFile(stream.node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.ENODEV) - } - if (mmapFlags & 2) { - return 0 - } - var bytesWritten = MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false); - return 0 - }) - } -}; -var IDBFS = { - dbs: {}, indexedDB: (function () { - if (typeof indexedDB !== "undefined") return indexedDB; - var ret = null; - if (typeof window === "object") ret = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; - assert(ret, "IDBFS used, but indexedDB not supported"); - return ret - }), DB_VERSION: 21, DB_STORE_NAME: "FILE_DATA", mount: (function (mount) { - return MEMFS.mount.apply(null, arguments) - }), syncfs: (function (mount, populate, callback) { - IDBFS.getLocalSet(mount, (function (err, local) { - if (err) return callback(err); - IDBFS.getRemoteSet(mount, (function (err, remote) { - if (err) return callback(err); - var src = populate ? remote : local; - var dst = populate ? local : remote; - IDBFS.reconcile(src, dst, callback) - })) - })) - }), getDB: (function (name, callback) { - var db = IDBFS.dbs[name]; - if (db) { - return callback(null, db) - } - var req; - try { - req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION) - } catch (e) { - return callback(e) - } - if (!req) { - return callback("Unable to connect to IndexedDB") - } - req.onupgradeneeded = (function (e) { - var db = e.target.result; - var transaction = e.target.transaction; - var fileStore; - if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) { - fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME) - } else { - fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME) - } - if (!fileStore.indexNames.contains("timestamp")) { - fileStore.createIndex("timestamp", "timestamp", {unique: false}) - } - }); - req.onsuccess = (function () { - db = req.result; - IDBFS.dbs[name] = db; - callback(null, db) - }); - req.onerror = (function (e) { - callback(this.error); - e.preventDefault() - }) - }), getLocalSet: (function (mount, callback) { - var entries = {}; - - function isRealDir(p) { - return p !== "." && p !== ".." - } - - function toAbsolute(root) { - return (function (p) { - return PATH.join2(root, p) - }) - } - - var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint)); - while (check.length) { - var path = check.pop(); - var stat; - try { - stat = FS.stat(path) - } catch (e) { - return callback(e) - } - if (FS.isDir(stat.mode)) { - check.push.apply(check, FS.readdir(path).filter(isRealDir).map(toAbsolute(path))) - } - entries[path] = {timestamp: stat.mtime} - } - return callback(null, {type: "local", entries: entries}) - }), getRemoteSet: (function (mount, callback) { - var entries = {}; - IDBFS.getDB(mount.mountpoint, (function (err, db) { - if (err) return callback(err); - try { - var transaction = db.transaction([IDBFS.DB_STORE_NAME], "readonly"); - transaction.onerror = (function (e) { - callback(this.error); - e.preventDefault() - }); - var store = transaction.objectStore(IDBFS.DB_STORE_NAME); - var index = store.index("timestamp"); - index.openKeyCursor().onsuccess = (function (event) { - var cursor = event.target.result; - if (!cursor) { - return callback(null, {type: "remote", db: db, entries: entries}) - } - entries[cursor.primaryKey] = {timestamp: cursor.key}; - cursor.continue() - }) - } catch (e) { - return callback(e) - } - })) - }), loadLocalEntry: (function (path, callback) { - var stat, node; - try { - var lookup = FS.lookupPath(path); - node = lookup.node; - stat = FS.stat(path) - } catch (e) { - return callback(e) - } - if (FS.isDir(stat.mode)) { - return callback(null, {timestamp: stat.mtime, mode: stat.mode}) - } else if (FS.isFile(stat.mode)) { - node.contents = MEMFS.getFileDataAsTypedArray(node); - return callback(null, {timestamp: stat.mtime, mode: stat.mode, contents: node.contents}) - } else { - return callback(new Error("node type not supported")) - } - }), storeLocalEntry: (function (path, entry, callback) { - try { - if (FS.isDir(entry.mode)) { - FS.mkdir(path, entry.mode) - } else if (FS.isFile(entry.mode)) { - FS.writeFile(path, entry.contents, {canOwn: true}) - } else { - return callback(new Error("node type not supported")) - } - FS.chmod(path, entry.mode); - FS.utime(path, entry.timestamp, entry.timestamp) - } catch (e) { - return callback(e) - } - callback(null) - }), removeLocalEntry: (function (path, callback) { - try { - var lookup = FS.lookupPath(path); - var stat = FS.stat(path); - if (FS.isDir(stat.mode)) { - FS.rmdir(path) - } else if (FS.isFile(stat.mode)) { - FS.unlink(path) - } - } catch (e) { - return callback(e) - } - callback(null) - }), loadRemoteEntry: (function (store, path, callback) { - var req = store.get(path); - req.onsuccess = (function (event) { - callback(null, event.target.result) - }); - req.onerror = (function (e) { - callback(this.error); - e.preventDefault() - }) - }), storeRemoteEntry: (function (store, path, entry, callback) { - var req = store.put(entry, path); - req.onsuccess = (function () { - callback(null) - }); - req.onerror = (function (e) { - callback(this.error); - e.preventDefault() - }) - }), removeRemoteEntry: (function (store, path, callback) { - var req = store.delete(path); - req.onsuccess = (function () { - callback(null) - }); - req.onerror = (function (e) { - callback(this.error); - e.preventDefault() - }) - }), reconcile: (function (src, dst, callback) { - var total = 0; - var create = []; - Object.keys(src.entries).forEach((function (key) { - var e = src.entries[key]; - var e2 = dst.entries[key]; - if (!e2 || e.timestamp > e2.timestamp) { - create.push(key); - total++ - } - })); - var remove = []; - Object.keys(dst.entries).forEach((function (key) { - var e = dst.entries[key]; - var e2 = src.entries[key]; - if (!e2) { - remove.push(key); - total++ - } - })); - if (!total) { - return callback(null) - } - var completed = 0; - var db = src.type === "remote" ? src.db : dst.db; - var transaction = db.transaction([IDBFS.DB_STORE_NAME], "readwrite"); - var store = transaction.objectStore(IDBFS.DB_STORE_NAME); - - function done(err) { - if (err) { - if (!done.errored) { - done.errored = true; - return callback(err) - } - return - } - if (++completed >= total) { - return callback(null) - } - } - - transaction.onerror = (function (e) { - done(this.error); - e.preventDefault() - }); - create.sort().forEach((function (path) { - if (dst.type === "local") { - IDBFS.loadRemoteEntry(store, path, (function (err, entry) { - if (err) return done(err); - IDBFS.storeLocalEntry(path, entry, done) - })) - } else { - IDBFS.loadLocalEntry(path, (function (err, entry) { - if (err) return done(err); - IDBFS.storeRemoteEntry(store, path, entry, done) - })) - } - })); - remove.sort().reverse().forEach((function (path) { - if (dst.type === "local") { - IDBFS.removeLocalEntry(path, done) - } else { - IDBFS.removeRemoteEntry(store, path, done) - } - })) - }) -}; -var NODEFS = { - isWindows: false, staticInit: (function () { - NODEFS.isWindows = !!process.platform.match(/^win/); - var flags = process["binding"]("constants"); - if (flags["fs"]) { - flags = flags["fs"] - } - NODEFS.flagsForNodeMap = { - "1024": flags["O_APPEND"], - "64": flags["O_CREAT"], - "128": flags["O_EXCL"], - "0": flags["O_RDONLY"], - "2": flags["O_RDWR"], - "4096": flags["O_SYNC"], - "512": flags["O_TRUNC"], - "1": flags["O_WRONLY"] - } - }), bufferFrom: (function (arrayBuffer) { - return Buffer.alloc ? Buffer.from(arrayBuffer) : new Buffer(arrayBuffer) - }), mount: (function (mount) { - assert(ENVIRONMENT_IS_NODE); - return NODEFS.createNode(null, "/", NODEFS.getMode(mount.opts.root), 0) - }), createNode: (function (parent, name, mode, dev) { - if (!FS.isDir(mode) && !FS.isFile(mode) && !FS.isLink(mode)) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - var node = FS.createNode(parent, name, mode); - node.node_ops = NODEFS.node_ops; - node.stream_ops = NODEFS.stream_ops; - return node - }), getMode: (function (path) { - var stat; - try { - stat = fs.lstatSync(path); - if (NODEFS.isWindows) { - stat.mode = stat.mode | (stat.mode & 292) >> 2 - } - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - return stat.mode - }), realPath: (function (node) { - var parts = []; - while (node.parent !== node) { - parts.push(node.name); - node = node.parent - } - parts.push(node.mount.opts.root); - parts.reverse(); - return PATH.join.apply(null, parts) - }), flagsForNode: (function (flags) { - flags &= ~2097152; - flags &= ~2048; - flags &= ~32768; - flags &= ~524288; - var newFlags = 0; - for (var k in NODEFS.flagsForNodeMap) { - if (flags & k) { - newFlags |= NODEFS.flagsForNodeMap[k]; - flags ^= k - } - } - if (!flags) { - return newFlags - } else { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - }), node_ops: { - getattr: (function (node) { - var path = NODEFS.realPath(node); - var stat; - try { - stat = fs.lstatSync(path) - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - if (NODEFS.isWindows && !stat.blksize) { - stat.blksize = 4096 - } - if (NODEFS.isWindows && !stat.blocks) { - stat.blocks = (stat.size + stat.blksize - 1) / stat.blksize | 0 - } - return { - dev: stat.dev, - ino: stat.ino, - mode: stat.mode, - nlink: stat.nlink, - uid: stat.uid, - gid: stat.gid, - rdev: stat.rdev, - size: stat.size, - atime: stat.atime, - mtime: stat.mtime, - ctime: stat.ctime, - blksize: stat.blksize, - blocks: stat.blocks - } - }), setattr: (function (node, attr) { - var path = NODEFS.realPath(node); - try { - if (attr.mode !== undefined) { - fs.chmodSync(path, attr.mode); - node.mode = attr.mode - } - if (attr.timestamp !== undefined) { - var date = new Date(attr.timestamp); - fs.utimesSync(path, date, date) - } - if (attr.size !== undefined) { - fs.truncateSync(path, attr.size) - } - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), lookup: (function (parent, name) { - var path = PATH.join2(NODEFS.realPath(parent), name); - var mode = NODEFS.getMode(path); - return NODEFS.createNode(parent, name, mode) - }), mknod: (function (parent, name, mode, dev) { - var node = NODEFS.createNode(parent, name, mode, dev); - var path = NODEFS.realPath(node); - try { - if (FS.isDir(node.mode)) { - fs.mkdirSync(path, node.mode) - } else { - fs.writeFileSync(path, "", {mode: node.mode}) - } - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - return node - }), rename: (function (oldNode, newDir, newName) { - var oldPath = NODEFS.realPath(oldNode); - var newPath = PATH.join2(NODEFS.realPath(newDir), newName); - try { - fs.renameSync(oldPath, newPath) - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), unlink: (function (parent, name) { - var path = PATH.join2(NODEFS.realPath(parent), name); - try { - fs.unlinkSync(path) - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), rmdir: (function (parent, name) { - var path = PATH.join2(NODEFS.realPath(parent), name); - try { - fs.rmdirSync(path) - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), readdir: (function (node) { - var path = NODEFS.realPath(node); - try { - return fs.readdirSync(path) - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), symlink: (function (parent, newName, oldPath) { - var newPath = PATH.join2(NODEFS.realPath(parent), newName); - try { - fs.symlinkSync(oldPath, newPath) - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), readlink: (function (node) { - var path = NODEFS.realPath(node); - try { - path = fs.readlinkSync(path); - path = NODEJS_PATH.relative(NODEJS_PATH.resolve(node.mount.opts.root), path); - return path - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }) - }, stream_ops: { - open: (function (stream) { - var path = NODEFS.realPath(stream.node); - try { - if (FS.isFile(stream.node.mode)) { - stream.nfd = fs.openSync(path, NODEFS.flagsForNode(stream.flags)) - } - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), close: (function (stream) { - try { - if (FS.isFile(stream.node.mode) && stream.nfd) { - fs.closeSync(stream.nfd) - } - } catch (e) { - if (!e.code) throw e; - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), read: (function (stream, buffer, offset, length, position) { - if (length === 0) return 0; - try { - return fs.readSync(stream.nfd, NODEFS.bufferFrom(buffer.buffer), offset, length, position) - } catch (e) { - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), write: (function (stream, buffer, offset, length, position) { - try { - return fs.writeSync(stream.nfd, NODEFS.bufferFrom(buffer.buffer), offset, length, position) - } catch (e) { - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - }), llseek: (function (stream, offset, whence) { - var position = offset; - if (whence === 1) { - position += stream.position - } else if (whence === 2) { - if (FS.isFile(stream.node.mode)) { - try { - var stat = fs.fstatSync(stream.nfd); - position += stat.size - } catch (e) { - throw new FS.ErrnoError(ERRNO_CODES[e.code]) - } - } - } - if (position < 0) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - return position - }) - } -}; -var WORKERFS = { - DIR_MODE: 16895, FILE_MODE: 33279, reader: null, mount: (function (mount) { - assert(ENVIRONMENT_IS_WORKER); - if (!WORKERFS.reader) WORKERFS.reader = new FileReaderSync; - var root = WORKERFS.createNode(null, "/", WORKERFS.DIR_MODE, 0); - var createdParents = {}; - - function ensureParent(path) { - var parts = path.split("/"); - var parent = root; - for (var i = 0; i < parts.length - 1; i++) { - var curr = parts.slice(0, i + 1).join("/"); - if (!createdParents[curr]) { - createdParents[curr] = WORKERFS.createNode(parent, parts[i], WORKERFS.DIR_MODE, 0) - } - parent = createdParents[curr] - } - return parent - } - - function base(path) { - var parts = path.split("/"); - return parts[parts.length - 1] - } - - Array.prototype.forEach.call(mount.opts["files"] || [], (function (file) { - WORKERFS.createNode(ensureParent(file.name), base(file.name), WORKERFS.FILE_MODE, 0, file, file.lastModifiedDate) - })); - (mount.opts["blobs"] || []).forEach((function (obj) { - WORKERFS.createNode(ensureParent(obj["name"]), base(obj["name"]), WORKERFS.FILE_MODE, 0, obj["data"]) - })); - (mount.opts["packages"] || []).forEach((function (pack) { - pack["metadata"].files.forEach((function (file) { - var name = file.filename.substr(1); - WORKERFS.createNode(ensureParent(name), base(name), WORKERFS.FILE_MODE, 0, pack["blob"].slice(file.start, file.end)) - })) - })); - return root - }), createNode: (function (parent, name, mode, dev, contents, mtime) { - var node = FS.createNode(parent, name, mode); - node.mode = mode; - node.node_ops = WORKERFS.node_ops; - node.stream_ops = WORKERFS.stream_ops; - node.timestamp = (mtime || new Date).getTime(); - assert(WORKERFS.FILE_MODE !== WORKERFS.DIR_MODE); - if (mode === WORKERFS.FILE_MODE) { - node.size = contents.size; - node.contents = contents - } else { - node.size = 4096; - node.contents = {} - } - if (parent) { - parent.contents[name] = node - } - return node - }), node_ops: { - getattr: (function (node) { - return { - dev: 1, - ino: undefined, - mode: node.mode, - nlink: 1, - uid: 0, - gid: 0, - rdev: undefined, - size: node.size, - atime: new Date(node.timestamp), - mtime: new Date(node.timestamp), - ctime: new Date(node.timestamp), - blksize: 4096, - blocks: Math.ceil(node.size / 4096) - } - }), setattr: (function (node, attr) { - if (attr.mode !== undefined) { - node.mode = attr.mode - } - if (attr.timestamp !== undefined) { - node.timestamp = attr.timestamp - } - }), lookup: (function (parent, name) { - throw new FS.ErrnoError(ERRNO_CODES.ENOENT) - }), mknod: (function (parent, name, mode, dev) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - }), rename: (function (oldNode, newDir, newName) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - }), unlink: (function (parent, name) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - }), rmdir: (function (parent, name) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - }), readdir: (function (node) { - var entries = [".", ".."]; - for (var key in node.contents) { - if (!node.contents.hasOwnProperty(key)) { - continue - } - entries.push(key) - } - return entries - }), symlink: (function (parent, newName, oldPath) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - }), readlink: (function (node) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - }) - }, stream_ops: { - read: (function (stream, buffer, offset, length, position) { - if (position >= stream.node.size) return 0; - var chunk = stream.node.contents.slice(position, position + length); - var ab = WORKERFS.reader.readAsArrayBuffer(chunk); - buffer.set(new Uint8Array(ab), offset); - return chunk.size - }), write: (function (stream, buffer, offset, length, position) { - throw new FS.ErrnoError(ERRNO_CODES.EIO) - }), llseek: (function (stream, offset, whence) { - var position = offset; - if (whence === 1) { - position += stream.position - } else if (whence === 2) { - if (FS.isFile(stream.node.mode)) { - position += stream.node.size - } - } - if (position < 0) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - return position - }) - } -}; -STATICTOP += 16; -STATICTOP += 16; -STATICTOP += 16; -var FS = { - root: null, - mounts: [], - devices: {}, - streams: [], - nextInode: 1, - nameTable: null, - currentPath: "/", - initialized: false, - ignorePermissions: true, - trackingDelegate: {}, - tracking: {openFlags: {READ: 1, WRITE: 2}}, - ErrnoError: null, - genericErrors: {}, - filesystems: null, - syncFSRequests: 0, - handleFSError: (function (e) { - if (!(e instanceof FS.ErrnoError)) throw e + " : " + stackTrace(); - return ___setErrNo(e.errno) - }), - lookupPath: (function (path, opts) { - path = PATH.resolve(FS.cwd(), path); - opts = opts || {}; - if (!path) return {path: "", node: null}; - var defaults = {follow_mount: true, recurse_count: 0}; - for (var key in defaults) { - if (opts[key] === undefined) { - opts[key] = defaults[key] - } - } - if (opts.recurse_count > 8) { - throw new FS.ErrnoError(ERRNO_CODES.ELOOP) - } - var parts = PATH.normalizeArray(path.split("/").filter((function (p) { - return !!p - })), false); - var current = FS.root; - var current_path = "/"; - for (var i = 0; i < parts.length; i++) { - var islast = i === parts.length - 1; - if (islast && opts.parent) { - break - } - current = FS.lookupNode(current, parts[i]); - current_path = PATH.join2(current_path, parts[i]); - if (FS.isMountpoint(current)) { - if (!islast || islast && opts.follow_mount) { - current = current.mounted.root - } - } - if (!islast || opts.follow) { - var count = 0; - while (FS.isLink(current.mode)) { - var link = FS.readlink(current_path); - current_path = PATH.resolve(PATH.dirname(current_path), link); - var lookup = FS.lookupPath(current_path, {recurse_count: opts.recurse_count}); - current = lookup.node; - if (count++ > 40) { - throw new FS.ErrnoError(ERRNO_CODES.ELOOP) - } - } - } - } - return {path: current_path, node: current} - }), - getPath: (function (node) { - var path; - while (true) { - if (FS.isRoot(node)) { - var mount = node.mount.mountpoint; - if (!path) return mount; - return mount[mount.length - 1] !== "/" ? mount + "/" + path : mount + path - } - path = path ? node.name + "/" + path : node.name; - node = node.parent - } - }), - hashName: (function (parentid, name) { - var hash = 0; - for (var i = 0; i < name.length; i++) { - hash = (hash << 5) - hash + name.charCodeAt(i) | 0 - } - return (parentid + hash >>> 0) % FS.nameTable.length - }), - hashAddNode: (function (node) { - var hash = FS.hashName(node.parent.id, node.name); - node.name_next = FS.nameTable[hash]; - FS.nameTable[hash] = node - }), - hashRemoveNode: (function (node) { - var hash = FS.hashName(node.parent.id, node.name); - if (FS.nameTable[hash] === node) { - FS.nameTable[hash] = node.name_next - } else { - var current = FS.nameTable[hash]; - while (current) { - if (current.name_next === node) { - current.name_next = node.name_next; - break - } - current = current.name_next - } - } - }), - lookupNode: (function (parent, name) { - var err = FS.mayLookup(parent); - if (err) { - throw new FS.ErrnoError(err, parent) - } - var hash = FS.hashName(parent.id, name); - for (var node = FS.nameTable[hash]; node; node = node.name_next) { - var nodeName = node.name; - if (node.parent.id === parent.id && nodeName === name) { - return node - } - } - return FS.lookup(parent, name) - }), - createNode: (function (parent, name, mode, rdev) { - if (!FS.FSNode) { - FS.FSNode = (function (parent, name, mode, rdev) { - if (!parent) { - parent = this - } - this.parent = parent; - this.mount = parent.mount; - this.mounted = null; - this.id = FS.nextInode++; - this.name = name; - this.mode = mode; - this.node_ops = {}; - this.stream_ops = {}; - this.rdev = rdev - }); - FS.FSNode.prototype = {}; - var readMode = 292 | 73; - var writeMode = 146; - Object.defineProperties(FS.FSNode.prototype, { - read: { - get: (function () { - return (this.mode & readMode) === readMode - }), set: (function (val) { - val ? this.mode |= readMode : this.mode &= ~readMode - }) - }, write: { - get: (function () { - return (this.mode & writeMode) === writeMode - }), set: (function (val) { - val ? this.mode |= writeMode : this.mode &= ~writeMode - }) - }, isFolder: { - get: (function () { - return FS.isDir(this.mode) - }) - }, isDevice: { - get: (function () { - return FS.isChrdev(this.mode) - }) - } - }) - } - var node = new FS.FSNode(parent, name, mode, rdev); - FS.hashAddNode(node); - return node - }), - destroyNode: (function (node) { - FS.hashRemoveNode(node) - }), - isRoot: (function (node) { - return node === node.parent - }), - isMountpoint: (function (node) { - return !!node.mounted - }), - isFile: (function (mode) { - return (mode & 61440) === 32768 - }), - isDir: (function (mode) { - return (mode & 61440) === 16384 - }), - isLink: (function (mode) { - return (mode & 61440) === 40960 - }), - isChrdev: (function (mode) { - return (mode & 61440) === 8192 - }), - isBlkdev: (function (mode) { - return (mode & 61440) === 24576 - }), - isFIFO: (function (mode) { - return (mode & 61440) === 4096 - }), - isSocket: (function (mode) { - return (mode & 49152) === 49152 - }), - flagModes: { - "r": 0, - "rs": 1052672, - "r+": 2, - "w": 577, - "wx": 705, - "xw": 705, - "w+": 578, - "wx+": 706, - "xw+": 706, - "a": 1089, - "ax": 1217, - "xa": 1217, - "a+": 1090, - "ax+": 1218, - "xa+": 1218 - }, - modeStringToFlags: (function (str) { - var flags = FS.flagModes[str]; - if (typeof flags === "undefined") { - throw new Error("Unknown file open mode: " + str) - } - return flags - }), - flagsToPermissionString: (function (flag) { - var perms = ["r", "w", "rw"][flag & 3]; - if (flag & 512) { - perms += "w" - } - return perms - }), - nodePermissions: (function (node, perms) { - if (FS.ignorePermissions) { - return 0 - } - if (perms.indexOf("r") !== -1 && !(node.mode & 292)) { - return ERRNO_CODES.EACCES - } else if (perms.indexOf("w") !== -1 && !(node.mode & 146)) { - return ERRNO_CODES.EACCES - } else if (perms.indexOf("x") !== -1 && !(node.mode & 73)) { - return ERRNO_CODES.EACCES - } - return 0 - }), - mayLookup: (function (dir) { - var err = FS.nodePermissions(dir, "x"); - if (err) return err; - if (!dir.node_ops.lookup) return ERRNO_CODES.EACCES; - return 0 - }), - mayCreate: (function (dir, name) { - try { - var node = FS.lookupNode(dir, name); - return ERRNO_CODES.EEXIST - } catch (e) { - } - return FS.nodePermissions(dir, "wx") - }), - mayDelete: (function (dir, name, isdir) { - var node; - try { - node = FS.lookupNode(dir, name) - } catch (e) { - return e.errno - } - var err = FS.nodePermissions(dir, "wx"); - if (err) { - return err - } - if (isdir) { - if (!FS.isDir(node.mode)) { - return ERRNO_CODES.ENOTDIR - } - if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) { - return ERRNO_CODES.EBUSY - } - } else { - if (FS.isDir(node.mode)) { - return ERRNO_CODES.EISDIR - } - } - return 0 - }), - mayOpen: (function (node, flags) { - if (!node) { - return ERRNO_CODES.ENOENT - } - if (FS.isLink(node.mode)) { - return ERRNO_CODES.ELOOP - } else if (FS.isDir(node.mode)) { - if (FS.flagsToPermissionString(flags) !== "r" || flags & 512) { - return ERRNO_CODES.EISDIR - } - } - return FS.nodePermissions(node, FS.flagsToPermissionString(flags)) - }), - MAX_OPEN_FDS: 4096, - nextfd: (function (fd_start, fd_end) { - fd_start = fd_start || 0; - fd_end = fd_end || FS.MAX_OPEN_FDS; - for (var fd = fd_start; fd <= fd_end; fd++) { - if (!FS.streams[fd]) { - return fd - } - } - throw new FS.ErrnoError(ERRNO_CODES.EMFILE) - }), - getStream: (function (fd) { - return FS.streams[fd] - }), - createStream: (function (stream, fd_start, fd_end) { - if (!FS.FSStream) { - FS.FSStream = (function () { - }); - FS.FSStream.prototype = {}; - Object.defineProperties(FS.FSStream.prototype, { - object: { - get: (function () { - return this.node - }), set: (function (val) { - this.node = val - }) - }, isRead: { - get: (function () { - return (this.flags & 2097155) !== 1 - }) - }, isWrite: { - get: (function () { - return (this.flags & 2097155) !== 0 - }) - }, isAppend: { - get: (function () { - return this.flags & 1024 - }) - } - }) - } - var newStream = new FS.FSStream; - for (var p in stream) { - newStream[p] = stream[p] - } - stream = newStream; - var fd = FS.nextfd(fd_start, fd_end); - stream.fd = fd; - FS.streams[fd] = stream; - return stream - }), - closeStream: (function (fd) { - FS.streams[fd] = null - }), - chrdev_stream_ops: { - open: (function (stream) { - var device = FS.getDevice(stream.node.rdev); - stream.stream_ops = device.stream_ops; - if (stream.stream_ops.open) { - stream.stream_ops.open(stream) - } - }), llseek: (function () { - throw new FS.ErrnoError(ERRNO_CODES.ESPIPE) - }) - }, - major: (function (dev) { - return dev >> 8 - }), - minor: (function (dev) { - return dev & 255 - }), - makedev: (function (ma, mi) { - return ma << 8 | mi - }), - registerDevice: (function (dev, ops) { - FS.devices[dev] = {stream_ops: ops} - }), - getDevice: (function (dev) { - return FS.devices[dev] - }), - getMounts: (function (mount) { - var mounts = []; - var check = [mount]; - while (check.length) { - var m = check.pop(); - mounts.push(m); - check.push.apply(check, m.mounts) - } - return mounts - }), - syncfs: (function (populate, callback) { - if (typeof populate === "function") { - callback = populate; - populate = false - } - FS.syncFSRequests++; - if (FS.syncFSRequests > 1) { - console.log("warning: " + FS.syncFSRequests + " FS.syncfs operations in flight at once, probably just doing extra work") - } - var mounts = FS.getMounts(FS.root.mount); - var completed = 0; - - function doCallback(err) { - assert(FS.syncFSRequests > 0); - FS.syncFSRequests--; - return callback(err) - } - - function done(err) { - if (err) { - if (!done.errored) { - done.errored = true; - return doCallback(err) - } - return - } - if (++completed >= mounts.length) { - doCallback(null) - } - } - - mounts.forEach((function (mount) { - if (!mount.type.syncfs) { - return done(null) - } - mount.type.syncfs(mount, populate, done) - })) - }), - mount: (function (type, opts, mountpoint) { - var root = mountpoint === "/"; - var pseudo = !mountpoint; - var node; - if (root && FS.root) { - throw new FS.ErrnoError(ERRNO_CODES.EBUSY) - } else if (!root && !pseudo) { - var lookup = FS.lookupPath(mountpoint, {follow_mount: false}); - mountpoint = lookup.path; - node = lookup.node; - if (FS.isMountpoint(node)) { - throw new FS.ErrnoError(ERRNO_CODES.EBUSY) - } - if (!FS.isDir(node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR) - } - } - var mount = {type: type, opts: opts, mountpoint: mountpoint, mounts: []}; - var mountRoot = type.mount(mount); - mountRoot.mount = mount; - mount.root = mountRoot; - if (root) { - FS.root = mountRoot - } else if (node) { - node.mounted = mount; - if (node.mount) { - node.mount.mounts.push(mount) - } - } - return mountRoot - }), - unmount: (function (mountpoint) { - var lookup = FS.lookupPath(mountpoint, {follow_mount: false}); - if (!FS.isMountpoint(lookup.node)) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - var node = lookup.node; - var mount = node.mounted; - var mounts = FS.getMounts(mount); - Object.keys(FS.nameTable).forEach((function (hash) { - var current = FS.nameTable[hash]; - while (current) { - var next = current.name_next; - if (mounts.indexOf(current.mount) !== -1) { - FS.destroyNode(current) - } - current = next - } - })); - node.mounted = null; - var idx = node.mount.mounts.indexOf(mount); - assert(idx !== -1); - node.mount.mounts.splice(idx, 1) - }), - lookup: (function (parent, name) { - return parent.node_ops.lookup(parent, name) - }), - mknod: (function (path, mode, dev) { - var lookup = FS.lookupPath(path, {parent: true}); - var parent = lookup.node; - var name = PATH.basename(path); - if (!name || name === "." || name === "..") { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - var err = FS.mayCreate(parent, name); - if (err) { - throw new FS.ErrnoError(err) - } - if (!parent.node_ops.mknod) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - return parent.node_ops.mknod(parent, name, mode, dev) - }), - create: (function (path, mode) { - mode = mode !== undefined ? mode : 438; - mode &= 4095; - mode |= 32768; - return FS.mknod(path, mode, 0) - }), - mkdir: (function (path, mode) { - mode = mode !== undefined ? mode : 511; - mode &= 511 | 512; - mode |= 16384; - return FS.mknod(path, mode, 0) - }), - mkdirTree: (function (path, mode) { - var dirs = path.split("/"); - var d = ""; - for (var i = 0; i < dirs.length; ++i) { - if (!dirs[i]) continue; - d += "/" + dirs[i]; - try { - FS.mkdir(d, mode) - } catch (e) { - if (e.errno != ERRNO_CODES.EEXIST) throw e - } - } - }), - mkdev: (function (path, mode, dev) { - if (typeof dev === "undefined") { - dev = mode; - mode = 438 - } - mode |= 8192; - return FS.mknod(path, mode, dev) - }), - symlink: (function (oldpath, newpath) { - if (!PATH.resolve(oldpath)) { - throw new FS.ErrnoError(ERRNO_CODES.ENOENT) - } - var lookup = FS.lookupPath(newpath, {parent: true}); - var parent = lookup.node; - if (!parent) { - throw new FS.ErrnoError(ERRNO_CODES.ENOENT) - } - var newname = PATH.basename(newpath); - var err = FS.mayCreate(parent, newname); - if (err) { - throw new FS.ErrnoError(err) - } - if (!parent.node_ops.symlink) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - return parent.node_ops.symlink(parent, newname, oldpath) - }), - rename: (function (old_path, new_path) { - var old_dirname = PATH.dirname(old_path); - var new_dirname = PATH.dirname(new_path); - var old_name = PATH.basename(old_path); - var new_name = PATH.basename(new_path); - var lookup, old_dir, new_dir; - try { - lookup = FS.lookupPath(old_path, {parent: true}); - old_dir = lookup.node; - lookup = FS.lookupPath(new_path, {parent: true}); - new_dir = lookup.node - } catch (e) { - throw new FS.ErrnoError(ERRNO_CODES.EBUSY) - } - if (!old_dir || !new_dir) throw new FS.ErrnoError(ERRNO_CODES.ENOENT); - if (old_dir.mount !== new_dir.mount) { - throw new FS.ErrnoError(ERRNO_CODES.EXDEV) - } - var old_node = FS.lookupNode(old_dir, old_name); - var relative = PATH.relative(old_path, new_dirname); - if (relative.charAt(0) !== ".") { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - relative = PATH.relative(new_path, old_dirname); - if (relative.charAt(0) !== ".") { - throw new FS.ErrnoError(ERRNO_CODES.ENOTEMPTY) - } - var new_node; - try { - new_node = FS.lookupNode(new_dir, new_name) - } catch (e) { - } - if (old_node === new_node) { - return - } - var isdir = FS.isDir(old_node.mode); - var err = FS.mayDelete(old_dir, old_name, isdir); - if (err) { - throw new FS.ErrnoError(err) - } - err = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name); - if (err) { - throw new FS.ErrnoError(err) - } - if (!old_dir.node_ops.rename) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) { - throw new FS.ErrnoError(ERRNO_CODES.EBUSY) - } - if (new_dir !== old_dir) { - err = FS.nodePermissions(old_dir, "w"); - if (err) { - throw new FS.ErrnoError(err) - } - } - try { - if (FS.trackingDelegate["willMovePath"]) { - FS.trackingDelegate["willMovePath"](old_path, new_path) - } - } catch (e) { - console.log("FS.trackingDelegate['willMovePath']('" + old_path + "', '" + new_path + "') threw an exception: " + e.message) - } - FS.hashRemoveNode(old_node); - try { - old_dir.node_ops.rename(old_node, new_dir, new_name) - } catch (e) { - throw e - } finally { - FS.hashAddNode(old_node) - } - try { - if (FS.trackingDelegate["onMovePath"]) FS.trackingDelegate["onMovePath"](old_path, new_path) - } catch (e) { - console.log("FS.trackingDelegate['onMovePath']('" + old_path + "', '" + new_path + "') threw an exception: " + e.message) - } - }), - rmdir: (function (path) { - var lookup = FS.lookupPath(path, {parent: true}); - var parent = lookup.node; - var name = PATH.basename(path); - var node = FS.lookupNode(parent, name); - var err = FS.mayDelete(parent, name, true); - if (err) { - throw new FS.ErrnoError(err) - } - if (!parent.node_ops.rmdir) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - if (FS.isMountpoint(node)) { - throw new FS.ErrnoError(ERRNO_CODES.EBUSY) - } - try { - if (FS.trackingDelegate["willDeletePath"]) { - FS.trackingDelegate["willDeletePath"](path) - } - } catch (e) { - console.log("FS.trackingDelegate['willDeletePath']('" + path + "') threw an exception: " + e.message) - } - parent.node_ops.rmdir(parent, name); - FS.destroyNode(node); - try { - if (FS.trackingDelegate["onDeletePath"]) FS.trackingDelegate["onDeletePath"](path) - } catch (e) { - console.log("FS.trackingDelegate['onDeletePath']('" + path + "') threw an exception: " + e.message) - } - }), - readdir: (function (path) { - var lookup = FS.lookupPath(path, {follow: true}); - var node = lookup.node; - if (!node.node_ops.readdir) { - throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR) - } - return node.node_ops.readdir(node) - }), - unlink: (function (path) { - var lookup = FS.lookupPath(path, {parent: true}); - var parent = lookup.node; - var name = PATH.basename(path); - var node = FS.lookupNode(parent, name); - var err = FS.mayDelete(parent, name, false); - if (err) { - throw new FS.ErrnoError(err) - } - if (!parent.node_ops.unlink) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - if (FS.isMountpoint(node)) { - throw new FS.ErrnoError(ERRNO_CODES.EBUSY) - } - try { - if (FS.trackingDelegate["willDeletePath"]) { - FS.trackingDelegate["willDeletePath"](path) - } - } catch (e) { - console.log("FS.trackingDelegate['willDeletePath']('" + path + "') threw an exception: " + e.message) - } - parent.node_ops.unlink(parent, name); - FS.destroyNode(node); - try { - if (FS.trackingDelegate["onDeletePath"]) FS.trackingDelegate["onDeletePath"](path) - } catch (e) { - console.log("FS.trackingDelegate['onDeletePath']('" + path + "') threw an exception: " + e.message) - } - }), - readlink: (function (path) { - var lookup = FS.lookupPath(path); - var link = lookup.node; - if (!link) { - throw new FS.ErrnoError(ERRNO_CODES.ENOENT) - } - if (!link.node_ops.readlink) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - return PATH.resolve(FS.getPath(link.parent), link.node_ops.readlink(link)) - }), - stat: (function (path, dontFollow) { - var lookup = FS.lookupPath(path, {follow: !dontFollow}); - var node = lookup.node; - if (!node) { - throw new FS.ErrnoError(ERRNO_CODES.ENOENT) - } - if (!node.node_ops.getattr) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - return node.node_ops.getattr(node) - }), - lstat: (function (path) { - return FS.stat(path, true) - }), - chmod: (function (path, mode, dontFollow) { - var node; - if (typeof path === "string") { - var lookup = FS.lookupPath(path, {follow: !dontFollow}); - node = lookup.node - } else { - node = path - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - node.node_ops.setattr(node, {mode: mode & 4095 | node.mode & ~4095, timestamp: Date.now()}) - }), - lchmod: (function (path, mode) { - FS.chmod(path, mode, true) - }), - fchmod: (function (fd, mode) { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - FS.chmod(stream.node, mode) - }), - chown: (function (path, uid, gid, dontFollow) { - var node; - if (typeof path === "string") { - var lookup = FS.lookupPath(path, {follow: !dontFollow}); - node = lookup.node - } else { - node = path - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - node.node_ops.setattr(node, {timestamp: Date.now()}) - }), - lchown: (function (path, uid, gid) { - FS.chown(path, uid, gid, true) - }), - fchown: (function (fd, uid, gid) { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - FS.chown(stream.node, uid, gid) - }), - truncate: (function (path, len) { - if (len < 0) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - var node; - if (typeof path === "string") { - var lookup = FS.lookupPath(path, {follow: true}); - node = lookup.node - } else { - node = path - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(ERRNO_CODES.EPERM) - } - if (FS.isDir(node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.EISDIR) - } - if (!FS.isFile(node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - var err = FS.nodePermissions(node, "w"); - if (err) { - throw new FS.ErrnoError(err) - } - node.node_ops.setattr(node, {size: len, timestamp: Date.now()}) - }), - ftruncate: (function (fd, len) { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - FS.truncate(stream.node, len) - }), - utime: (function (path, atime, mtime) { - var lookup = FS.lookupPath(path, {follow: true}); - var node = lookup.node; - node.node_ops.setattr(node, {timestamp: Math.max(atime, mtime)}) - }), - open: (function (path, flags, mode, fd_start, fd_end) { - if (path === "") { - throw new FS.ErrnoError(ERRNO_CODES.ENOENT) - } - flags = typeof flags === "string" ? FS.modeStringToFlags(flags) : flags; - mode = typeof mode === "undefined" ? 438 : mode; - if (flags & 64) { - mode = mode & 4095 | 32768 - } else { - mode = 0 - } - var node; - if (typeof path === "object") { - node = path - } else { - path = PATH.normalize(path); - try { - var lookup = FS.lookupPath(path, {follow: !(flags & 131072)}); - node = lookup.node - } catch (e) { - } - } - var created = false; - if (flags & 64) { - if (node) { - if (flags & 128) { - throw new FS.ErrnoError(ERRNO_CODES.EEXIST) - } - } else { - node = FS.mknod(path, mode, 0); - created = true - } - } - if (!node) { - throw new FS.ErrnoError(ERRNO_CODES.ENOENT) - } - if (FS.isChrdev(node.mode)) { - flags &= ~512 - } - if (flags & 65536 && !FS.isDir(node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR) - } - if (!created) { - var err = FS.mayOpen(node, flags); - if (err) { - throw new FS.ErrnoError(err) - } - } - if (flags & 512) { - FS.truncate(node, 0) - } - flags &= ~(128 | 512); - var stream = FS.createStream({ - node: node, - path: FS.getPath(node), - flags: flags, - seekable: true, - position: 0, - stream_ops: node.stream_ops, - ungotten: [], - error: false - }, fd_start, fd_end); - if (stream.stream_ops.open) { - stream.stream_ops.open(stream) - } - if (Module["logReadFiles"] && !(flags & 1)) { - if (!FS.readFiles) FS.readFiles = {}; - if (!(path in FS.readFiles)) { - FS.readFiles[path] = 1; - console.log("FS.trackingDelegate error on read file: " + path) - } - } - try { - if (FS.trackingDelegate["onOpenFile"]) { - var trackingFlags = 0; - if ((flags & 2097155) !== 1) { - trackingFlags |= FS.tracking.openFlags.READ - } - if ((flags & 2097155) !== 0) { - trackingFlags |= FS.tracking.openFlags.WRITE - } - FS.trackingDelegate["onOpenFile"](path, trackingFlags) - } - } catch (e) { - console.log("FS.trackingDelegate['onOpenFile']('" + path + "', flags) threw an exception: " + e.message) - } - return stream - }), - close: (function (stream) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if (stream.getdents) stream.getdents = null; - try { - if (stream.stream_ops.close) { - stream.stream_ops.close(stream) - } - } catch (e) { - throw e - } finally { - FS.closeStream(stream.fd) - } - stream.fd = null - }), - isClosed: (function (stream) { - return stream.fd === null - }), - llseek: (function (stream, offset, whence) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if (!stream.seekable || !stream.stream_ops.llseek) { - throw new FS.ErrnoError(ERRNO_CODES.ESPIPE) - } - stream.position = stream.stream_ops.llseek(stream, offset, whence); - stream.ungotten = []; - return stream.position - }), - read: (function (stream, buffer, offset, length, position) { - if (length < 0 || position < 0) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if ((stream.flags & 2097155) === 1) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if (FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.EISDIR) - } - if (!stream.stream_ops.read) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - var seeking = typeof position !== "undefined"; - if (!seeking) { - position = stream.position - } else if (!stream.seekable) { - throw new FS.ErrnoError(ERRNO_CODES.ESPIPE) - } - var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position); - if (!seeking) stream.position += bytesRead; - return bytesRead - }), - write: (function (stream, buffer, offset, length, position, canOwn) { - if (length < 0 || position < 0) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if (FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.EISDIR) - } - if (!stream.stream_ops.write) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - if (stream.flags & 1024) { - FS.llseek(stream, 0, 2) - } - var seeking = typeof position !== "undefined"; - if (!seeking) { - position = stream.position - } else if (!stream.seekable) { - throw new FS.ErrnoError(ERRNO_CODES.ESPIPE) - } - var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn); - if (!seeking) stream.position += bytesWritten; - try { - if (stream.path && FS.trackingDelegate["onWriteToFile"]) FS.trackingDelegate["onWriteToFile"](stream.path) - } catch (e) { - console.log("FS.trackingDelegate['onWriteToFile']('" + path + "') threw an exception: " + e.message) - } - return bytesWritten - }), - allocate: (function (stream, offset, length) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if (offset < 0 || length <= 0) { - throw new FS.ErrnoError(ERRNO_CODES.EINVAL) - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(ERRNO_CODES.EBADF) - } - if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.ENODEV) - } - if (!stream.stream_ops.allocate) { - throw new FS.ErrnoError(ERRNO_CODES.EOPNOTSUPP) - } - stream.stream_ops.allocate(stream, offset, length) - }), - mmap: (function (stream, buffer, offset, length, position, prot, flags) { - if ((stream.flags & 2097155) === 1) { - throw new FS.ErrnoError(ERRNO_CODES.EACCES) - } - if (!stream.stream_ops.mmap) { - throw new FS.ErrnoError(ERRNO_CODES.ENODEV) - } - return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags) - }), - msync: (function (stream, buffer, offset, length, mmapFlags) { - if (!stream || !stream.stream_ops.msync) { - return 0 - } - return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags) - }), - munmap: (function (stream) { - return 0 - }), - ioctl: (function (stream, cmd, arg) { - if (!stream.stream_ops.ioctl) { - throw new FS.ErrnoError(ERRNO_CODES.ENOTTY) - } - return stream.stream_ops.ioctl(stream, cmd, arg) - }), - readFile: (function (path, opts) { - opts = opts || {}; - opts.flags = opts.flags || "r"; - opts.encoding = opts.encoding || "binary"; - if (opts.encoding !== "utf8" && opts.encoding !== "binary") { - throw new Error('Invalid encoding type "' + opts.encoding + '"') - } - var ret; - var stream = FS.open(path, opts.flags); - var stat = FS.stat(path); - var length = stat.size; - var buf = new Uint8Array(length); - FS.read(stream, buf, 0, length, 0); - if (opts.encoding === "utf8") { - ret = UTF8ArrayToString(buf, 0) - } else if (opts.encoding === "binary") { - ret = buf - } - FS.close(stream); - return ret - }), - writeFile: (function (path, data, opts) { - opts = opts || {}; - opts.flags = opts.flags || "w"; - var stream = FS.open(path, opts.flags, opts.mode); - if (typeof data === "string") { - var buf = new Uint8Array(lengthBytesUTF8(data) + 1); - var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length); - FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn) - } else if (ArrayBuffer.isView(data)) { - FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn) - } else { - throw new Error("Unsupported data type") - } - FS.close(stream) - }), - cwd: (function () { - return FS.currentPath - }), - chdir: (function (path) { - var lookup = FS.lookupPath(path, {follow: true}); - if (lookup.node === null) { - throw new FS.ErrnoError(ERRNO_CODES.ENOENT) - } - if (!FS.isDir(lookup.node.mode)) { - throw new FS.ErrnoError(ERRNO_CODES.ENOTDIR) - } - var err = FS.nodePermissions(lookup.node, "x"); - if (err) { - throw new FS.ErrnoError(err) - } - FS.currentPath = lookup.path - }), - createDefaultDirectories: (function () { - FS.mkdir("/tmp"); - FS.mkdir("/home"); - FS.mkdir("/home/web_user") - }), - createDefaultDevices: (function () { - FS.mkdir("/dev"); - FS.registerDevice(FS.makedev(1, 3), { - read: (function () { - return 0 - }), write: (function (stream, buffer, offset, length, pos) { - return length - }) - }); - FS.mkdev("/dev/null", FS.makedev(1, 3)); - TTY.register(FS.makedev(5, 0), TTY.default_tty_ops); - TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops); - FS.mkdev("/dev/tty", FS.makedev(5, 0)); - FS.mkdev("/dev/tty1", FS.makedev(6, 0)); - var random_device; - if (typeof crypto !== "undefined") { - var randomBuffer = new Uint8Array(1); - random_device = (function () { - crypto.getRandomValues(randomBuffer); - return randomBuffer[0] - }) - } else if (ENVIRONMENT_IS_NODE) { - random_device = (function () { - return require("crypto")["randomBytes"](1)[0] - }) - } else { - random_device = (function () { - abort("random_device") - }) - } - FS.createDevice("/dev", "random", random_device); - FS.createDevice("/dev", "urandom", random_device); - FS.mkdir("/dev/shm"); - FS.mkdir("/dev/shm/tmp") - }), - createSpecialDirectories: (function () { - FS.mkdir("/proc"); - FS.mkdir("/proc/self"); - FS.mkdir("/proc/self/fd"); - FS.mount({ - mount: (function () { - var node = FS.createNode("/proc/self", "fd", 16384 | 511, 73); - node.node_ops = { - lookup: (function (parent, name) { - var fd = +name; - var stream = FS.getStream(fd); - if (!stream) throw new FS.ErrnoError(ERRNO_CODES.EBADF); - var ret = { - parent: null, mount: {mountpoint: "fake"}, node_ops: { - readlink: (function () { - return stream.path - }) - } - }; - ret.parent = ret; - return ret - }) - }; - return node - }) - }, {}, "/proc/self/fd") - }), - createStandardStreams: (function () { - if (Module["stdin"]) { - FS.createDevice("/dev", "stdin", Module["stdin"]) - } else { - FS.symlink("/dev/tty", "/dev/stdin") - } - if (Module["stdout"]) { - FS.createDevice("/dev", "stdout", null, Module["stdout"]) - } else { - FS.symlink("/dev/tty", "/dev/stdout") - } - if (Module["stderr"]) { - FS.createDevice("/dev", "stderr", null, Module["stderr"]) - } else { - FS.symlink("/dev/tty1", "/dev/stderr") - } - var stdin = FS.open("/dev/stdin", "r"); - assert(stdin.fd === 0, "invalid handle for stdin (" + stdin.fd + ")"); - var stdout = FS.open("/dev/stdout", "w"); - assert(stdout.fd === 1, "invalid handle for stdout (" + stdout.fd + ")"); - var stderr = FS.open("/dev/stderr", "w"); - assert(stderr.fd === 2, "invalid handle for stderr (" + stderr.fd + ")") - }), - ensureErrnoError: (function () { - if (FS.ErrnoError) return; - FS.ErrnoError = function ErrnoError(errno, node) { - this.node = node; - this.setErrno = (function (errno) { - this.errno = errno; - for (var key in ERRNO_CODES) { - if (ERRNO_CODES[key] === errno) { - this.code = key; - break - } - } - }); - this.setErrno(errno); - this.message = ERRNO_MESSAGES[errno]; - if (this.stack) Object.defineProperty(this, "stack", {value: (new Error).stack, writable: true}) - }; - FS.ErrnoError.prototype = new Error; - FS.ErrnoError.prototype.constructor = FS.ErrnoError; - [ERRNO_CODES.ENOENT].forEach((function (code) { - FS.genericErrors[code] = new FS.ErrnoError(code); - FS.genericErrors[code].stack = "" - })) - }), - staticInit: (function () { - FS.ensureErrnoError(); - FS.nameTable = new Array(4096); - FS.mount(MEMFS, {}, "/"); - FS.createDefaultDirectories(); - FS.createDefaultDevices(); - FS.createSpecialDirectories(); - FS.filesystems = {"MEMFS": MEMFS, "IDBFS": IDBFS, "NODEFS": NODEFS, "WORKERFS": WORKERFS} - }), - init: (function (input, output, error) { - assert(!FS.init.initialized, "FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"); - FS.init.initialized = true; - FS.ensureErrnoError(); - Module["stdin"] = input || Module["stdin"]; - Module["stdout"] = output || Module["stdout"]; - Module["stderr"] = error || Module["stderr"]; - FS.createStandardStreams() - }), - quit: (function () { - FS.init.initialized = false; - var fflush = Module["_fflush"]; - if (fflush) fflush(0); - for (var i = 0; i < FS.streams.length; i++) { - var stream = FS.streams[i]; - if (!stream) { - continue - } - FS.close(stream) - } - }), - getMode: (function (canRead, canWrite) { - var mode = 0; - if (canRead) mode |= 292 | 73; - if (canWrite) mode |= 146; - return mode - }), - joinPath: (function (parts, forceRelative) { - var path = PATH.join.apply(null, parts); - if (forceRelative && path[0] == "/") path = path.substr(1); - return path - }), - absolutePath: (function (relative, base) { - return PATH.resolve(base, relative) - }), - standardizePath: (function (path) { - return PATH.normalize(path) - }), - findObject: (function (path, dontResolveLastLink) { - var ret = FS.analyzePath(path, dontResolveLastLink); - if (ret.exists) { - return ret.object - } else { - ___setErrNo(ret.error); - return null - } - }), - analyzePath: (function (path, dontResolveLastLink) { - try { - var lookup = FS.lookupPath(path, {follow: !dontResolveLastLink}); - path = lookup.path - } catch (e) { - } - var ret = { - isRoot: false, - exists: false, - error: 0, - name: null, - path: null, - object: null, - parentExists: false, - parentPath: null, - parentObject: null - }; - try { - var lookup = FS.lookupPath(path, {parent: true}); - ret.parentExists = true; - ret.parentPath = lookup.path; - ret.parentObject = lookup.node; - ret.name = PATH.basename(path); - lookup = FS.lookupPath(path, {follow: !dontResolveLastLink}); - ret.exists = true; - ret.path = lookup.path; - ret.object = lookup.node; - ret.name = lookup.node.name; - ret.isRoot = lookup.path === "/" - } catch (e) { - ret.error = e.errno - } - return ret - }), - createFolder: (function (parent, name, canRead, canWrite) { - var path = PATH.join2(typeof parent === "string" ? parent : FS.getPath(parent), name); - var mode = FS.getMode(canRead, canWrite); - return FS.mkdir(path, mode) - }), - createPath: (function (parent, path, canRead, canWrite) { - parent = typeof parent === "string" ? parent : FS.getPath(parent); - var parts = path.split("/").reverse(); - while (parts.length) { - var part = parts.pop(); - if (!part) continue; - var current = PATH.join2(parent, part); - try { - FS.mkdir(current) - } catch (e) { - } - parent = current - } - return current - }), - createFile: (function (parent, name, properties, canRead, canWrite) { - var path = PATH.join2(typeof parent === "string" ? parent : FS.getPath(parent), name); - var mode = FS.getMode(canRead, canWrite); - return FS.create(path, mode) - }), - createDataFile: (function (parent, name, data, canRead, canWrite, canOwn) { - var path = name ? PATH.join2(typeof parent === "string" ? parent : FS.getPath(parent), name) : parent; - var mode = FS.getMode(canRead, canWrite); - var node = FS.create(path, mode); - if (data) { - if (typeof data === "string") { - var arr = new Array(data.length); - for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i); - data = arr - } - FS.chmod(node, mode | 146); - var stream = FS.open(node, "w"); - FS.write(stream, data, 0, data.length, 0, canOwn); - FS.close(stream); - FS.chmod(node, mode) - } - return node - }), - createDevice: (function (parent, name, input, output) { - var path = PATH.join2(typeof parent === "string" ? parent : FS.getPath(parent), name); - var mode = FS.getMode(!!input, !!output); - if (!FS.createDevice.major) FS.createDevice.major = 64; - var dev = FS.makedev(FS.createDevice.major++, 0); - FS.registerDevice(dev, { - open: (function (stream) { - stream.seekable = false - }), close: (function (stream) { - if (output && output.buffer && output.buffer.length) { - output(10) - } - }), read: (function (stream, buffer, offset, length, pos) { - var bytesRead = 0; - for (var i = 0; i < length; i++) { - var result; - try { - result = input() - } catch (e) { - throw new FS.ErrnoError(ERRNO_CODES.EIO) - } - if (result === undefined && bytesRead === 0) { - throw new FS.ErrnoError(ERRNO_CODES.EAGAIN) - } - if (result === null || result === undefined) break; - bytesRead++; - buffer[offset + i] = result - } - if (bytesRead) { - stream.node.timestamp = Date.now() - } - return bytesRead - }), write: (function (stream, buffer, offset, length, pos) { - for (var i = 0; i < length; i++) { - try { - output(buffer[offset + i]) - } catch (e) { - throw new FS.ErrnoError(ERRNO_CODES.EIO) - } - } - if (length) { - stream.node.timestamp = Date.now() - } - return i - }) - }); - return FS.mkdev(path, mode, dev) - }), - createLink: (function (parent, name, target, canRead, canWrite) { - var path = PATH.join2(typeof parent === "string" ? parent : FS.getPath(parent), name); - return FS.symlink(target, path) - }), - forceLoadFile: (function (obj) { - if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true; - var success = true; - if (typeof XMLHttpRequest !== "undefined") { - throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.") - } else if (Module["read"]) { - try { - obj.contents = intArrayFromString(Module["read"](obj.url), true); - obj.usedBytes = obj.contents.length - } catch (e) { - success = false - } - } else { - throw new Error("Cannot load without read() or XMLHttpRequest.") - } - if (!success) ___setErrNo(ERRNO_CODES.EIO); - return success - }), - createLazyFile: (function (parent, name, url, canRead, canWrite) { - function LazyUint8Array() { - this.lengthKnown = false; - this.chunks = [] - } - - LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) { - if (idx > this.length - 1 || idx < 0) { - return undefined - } - var chunkOffset = idx % this.chunkSize; - var chunkNum = idx / this.chunkSize | 0; - return this.getter(chunkNum)[chunkOffset] - }; - LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) { - this.getter = getter - }; - LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() { - var xhr = new XMLHttpRequest; - xhr.open("HEAD", url, false); - xhr.send(null); - if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status); - var datalength = Number(xhr.getResponseHeader("Content-length")); - var header; - var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes"; - var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip"; - var chunkSize = 1024 * 1024; - if (!hasByteServing) chunkSize = datalength; - var doXHR = (function (from, to) { - if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!"); - if (to > datalength - 1) throw new Error("only " + datalength + " bytes available! programmer error!"); - var xhr = new XMLHttpRequest; - xhr.open("GET", url, false); - if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to); - if (typeof Uint8Array != "undefined") xhr.responseType = "arraybuffer"; - if (xhr.overrideMimeType) { - xhr.overrideMimeType("text/plain; charset=x-user-defined") - } - xhr.send(null); - if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status); - if (xhr.response !== undefined) { - return new Uint8Array(xhr.response || []) - } else { - return intArrayFromString(xhr.responseText || "", true) - } - }); - var lazyArray = this; - lazyArray.setDataGetter((function (chunkNum) { - var start = chunkNum * chunkSize; - var end = (chunkNum + 1) * chunkSize - 1; - end = Math.min(end, datalength - 1); - if (typeof lazyArray.chunks[chunkNum] === "undefined") { - lazyArray.chunks[chunkNum] = doXHR(start, end) - } - if (typeof lazyArray.chunks[chunkNum] === "undefined") throw new Error("doXHR failed!"); - return lazyArray.chunks[chunkNum] - })); - if (usesGzip || !datalength) { - chunkSize = datalength = 1; - datalength = this.getter(0).length; - chunkSize = datalength; - console.log("LazyFiles on gzip forces download of the whole file when length is accessed") - } - this._length = datalength; - this._chunkSize = chunkSize; - this.lengthKnown = true - }; - if (typeof XMLHttpRequest !== "undefined") { - if (!ENVIRONMENT_IS_WORKER) throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc"; - var lazyArray = new LazyUint8Array; - Object.defineProperties(lazyArray, { - length: { - get: (function () { - if (!this.lengthKnown) { - this.cacheLength() - } - return this._length - }) - }, chunkSize: { - get: (function () { - if (!this.lengthKnown) { - this.cacheLength() - } - return this._chunkSize - }) - } - }); - var properties = {isDevice: false, contents: lazyArray} - } else { - var properties = {isDevice: false, url: url} - } - var node = FS.createFile(parent, name, properties, canRead, canWrite); - if (properties.contents) { - node.contents = properties.contents - } else if (properties.url) { - node.contents = null; - node.url = properties.url - } - Object.defineProperties(node, { - usedBytes: { - get: (function () { - return this.contents.length - }) - } - }); - var stream_ops = {}; - var keys = Object.keys(node.stream_ops); - keys.forEach((function (key) { - var fn = node.stream_ops[key]; - stream_ops[key] = function forceLoadLazyFile() { - if (!FS.forceLoadFile(node)) { - throw new FS.ErrnoError(ERRNO_CODES.EIO) - } - return fn.apply(null, arguments) - } - })); - stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) { - if (!FS.forceLoadFile(node)) { - throw new FS.ErrnoError(ERRNO_CODES.EIO) - } - var contents = stream.node.contents; - if (position >= contents.length) return 0; - var size = Math.min(contents.length - position, length); - assert(size >= 0); - if (contents.slice) { - for (var i = 0; i < size; i++) { - buffer[offset + i] = contents[position + i] - } - } else { - for (var i = 0; i < size; i++) { - buffer[offset + i] = contents.get(position + i) - } - } - return size - }; - node.stream_ops = stream_ops; - return node - }), - createPreloadedFile: (function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) { - Browser.init(); - var fullname = name ? PATH.resolve(PATH.join2(parent, name)) : parent; - var dep = getUniqueRunDependency("cp " + fullname); - - function processData(byteArray) { - function finish(byteArray) { - if (preFinish) preFinish(); - if (!dontCreateFile) { - FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn) - } - if (onload) onload(); - removeRunDependency(dep) - } - - var handled = false; - Module["preloadPlugins"].forEach((function (plugin) { - if (handled) return; - if (plugin["canHandle"](fullname)) { - plugin["handle"](byteArray, fullname, finish, (function () { - if (onerror) onerror(); - removeRunDependency(dep) - })); - handled = true - } - })); - if (!handled) finish(byteArray) - } - - addRunDependency(dep); - if (typeof url == "string") { - Browser.asyncLoad(url, (function (byteArray) { - processData(byteArray) - }), onerror) - } else { - processData(url) - } - }), - indexedDB: (function () { - return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB - }), - DB_NAME: (function () { - return "EM_FS_" + window.location.pathname - }), - DB_VERSION: 20, - DB_STORE_NAME: "FILE_DATA", - saveFilesToDB: (function (paths, onload, onerror) { - onload = onload || (function () { - }); - onerror = onerror || (function () { - }); - var indexedDB = FS.indexedDB(); - try { - var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION) - } catch (e) { - return onerror(e) - } - openRequest.onupgradeneeded = function openRequest_onupgradeneeded() { - var db = openRequest.result; - db.createObjectStore(FS.DB_STORE_NAME) - }; - openRequest.onsuccess = function openRequest_onsuccess() { - var db = openRequest.result; - var transaction = db.transaction([FS.DB_STORE_NAME], "readwrite"); - var files = transaction.objectStore(FS.DB_STORE_NAME); - var ok = 0, fail = 0, total = paths.length; - - function finish() { - if (fail == 0) onload(); else onerror() - } - - paths.forEach((function (path) { - var putRequest = files.put(FS.analyzePath(path).object.contents, path); - putRequest.onsuccess = function putRequest_onsuccess() { - ok++; - if (ok + fail == total) finish() - }; - putRequest.onerror = function putRequest_onerror() { - fail++; - if (ok + fail == total) finish() - } - })); - transaction.onerror = onerror - }; - openRequest.onerror = onerror - }), - loadFilesFromDB: (function (paths, onload, onerror) { - onload = onload || (function () { - }); - onerror = onerror || (function () { - }); - var indexedDB = FS.indexedDB(); - try { - var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION) - } catch (e) { - return onerror(e) - } - openRequest.onupgradeneeded = onerror; - openRequest.onsuccess = function openRequest_onsuccess() { - var db = openRequest.result; - try { - var transaction = db.transaction([FS.DB_STORE_NAME], "readonly") - } catch (e) { - onerror(e); - return - } - var files = transaction.objectStore(FS.DB_STORE_NAME); - var ok = 0, fail = 0, total = paths.length; - - function finish() { - if (fail == 0) onload(); else onerror() - } - - paths.forEach((function (path) { - var getRequest = files.get(path); - getRequest.onsuccess = function getRequest_onsuccess() { - if (FS.analyzePath(path).exists) { - FS.unlink(path) - } - FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true); - ok++; - if (ok + fail == total) finish() - }; - getRequest.onerror = function getRequest_onerror() { - fail++; - if (ok + fail == total) finish() - } - })); - transaction.onerror = onerror - }; - openRequest.onerror = onerror - }) -}; -var SYSCALLS = { - DEFAULT_POLLMASK: 5, mappings: {}, umask: 511, calculateAt: (function (dirfd, path) { - if (path[0] !== "/") { - var dir; - if (dirfd === -100) { - dir = FS.cwd() - } else { - var dirstream = FS.getStream(dirfd); - if (!dirstream) throw new FS.ErrnoError(ERRNO_CODES.EBADF); - dir = dirstream.path - } - path = PATH.join2(dir, path) - } - return path - }), doStat: (function (func, path, buf) { - try { - var stat = func(path) - } catch (e) { - if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) { - return -ERRNO_CODES.ENOTDIR - } - throw e - } - HEAP32[buf >> 2] = stat.dev; - HEAP32[buf + 4 >> 2] = 0; - HEAP32[buf + 8 >> 2] = stat.ino; - HEAP32[buf + 12 >> 2] = stat.mode; - HEAP32[buf + 16 >> 2] = stat.nlink; - HEAP32[buf + 20 >> 2] = stat.uid; - HEAP32[buf + 24 >> 2] = stat.gid; - HEAP32[buf + 28 >> 2] = stat.rdev; - HEAP32[buf + 32 >> 2] = 0; - HEAP32[buf + 36 >> 2] = stat.size; - HEAP32[buf + 40 >> 2] = 4096; - HEAP32[buf + 44 >> 2] = stat.blocks; - HEAP32[buf + 48 >> 2] = stat.atime.getTime() / 1e3 | 0; - HEAP32[buf + 52 >> 2] = 0; - HEAP32[buf + 56 >> 2] = stat.mtime.getTime() / 1e3 | 0; - HEAP32[buf + 60 >> 2] = 0; - HEAP32[buf + 64 >> 2] = stat.ctime.getTime() / 1e3 | 0; - HEAP32[buf + 68 >> 2] = 0; - HEAP32[buf + 72 >> 2] = stat.ino; - return 0 - }), doMsync: (function (addr, stream, len, flags) { - var buffer = new Uint8Array(HEAPU8.subarray(addr, addr + len)); - FS.msync(stream, buffer, 0, len, flags) - }), doMkdir: (function (path, mode) { - path = PATH.normalize(path); - if (path[path.length - 1] === "/") path = path.substr(0, path.length - 1); - FS.mkdir(path, mode, 0); - return 0 - }), doMknod: (function (path, mode, dev) { - switch (mode & 61440) { - case 32768: - case 8192: - case 24576: - case 4096: - case 49152: - break; - default: - return -ERRNO_CODES.EINVAL - } - FS.mknod(path, mode, dev); - return 0 - }), doReadlink: (function (path, buf, bufsize) { - if (bufsize <= 0) return -ERRNO_CODES.EINVAL; - var ret = FS.readlink(path); - var len = Math.min(bufsize, lengthBytesUTF8(ret)); - var endChar = HEAP8[buf + len]; - stringToUTF8(ret, buf, bufsize + 1); - HEAP8[buf + len] = endChar; - return len - }), doAccess: (function (path, amode) { - if (amode & ~7) { - return -ERRNO_CODES.EINVAL - } - var node; - var lookup = FS.lookupPath(path, {follow: true}); - node = lookup.node; - var perms = ""; - if (amode & 4) perms += "r"; - if (amode & 2) perms += "w"; - if (amode & 1) perms += "x"; - if (perms && FS.nodePermissions(node, perms)) { - return -ERRNO_CODES.EACCES - } - return 0 - }), doDup: (function (path, flags, suggestFD) { - var suggest = FS.getStream(suggestFD); - if (suggest) FS.close(suggest); - return FS.open(path, flags, 0, suggestFD, suggestFD).fd - }), doReadv: (function (stream, iov, iovcnt, offset) { - var ret = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = HEAP32[iov + i * 8 >> 2]; - var len = HEAP32[iov + (i * 8 + 4) >> 2]; - var curr = FS.read(stream, HEAP8, ptr, len, offset); - if (curr < 0) return -1; - ret += curr; - if (curr < len) break - } - return ret - }), doWritev: (function (stream, iov, iovcnt, offset) { - var ret = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = HEAP32[iov + i * 8 >> 2]; - var len = HEAP32[iov + (i * 8 + 4) >> 2]; - if (i === 0) { - const bfr = HEAP8.slice(ptr, ptr + len); - window.parent.postMessage(UTF8Decoder.decode(bfr), '*'); - } - var curr = FS.write(stream, HEAP8, ptr, len, offset); - if (curr < 0) return -1; - ret += curr - } - return ret - }), varargs: 0, get: (function (varargs) { - SYSCALLS.varargs += 4; - var ret = HEAP32[SYSCALLS.varargs - 4 >> 2]; - return ret - }), getStr: (function () { - var ret = Pointer_stringify(SYSCALLS.get()); - return ret - }), getStreamFromFD: (function () { - var stream = FS.getStream(SYSCALLS.get()); - if (!stream) throw new FS.ErrnoError(ERRNO_CODES.EBADF); - return stream - }), getSocketFromFD: (function () { - var socket = SOCKFS.getSocket(SYSCALLS.get()); - if (!socket) throw new FS.ErrnoError(ERRNO_CODES.EBADF); - return socket - }), getSocketAddress: (function (allowNull) { - var addrp = SYSCALLS.get(), addrlen = SYSCALLS.get(); - if (allowNull && addrp === 0) return null; - var info = __read_sockaddr(addrp, addrlen); - if (info.errno) throw new FS.ErrnoError(info.errno); - info.addr = DNS.lookup_addr(info.addr) || info.addr; - return info - }), get64: (function () { - var low = SYSCALLS.get(), high = SYSCALLS.get(); - if (low >= 0) assert(high === 0); else assert(high === -1); - return low - }), getZero: (function () { - assert(SYSCALLS.get() === 0) - }) -}; - -function ___syscall140(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(), offset_high = SYSCALLS.get(), offset_low = SYSCALLS.get(), - result = SYSCALLS.get(), whence = SYSCALLS.get(); - var offset = offset_low; - FS.llseek(stream, offset, whence); - HEAP32[result >> 2] = stream.position; - if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; - return 0 - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall145(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(), iov = SYSCALLS.get(), iovcnt = SYSCALLS.get(); - return SYSCALLS.doReadv(stream, iov, iovcnt) - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall146(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(), iov = SYSCALLS.get(), iovcnt = SYSCALLS.get(); - return SYSCALLS.doWritev(stream, iov, iovcnt) - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall192(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var addr = SYSCALLS.get(), len = SYSCALLS.get(), prot = SYSCALLS.get(), flags = SYSCALLS.get(), - fd = SYSCALLS.get(), off = SYSCALLS.get(); - off <<= 12; - var ptr; - var allocated = false; - if (fd === -1) { - ptr = _memalign(PAGE_SIZE, len); - if (!ptr) return -ERRNO_CODES.ENOMEM; - _memset(ptr, 0, len); - allocated = true - } else { - var info = FS.getStream(fd); - if (!info) return -ERRNO_CODES.EBADF; - var res = FS.mmap(info, HEAPU8, addr, len, off, prot, flags); - ptr = res.ptr; - allocated = res.allocated - } - SYSCALLS.mappings[ptr] = {malloc: ptr, len: len, allocated: allocated, fd: fd, flags: flags}; - return ptr - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall195(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var path = SYSCALLS.getStr(), buf = SYSCALLS.get(); - return SYSCALLS.doStat(FS.stat, path, buf) - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall197(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(), buf = SYSCALLS.get(); - return SYSCALLS.doStat(FS.stat, stream.path, buf) - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall221(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(), cmd = SYSCALLS.get(); - switch (cmd) { - case 0: { - var arg = SYSCALLS.get(); - if (arg < 0) { - return -ERRNO_CODES.EINVAL - } - var newStream; - newStream = FS.open(stream.path, stream.flags, 0, arg); - return newStream.fd - } - ; - case 1: - case 2: - return 0; - case 3: - return stream.flags; - case 4: { - var arg = SYSCALLS.get(); - stream.flags |= arg; - return 0 - } - ; - case 12: - case 12: { - var arg = SYSCALLS.get(); - var offset = 0; - HEAP16[arg + offset >> 1] = 2; - return 0 - } - ; - case 13: - case 14: - case 13: - case 14: - return 0; - case 16: - case 8: - return -ERRNO_CODES.EINVAL; - case 9: - ___setErrNo(ERRNO_CODES.EINVAL); - return -1; - default: { - return -ERRNO_CODES.EINVAL - } - } - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall3(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(), buf = SYSCALLS.get(), count = SYSCALLS.get(); - return FS.read(stream, HEAP8, buf, count) - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall5(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var pathname = SYSCALLS.getStr(), flags = SYSCALLS.get(), mode = SYSCALLS.get(); - var stream = FS.open(pathname, flags, mode); - return stream.fd - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall54(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(), op = SYSCALLS.get(); - switch (op) { - case 21509: - case 21505: { - if (!stream.tty) return -ERRNO_CODES.ENOTTY; - return 0 - } - ; - case 21510: - case 21511: - case 21512: - case 21506: - case 21507: - case 21508: { - if (!stream.tty) return -ERRNO_CODES.ENOTTY; - return 0 - } - ; - case 21519: { - if (!stream.tty) return -ERRNO_CODES.ENOTTY; - var argp = SYSCALLS.get(); - HEAP32[argp >> 2] = 0; - return 0 - } - ; - case 21520: { - if (!stream.tty) return -ERRNO_CODES.ENOTTY; - return -ERRNO_CODES.EINVAL - } - ; - case 21531: { - var argp = SYSCALLS.get(); - return FS.ioctl(stream, op, argp) - } - ; - case 21523: { - if (!stream.tty) return -ERRNO_CODES.ENOTTY; - return 0 - } - ; - case 21524: { - if (!stream.tty) return -ERRNO_CODES.ENOTTY; - return 0 - } - ; - default: - abort("bad ioctl syscall " + op) - } - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall6(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(); - FS.close(stream); - return 0 - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___syscall91(which, varargs) { - SYSCALLS.varargs = varargs; - try { - var addr = SYSCALLS.get(), len = SYSCALLS.get(); - var info = SYSCALLS.mappings[addr]; - if (!info) return 0; - if (len === info.len) { - var stream = FS.getStream(info.fd); - SYSCALLS.doMsync(addr, stream, len, info.flags); - FS.munmap(stream); - SYSCALLS.mappings[addr] = null; - if (info.allocated) { - _free(info.malloc) - } - } - return 0 - } catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) abort(e); - return -e.errno - } -} - -function ___unlock() { -} - -function getShiftFromSize(size) { - switch (size) { - case 1: - return 0; - case 2: - return 1; - case 4: - return 2; - case 8: - return 3; - default: - throw new TypeError("Unknown type size: " + size) - } -} - -function embind_init_charCodes() { - var codes = new Array(256); - for (var i = 0; i < 256; ++i) { - codes[i] = String.fromCharCode(i) - } - embind_charCodes = codes -} - -var embind_charCodes = undefined; - -function readLatin1String(ptr) { - var ret = ""; - var c = ptr; - while (HEAPU8[c]) { - ret += embind_charCodes[HEAPU8[c++]] - } - return ret -} - -var awaitingDependencies = {}; -var registeredTypes = {}; -var typeDependencies = {}; -var char_0 = 48; -var char_9 = 57; - -function makeLegalFunctionName(name) { - if (undefined === name) { - return "_unknown" - } - name = name.replace(/[^a-zA-Z0-9_]/g, "$"); - var f = name.charCodeAt(0); - if (f >= char_0 && f <= char_9) { - return "_" + name - } else { - return name - } -} - -function createNamedFunction(name, body) { - name = makeLegalFunctionName(name); - return (new Function("body", "return function " + name + "() {\n" + ' "use strict";' + " return body.apply(this, arguments);\n" + "};\n"))(body) -} - -function extendError(baseErrorType, errorName) { - var errorClass = createNamedFunction(errorName, (function (message) { - this.name = errorName; - this.message = message; - var stack = (new Error(message)).stack; - if (stack !== undefined) { - this.stack = this.toString() + "\n" + stack.replace(/^Error(:[^\n]*)?\n/, "") - } - })); - errorClass.prototype = Object.create(baseErrorType.prototype); - errorClass.prototype.constructor = errorClass; - errorClass.prototype.toString = (function () { - if (this.message === undefined) { - return this.name - } else { - return this.name + ": " + this.message - } - }); - return errorClass -} - -var BindingError = undefined; - -function throwBindingError(message) { - throw new BindingError(message) -} - -var InternalError = undefined; - -function throwInternalError(message) { - throw new InternalError(message) -} - -function whenDependentTypesAreResolved(myTypes, dependentTypes, getTypeConverters) { - myTypes.forEach((function (type) { - typeDependencies[type] = dependentTypes - })); - - function onComplete(typeConverters) { - var myTypeConverters = getTypeConverters(typeConverters); - if (myTypeConverters.length !== myTypes.length) { - throwInternalError("Mismatched type converter count") - } - for (var i = 0; i < myTypes.length; ++i) { - registerType(myTypes[i], myTypeConverters[i]) - } - } - - var typeConverters = new Array(dependentTypes.length); - var unregisteredTypes = []; - var registered = 0; - dependentTypes.forEach((function (dt, i) { - if (registeredTypes.hasOwnProperty(dt)) { - typeConverters[i] = registeredTypes[dt] - } else { - unregisteredTypes.push(dt); - if (!awaitingDependencies.hasOwnProperty(dt)) { - awaitingDependencies[dt] = [] - } - awaitingDependencies[dt].push((function () { - typeConverters[i] = registeredTypes[dt]; - ++registered; - if (registered === unregisteredTypes.length) { - onComplete(typeConverters) - } - })) - } - })); - if (0 === unregisteredTypes.length) { - onComplete(typeConverters) - } -} - -function registerType(rawType, registeredInstance, options) { - options = options || {}; - if (!("argPackAdvance" in registeredInstance)) { - throw new TypeError("registerType registeredInstance requires argPackAdvance") - } - var name = registeredInstance.name; - if (!rawType) { - throwBindingError('type "' + name + '" must have a positive integer typeid pointer') - } - if (registeredTypes.hasOwnProperty(rawType)) { - if (options.ignoreDuplicateRegistrations) { - return - } else { - throwBindingError("Cannot register type '" + name + "' twice") - } - } - registeredTypes[rawType] = registeredInstance; - delete typeDependencies[rawType]; - if (awaitingDependencies.hasOwnProperty(rawType)) { - var callbacks = awaitingDependencies[rawType]; - delete awaitingDependencies[rawType]; - callbacks.forEach((function (cb) { - cb() - })) - } -} - -function __embind_register_bool(rawType, name, size, trueValue, falseValue) { - var shift = getShiftFromSize(size); - name = readLatin1String(name); - registerType(rawType, { - name: name, "fromWireType": (function (wt) { - return !!wt - }), "toWireType": (function (destructors, o) { - return o ? trueValue : falseValue - }), "argPackAdvance": 8, "readValueFromPointer": (function (pointer) { - var heap; - if (size === 1) { - heap = HEAP8 - } else if (size === 2) { - heap = HEAP16 - } else if (size === 4) { - heap = HEAP32 - } else { - throw new TypeError("Unknown boolean type size: " + name) - } - return this["fromWireType"](heap[pointer >> shift]) - }), destructorFunction: null - }) -} - -function ClassHandle_isAliasOf(other) { - if (!(this instanceof ClassHandle)) { - return false - } - if (!(other instanceof ClassHandle)) { - return false - } - var leftClass = this.$$.ptrType.registeredClass; - var left = this.$$.ptr; - var rightClass = other.$$.ptrType.registeredClass; - var right = other.$$.ptr; - while (leftClass.baseClass) { - left = leftClass.upcast(left); - leftClass = leftClass.baseClass - } - while (rightClass.baseClass) { - right = rightClass.upcast(right); - rightClass = rightClass.baseClass - } - return leftClass === rightClass && left === right -} - -function shallowCopyInternalPointer(o) { - return { - count: o.count, - deleteScheduled: o.deleteScheduled, - preservePointerOnDelete: o.preservePointerOnDelete, - ptr: o.ptr, - ptrType: o.ptrType, - smartPtr: o.smartPtr, - smartPtrType: o.smartPtrType - } -} - -function throwInstanceAlreadyDeleted(obj) { - function getInstanceTypeName(handle) { - return handle.$$.ptrType.registeredClass.name - } - - throwBindingError(getInstanceTypeName(obj) + " instance already deleted") -} - -function ClassHandle_clone() { - if (!this.$$.ptr) { - throwInstanceAlreadyDeleted(this) - } - if (this.$$.preservePointerOnDelete) { - this.$$.count.value += 1; - return this - } else { - var clone = Object.create(Object.getPrototypeOf(this), {$$: {value: shallowCopyInternalPointer(this.$$)}}); - clone.$$.count.value += 1; - clone.$$.deleteScheduled = false; - return clone - } -} - -function runDestructor(handle) { - var $$ = handle.$$; - if ($$.smartPtr) { - $$.smartPtrType.rawDestructor($$.smartPtr) - } else { - $$.ptrType.registeredClass.rawDestructor($$.ptr) - } -} - -function ClassHandle_delete() { - if (!this.$$.ptr) { - throwInstanceAlreadyDeleted(this) - } - if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) { - throwBindingError("Object already scheduled for deletion") - } - this.$$.count.value -= 1; - var toDelete = 0 === this.$$.count.value; - if (toDelete) { - runDestructor(this) - } - if (!this.$$.preservePointerOnDelete) { - this.$$.smartPtr = undefined; - this.$$.ptr = undefined - } -} - -function ClassHandle_isDeleted() { - return !this.$$.ptr -} - -var delayFunction = undefined; -var deletionQueue = []; - -function flushPendingDeletes() { - while (deletionQueue.length) { - var obj = deletionQueue.pop(); - obj.$$.deleteScheduled = false; - obj["delete"]() - } -} - -function ClassHandle_deleteLater() { - if (!this.$$.ptr) { - throwInstanceAlreadyDeleted(this) - } - if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) { - throwBindingError("Object already scheduled for deletion") - } - deletionQueue.push(this); - if (deletionQueue.length === 1 && delayFunction) { - delayFunction(flushPendingDeletes) - } - this.$$.deleteScheduled = true; - return this -} - -function init_ClassHandle() { - ClassHandle.prototype["isAliasOf"] = ClassHandle_isAliasOf; - ClassHandle.prototype["clone"] = ClassHandle_clone; - ClassHandle.prototype["delete"] = ClassHandle_delete; - ClassHandle.prototype["isDeleted"] = ClassHandle_isDeleted; - ClassHandle.prototype["deleteLater"] = ClassHandle_deleteLater -} - -function ClassHandle() { -} - -var registeredPointers = {}; - -function ensureOverloadTable(proto, methodName, humanName) { - if (undefined === proto[methodName].overloadTable) { - var prevFunc = proto[methodName]; - proto[methodName] = (function () { - if (!proto[methodName].overloadTable.hasOwnProperty(arguments.length)) { - throwBindingError("Function '" + humanName + "' called with an invalid number of arguments (" + arguments.length + ") - expects one of (" + proto[methodName].overloadTable + ")!") - } - return proto[methodName].overloadTable[arguments.length].apply(this, arguments) - }); - proto[methodName].overloadTable = []; - proto[methodName].overloadTable[prevFunc.argCount] = prevFunc - } -} - -function exposePublicSymbol(name, value, numArguments) { - if (Module.hasOwnProperty(name)) { - if (undefined === numArguments || undefined !== Module[name].overloadTable && undefined !== Module[name].overloadTable[numArguments]) { - throwBindingError("Cannot register public name '" + name + "' twice") - } - ensureOverloadTable(Module, name, name); - if (Module.hasOwnProperty(numArguments)) { - throwBindingError("Cannot register multiple overloads of a function with the same number of arguments (" + numArguments + ")!") - } - Module[name].overloadTable[numArguments] = value - } else { - Module[name] = value; - if (undefined !== numArguments) { - Module[name].numArguments = numArguments - } - } -} - -function RegisteredClass(name, constructor, instancePrototype, rawDestructor, baseClass, getActualType, upcast, downcast) { - this.name = name; - this.constructor = constructor; - this.instancePrototype = instancePrototype; - this.rawDestructor = rawDestructor; - this.baseClass = baseClass; - this.getActualType = getActualType; - this.upcast = upcast; - this.downcast = downcast; - this.pureVirtualFunctions = [] -} - -function upcastPointer(ptr, ptrClass, desiredClass) { - while (ptrClass !== desiredClass) { - if (!ptrClass.upcast) { - throwBindingError("Expected null or instance of " + desiredClass.name + ", got an instance of " + ptrClass.name) - } - ptr = ptrClass.upcast(ptr); - ptrClass = ptrClass.baseClass - } - return ptr -} - -function constNoSmartPtrRawPointerToWireType(destructors, handle) { - if (handle === null) { - if (this.isReference) { - throwBindingError("null is not a valid " + this.name) - } - return 0 - } - if (!handle.$$) { - throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name) - } - if (!handle.$$.ptr) { - throwBindingError("Cannot pass deleted object as a pointer of type " + this.name) - } - var handleClass = handle.$$.ptrType.registeredClass; - var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass); - return ptr -} - -function genericPointerToWireType(destructors, handle) { - var ptr; - if (handle === null) { - if (this.isReference) { - throwBindingError("null is not a valid " + this.name) - } - if (this.isSmartPointer) { - ptr = this.rawConstructor(); - if (destructors !== null) { - destructors.push(this.rawDestructor, ptr) - } - return ptr - } else { - return 0 - } - } - if (!handle.$$) { - throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name) - } - if (!handle.$$.ptr) { - throwBindingError("Cannot pass deleted object as a pointer of type " + this.name) - } - if (!this.isConst && handle.$$.ptrType.isConst) { - throwBindingError("Cannot convert argument of type " + (handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name) + " to parameter type " + this.name) - } - var handleClass = handle.$$.ptrType.registeredClass; - ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass); - if (this.isSmartPointer) { - if (undefined === handle.$$.smartPtr) { - throwBindingError("Passing raw pointer to smart pointer is illegal") - } - switch (this.sharingPolicy) { - case 0: - if (handle.$$.smartPtrType === this) { - ptr = handle.$$.smartPtr - } else { - throwBindingError("Cannot convert argument of type " + (handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name) + " to parameter type " + this.name) - } - break; - case 1: - ptr = handle.$$.smartPtr; - break; - case 2: - if (handle.$$.smartPtrType === this) { - ptr = handle.$$.smartPtr - } else { - var clonedHandle = handle["clone"](); - ptr = this.rawShare(ptr, __emval_register((function () { - clonedHandle["delete"]() - }))); - if (destructors !== null) { - destructors.push(this.rawDestructor, ptr) - } - } - break; - default: - throwBindingError("Unsupporting sharing policy") - } - } - return ptr -} - -function nonConstNoSmartPtrRawPointerToWireType(destructors, handle) { - if (handle === null) { - if (this.isReference) { - throwBindingError("null is not a valid " + this.name) - } - return 0 - } - if (!handle.$$) { - throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name) - } - if (!handle.$$.ptr) { - throwBindingError("Cannot pass deleted object as a pointer of type " + this.name) - } - if (handle.$$.ptrType.isConst) { - throwBindingError("Cannot convert argument of type " + handle.$$.ptrType.name + " to parameter type " + this.name) - } - var handleClass = handle.$$.ptrType.registeredClass; - var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass); - return ptr -} - -function simpleReadValueFromPointer(pointer) { - return this["fromWireType"](HEAPU32[pointer >> 2]) -} - -function RegisteredPointer_getPointee(ptr) { - if (this.rawGetPointee) { - ptr = this.rawGetPointee(ptr) - } - return ptr -} - -function RegisteredPointer_destructor(ptr) { - if (this.rawDestructor) { - this.rawDestructor(ptr) - } -} - -function RegisteredPointer_deleteObject(handle) { - if (handle !== null) { - handle["delete"]() - } -} - -function downcastPointer(ptr, ptrClass, desiredClass) { - if (ptrClass === desiredClass) { - return ptr - } - if (undefined === desiredClass.baseClass) { - return null - } - var rv = downcastPointer(ptr, ptrClass, desiredClass.baseClass); - if (rv === null) { - return null - } - return desiredClass.downcast(rv) -} - -function getInheritedInstanceCount() { - return Object.keys(registeredInstances).length -} - -function getLiveInheritedInstances() { - var rv = []; - for (var k in registeredInstances) { - if (registeredInstances.hasOwnProperty(k)) { - rv.push(registeredInstances[k]) - } - } - return rv -} - -function setDelayFunction(fn) { - delayFunction = fn; - if (deletionQueue.length && delayFunction) { - delayFunction(flushPendingDeletes) - } -} - -function init_embind() { - Module["getInheritedInstanceCount"] = getInheritedInstanceCount; - Module["getLiveInheritedInstances"] = getLiveInheritedInstances; - Module["flushPendingDeletes"] = flushPendingDeletes; - Module["setDelayFunction"] = setDelayFunction -} - -var registeredInstances = {}; - -function getBasestPointer(class_, ptr) { - if (ptr === undefined) { - throwBindingError("ptr should not be undefined") - } - while (class_.baseClass) { - ptr = class_.upcast(ptr); - class_ = class_.baseClass - } - return ptr -} - -function getInheritedInstance(class_, ptr) { - ptr = getBasestPointer(class_, ptr); - return registeredInstances[ptr] -} - -function makeClassHandle(prototype, record) { - if (!record.ptrType || !record.ptr) { - throwInternalError("makeClassHandle requires ptr and ptrType") - } - var hasSmartPtrType = !!record.smartPtrType; - var hasSmartPtr = !!record.smartPtr; - if (hasSmartPtrType !== hasSmartPtr) { - throwInternalError("Both smartPtrType and smartPtr must be specified") - } - record.count = {value: 1}; - return Object.create(prototype, {$$: {value: record}}) -} - -function RegisteredPointer_fromWireType(ptr) { - var rawPointer = this.getPointee(ptr); - if (!rawPointer) { - this.destructor(ptr); - return null - } - var registeredInstance = getInheritedInstance(this.registeredClass, rawPointer); - if (undefined !== registeredInstance) { - if (0 === registeredInstance.$$.count.value) { - registeredInstance.$$.ptr = rawPointer; - registeredInstance.$$.smartPtr = ptr; - return registeredInstance["clone"]() - } else { - var rv = registeredInstance["clone"](); - this.destructor(ptr); - return rv - } - } - - function makeDefaultHandle() { - if (this.isSmartPointer) { - return makeClassHandle(this.registeredClass.instancePrototype, { - ptrType: this.pointeeType, - ptr: rawPointer, - smartPtrType: this, - smartPtr: ptr - }) - } else { - return makeClassHandle(this.registeredClass.instancePrototype, {ptrType: this, ptr: ptr}) - } - } - - var actualType = this.registeredClass.getActualType(rawPointer); - var registeredPointerRecord = registeredPointers[actualType]; - if (!registeredPointerRecord) { - return makeDefaultHandle.call(this) - } - var toType; - if (this.isConst) { - toType = registeredPointerRecord.constPointerType - } else { - toType = registeredPointerRecord.pointerType - } - var dp = downcastPointer(rawPointer, this.registeredClass, toType.registeredClass); - if (dp === null) { - return makeDefaultHandle.call(this) - } - if (this.isSmartPointer) { - return makeClassHandle(toType.registeredClass.instancePrototype, { - ptrType: toType, - ptr: dp, - smartPtrType: this, - smartPtr: ptr - }) - } else { - return makeClassHandle(toType.registeredClass.instancePrototype, {ptrType: toType, ptr: dp}) - } -} - -function init_RegisteredPointer() { - RegisteredPointer.prototype.getPointee = RegisteredPointer_getPointee; - RegisteredPointer.prototype.destructor = RegisteredPointer_destructor; - RegisteredPointer.prototype["argPackAdvance"] = 8; - RegisteredPointer.prototype["readValueFromPointer"] = simpleReadValueFromPointer; - RegisteredPointer.prototype["deleteObject"] = RegisteredPointer_deleteObject; - RegisteredPointer.prototype["fromWireType"] = RegisteredPointer_fromWireType -} - -function RegisteredPointer(name, registeredClass, isReference, isConst, isSmartPointer, pointeeType, sharingPolicy, rawGetPointee, rawConstructor, rawShare, rawDestructor) { - this.name = name; - this.registeredClass = registeredClass; - this.isReference = isReference; - this.isConst = isConst; - this.isSmartPointer = isSmartPointer; - this.pointeeType = pointeeType; - this.sharingPolicy = sharingPolicy; - this.rawGetPointee = rawGetPointee; - this.rawConstructor = rawConstructor; - this.rawShare = rawShare; - this.rawDestructor = rawDestructor; - if (!isSmartPointer && registeredClass.baseClass === undefined) { - if (isConst) { - this["toWireType"] = constNoSmartPtrRawPointerToWireType; - this.destructorFunction = null - } else { - this["toWireType"] = nonConstNoSmartPtrRawPointerToWireType; - this.destructorFunction = null - } - } else { - this["toWireType"] = genericPointerToWireType - } -} - -function replacePublicSymbol(name, value, numArguments) { - if (!Module.hasOwnProperty(name)) { - throwInternalError("Replacing nonexistant public symbol") - } - if (undefined !== Module[name].overloadTable && undefined !== numArguments) { - Module[name].overloadTable[numArguments] = value - } else { - Module[name] = value; - Module[name].argCount = numArguments - } -} - -function embind__requireFunction(signature, rawFunction) { - signature = readLatin1String(signature); - - function makeDynCaller(dynCall) { - var args = []; - for (var i = 1; i < signature.length; ++i) { - args.push("a" + i) - } - var name = "dynCall_" + signature + "_" + rawFunction; - var body = "return function " + name + "(" + args.join(", ") + ") {\n"; - body += " return dynCall(rawFunction" + (args.length ? ", " : "") + args.join(", ") + ");\n"; - body += "};\n"; - return (new Function("dynCall", "rawFunction", body))(dynCall, rawFunction) - } - - var fp; - if (Module["FUNCTION_TABLE_" + signature] !== undefined) { - fp = Module["FUNCTION_TABLE_" + signature][rawFunction] - } else if (typeof FUNCTION_TABLE !== "undefined") { - fp = FUNCTION_TABLE[rawFunction] - } else { - var dc = Module["dynCall_" + signature]; - if (dc === undefined) { - dc = Module["dynCall_" + signature.replace(/f/g, "d")]; - if (dc === undefined) { - throwBindingError("No dynCall invoker for signature: " + signature) - } - } - fp = makeDynCaller(dc) - } - if (typeof fp !== "function") { - throwBindingError("unknown function pointer with signature " + signature + ": " + rawFunction) - } - return fp -} - -var UnboundTypeError = undefined; - -function getTypeName(type) { - var ptr = ___getTypeName(type); - var rv = readLatin1String(ptr); - _free(ptr); - return rv -} - -function throwUnboundTypeError(message, types) { - var unboundTypes = []; - var seen = {}; - - function visit(type) { - if (seen[type]) { - return - } - if (registeredTypes[type]) { - return - } - if (typeDependencies[type]) { - typeDependencies[type].forEach(visit); - return - } - unboundTypes.push(type); - seen[type] = true - } - - types.forEach(visit); - throw new UnboundTypeError(message + ": " + unboundTypes.map(getTypeName).join([", "])) -} - -function __embind_register_class(rawType, rawPointerType, rawConstPointerType, baseClassRawType, getActualTypeSignature, getActualType, upcastSignature, upcast, downcastSignature, downcast, name, destructorSignature, rawDestructor) { - name = readLatin1String(name); - getActualType = embind__requireFunction(getActualTypeSignature, getActualType); - if (upcast) { - upcast = embind__requireFunction(upcastSignature, upcast) - } - if (downcast) { - downcast = embind__requireFunction(downcastSignature, downcast) - } - rawDestructor = embind__requireFunction(destructorSignature, rawDestructor); - var legalFunctionName = makeLegalFunctionName(name); - exposePublicSymbol(legalFunctionName, (function () { - throwUnboundTypeError("Cannot construct " + name + " due to unbound types", [baseClassRawType]) - })); - whenDependentTypesAreResolved([rawType, rawPointerType, rawConstPointerType], baseClassRawType ? [baseClassRawType] : [], (function (base) { - base = base[0]; - var baseClass; - var basePrototype; - if (baseClassRawType) { - baseClass = base.registeredClass; - basePrototype = baseClass.instancePrototype - } else { - basePrototype = ClassHandle.prototype - } - var constructor = createNamedFunction(legalFunctionName, (function () { - if (Object.getPrototypeOf(this) !== instancePrototype) { - throw new BindingError("Use 'new' to construct " + name) - } - if (undefined === registeredClass.constructor_body) { - throw new BindingError(name + " has no accessible constructor") - } - var body = registeredClass.constructor_body[arguments.length]; - if (undefined === body) { - throw new BindingError("Tried to invoke ctor of " + name + " with invalid number of parameters (" + arguments.length + ") - expected (" + Object.keys(registeredClass.constructor_body).toString() + ") parameters instead!") - } - return body.apply(this, arguments) - })); - var instancePrototype = Object.create(basePrototype, {constructor: {value: constructor}}); - constructor.prototype = instancePrototype; - var registeredClass = new RegisteredClass(name, constructor, instancePrototype, rawDestructor, baseClass, getActualType, upcast, downcast); - var referenceConverter = new RegisteredPointer(name, registeredClass, true, false, false); - var pointerConverter = new RegisteredPointer(name + "*", registeredClass, false, false, false); - var constPointerConverter = new RegisteredPointer(name + " const*", registeredClass, false, true, false); - registeredPointers[rawType] = {pointerType: pointerConverter, constPointerType: constPointerConverter}; - replacePublicSymbol(legalFunctionName, constructor); - return [referenceConverter, pointerConverter, constPointerConverter] - })) -} - -function heap32VectorToArray(count, firstElement) { - var array = []; - for (var i = 0; i < count; i++) { - array.push(HEAP32[(firstElement >> 2) + i]) - } - return array -} - -function runDestructors(destructors) { - while (destructors.length) { - var ptr = destructors.pop(); - var del = destructors.pop(); - del(ptr) - } -} - -function __embind_register_class_constructor(rawClassType, argCount, rawArgTypesAddr, invokerSignature, invoker, rawConstructor) { - var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr); - invoker = embind__requireFunction(invokerSignature, invoker); - whenDependentTypesAreResolved([], [rawClassType], (function (classType) { - classType = classType[0]; - var humanName = "constructor " + classType.name; - if (undefined === classType.registeredClass.constructor_body) { - classType.registeredClass.constructor_body = [] - } - if (undefined !== classType.registeredClass.constructor_body[argCount - 1]) { - throw new BindingError("Cannot register multiple constructors with identical number of parameters (" + (argCount - 1) + ") for class '" + classType.name + "'! Overload resolution is currently only performed using the parameter count, not actual type info!") - } - classType.registeredClass.constructor_body[argCount - 1] = function unboundTypeHandler() { - throwUnboundTypeError("Cannot construct " + classType.name + " due to unbound types", rawArgTypes) - }; - whenDependentTypesAreResolved([], rawArgTypes, (function (argTypes) { - classType.registeredClass.constructor_body[argCount - 1] = function constructor_body() { - if (arguments.length !== argCount - 1) { - throwBindingError(humanName + " called with " + arguments.length + " arguments, expected " + (argCount - 1)) - } - var destructors = []; - var args = new Array(argCount); - args[0] = rawConstructor; - for (var i = 1; i < argCount; ++i) { - args[i] = argTypes[i]["toWireType"](destructors, arguments[i - 1]) - } - var ptr = invoker.apply(null, args); - runDestructors(destructors); - return argTypes[0]["fromWireType"](ptr) - }; - return [] - })); - return [] - })) -} - -function new_(constructor, argumentList) { - if (!(constructor instanceof Function)) { - throw new TypeError("new_ called with constructor type " + typeof constructor + " which is not a function") - } - var dummy = createNamedFunction(constructor.name || "unknownFunctionName", (function () { - })); - dummy.prototype = constructor.prototype; - var obj = new dummy; - var r = constructor.apply(obj, argumentList); - return r instanceof Object ? r : obj -} - -function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc) { - var argCount = argTypes.length; - if (argCount < 2) { - throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!") - } - var isClassMethodFunc = argTypes[1] !== null && classType !== null; - var needsDestructorStack = false; - for (var i = 1; i < argTypes.length; ++i) { - if (argTypes[i] !== null && argTypes[i].destructorFunction === undefined) { - needsDestructorStack = true; - break - } - } - var returns = argTypes[0].name !== "void"; - var argsList = ""; - var argsListWired = ""; - for (var i = 0; i < argCount - 2; ++i) { - argsList += (i !== 0 ? ", " : "") + "arg" + i; - argsListWired += (i !== 0 ? ", " : "") + "arg" + i + "Wired" - } - var invokerFnBody = "return function " + makeLegalFunctionName(humanName) + "(" + argsList + ") {\n" + "if (arguments.length !== " + (argCount - 2) + ") {\n" + "throwBindingError('function " + humanName + " called with ' + arguments.length + ' arguments, expected " + (argCount - 2) + " args!');\n" + "}\n"; - if (needsDestructorStack) { - invokerFnBody += "var destructors = [];\n" - } - var dtorStack = needsDestructorStack ? "destructors" : "null"; - var args1 = ["throwBindingError", "invoker", "fn", "runDestructors", "retType", "classParam"]; - var args2 = [throwBindingError, cppInvokerFunc, cppTargetFunc, runDestructors, argTypes[0], argTypes[1]]; - if (isClassMethodFunc) { - invokerFnBody += "var thisWired = classParam.toWireType(" + dtorStack + ", this);\n" - } - for (var i = 0; i < argCount - 2; ++i) { - invokerFnBody += "var arg" + i + "Wired = argType" + i + ".toWireType(" + dtorStack + ", arg" + i + "); // " + argTypes[i + 2].name + "\n"; - args1.push("argType" + i); - args2.push(argTypes[i + 2]) - } - if (isClassMethodFunc) { - argsListWired = "thisWired" + (argsListWired.length > 0 ? ", " : "") + argsListWired - } - invokerFnBody += (returns ? "var rv = " : "") + "invoker(fn" + (argsListWired.length > 0 ? ", " : "") + argsListWired + ");\n"; - if (needsDestructorStack) { - invokerFnBody += "runDestructors(destructors);\n" - } else { - for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; ++i) { - var paramName = i === 1 ? "thisWired" : "arg" + (i - 2) + "Wired"; - if (argTypes[i].destructorFunction !== null) { - invokerFnBody += paramName + "_dtor(" + paramName + "); // " + argTypes[i].name + "\n"; - args1.push(paramName + "_dtor"); - args2.push(argTypes[i].destructorFunction) - } - } - } - if (returns) { - invokerFnBody += "var ret = retType.fromWireType(rv);\n" + "return ret;\n" - } else { - } - invokerFnBody += "}\n"; - args1.push(invokerFnBody); - var invokerFunction = new_(Function, args1).apply(null, args2); - return invokerFunction -} - -function __embind_register_class_function(rawClassType, methodName, argCount, rawArgTypesAddr, invokerSignature, rawInvoker, context, isPureVirtual) { - var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr); - methodName = readLatin1String(methodName); - rawInvoker = embind__requireFunction(invokerSignature, rawInvoker); - whenDependentTypesAreResolved([], [rawClassType], (function (classType) { - classType = classType[0]; - var humanName = classType.name + "." + methodName; - if (isPureVirtual) { - classType.registeredClass.pureVirtualFunctions.push(methodName) - } - - function unboundTypesHandler() { - throwUnboundTypeError("Cannot call " + humanName + " due to unbound types", rawArgTypes) - } - - var proto = classType.registeredClass.instancePrototype; - var method = proto[methodName]; - if (undefined === method || undefined === method.overloadTable && method.className !== classType.name && method.argCount === argCount - 2) { - unboundTypesHandler.argCount = argCount - 2; - unboundTypesHandler.className = classType.name; - proto[methodName] = unboundTypesHandler - } else { - ensureOverloadTable(proto, methodName, humanName); - proto[methodName].overloadTable[argCount - 2] = unboundTypesHandler - } - whenDependentTypesAreResolved([], rawArgTypes, (function (argTypes) { - var memberFunction = craftInvokerFunction(humanName, argTypes, classType, rawInvoker, context); - if (undefined === proto[methodName].overloadTable) { - memberFunction.argCount = argCount - 2; - proto[methodName] = memberFunction - } else { - proto[methodName].overloadTable[argCount - 2] = memberFunction - } - return [] - })); - return [] - })) -} - -var emval_free_list = []; -var emval_handle_array = [{}, {value: undefined}, {value: null}, {value: true}, {value: false}]; - -function __emval_decref(handle) { - if (handle > 4 && 0 === --emval_handle_array[handle].refcount) { - emval_handle_array[handle] = undefined; - emval_free_list.push(handle) - } -} - -function count_emval_handles() { - var count = 0; - for (var i = 5; i < emval_handle_array.length; ++i) { - if (emval_handle_array[i] !== undefined) { - ++count - } - } - return count -} - -function get_first_emval() { - for (var i = 5; i < emval_handle_array.length; ++i) { - if (emval_handle_array[i] !== undefined) { - return emval_handle_array[i] - } - } - return null -} - -function init_emval() { - Module["count_emval_handles"] = count_emval_handles; - Module["get_first_emval"] = get_first_emval -} - -function __emval_register(value) { - switch (value) { - case undefined: { - return 1 - } - ; - case null: { - return 2 - } - ; - case true: { - return 3 - } - ; - case false: { - return 4 - } - ; - default: { - var handle = emval_free_list.length ? emval_free_list.pop() : emval_handle_array.length; - emval_handle_array[handle] = {refcount: 1, value: value}; - return handle - } - } -} - -function __embind_register_emval(rawType, name) { - name = readLatin1String(name); - registerType(rawType, { - name: name, "fromWireType": (function (handle) { - var rv = emval_handle_array[handle].value; - __emval_decref(handle); - return rv - }), "toWireType": (function (destructors, value) { - return __emval_register(value) - }), "argPackAdvance": 8, "readValueFromPointer": simpleReadValueFromPointer, destructorFunction: null - }) -} - -function _embind_repr(v) { - if (v === null) { - return "null" - } - var t = typeof v; - if (t === "object" || t === "array" || t === "function") { - return v.toString() - } else { - return "" + v - } -} - -function floatReadValueFromPointer(name, shift) { - switch (shift) { - case 2: - return (function (pointer) { - return this["fromWireType"](HEAPF32[pointer >> 2]) - }); - case 3: - return (function (pointer) { - return this["fromWireType"](HEAPF64[pointer >> 3]) - }); - default: - throw new TypeError("Unknown float type: " + name) - } -} - -function __embind_register_float(rawType, name, size) { - var shift = getShiftFromSize(size); - name = readLatin1String(name); - registerType(rawType, { - name: name, - "fromWireType": (function (value) { - return value - }), - "toWireType": (function (destructors, value) { - if (typeof value !== "number" && typeof value !== "boolean") { - throw new TypeError('Cannot convert "' + _embind_repr(value) + '" to ' + this.name) - } - return value - }), - "argPackAdvance": 8, - "readValueFromPointer": floatReadValueFromPointer(name, shift), - destructorFunction: null - }) -} - -function integerReadValueFromPointer(name, shift, signed) { - switch (shift) { - case 0: - return signed ? function readS8FromPointer(pointer) { - return HEAP8[pointer] - } : function readU8FromPointer(pointer) { - return HEAPU8[pointer] - }; - case 1: - return signed ? function readS16FromPointer(pointer) { - return HEAP16[pointer >> 1] - } : function readU16FromPointer(pointer) { - return HEAPU16[pointer >> 1] - }; - case 2: - return signed ? function readS32FromPointer(pointer) { - return HEAP32[pointer >> 2] - } : function readU32FromPointer(pointer) { - return HEAPU32[pointer >> 2] - }; - default: - throw new TypeError("Unknown integer type: " + name) - } -} - -function __embind_register_integer(primitiveType, name, size, minRange, maxRange) { - name = readLatin1String(name); - if (maxRange === -1) { - maxRange = 4294967295 - } - var shift = getShiftFromSize(size); - var fromWireType = (function (value) { - return value - }); - if (minRange === 0) { - var bitshift = 32 - 8 * size; - fromWireType = (function (value) { - return value << bitshift >>> bitshift - }) - } - var isUnsignedType = name.indexOf("unsigned") != -1; - registerType(primitiveType, { - name: name, - "fromWireType": fromWireType, - "toWireType": (function (destructors, value) { - if (typeof value !== "number" && typeof value !== "boolean") { - throw new TypeError('Cannot convert "' + _embind_repr(value) + '" to ' + this.name) - } - if (value < minRange || value > maxRange) { - throw new TypeError('Passing a number "' + _embind_repr(value) + '" from JS side to C/C++ side to an argument of type "' + name + '", which is outside the valid range [' + minRange + ", " + maxRange + "]!") - } - return isUnsignedType ? value >>> 0 : value | 0 - }), - "argPackAdvance": 8, - "readValueFromPointer": integerReadValueFromPointer(name, shift, minRange !== 0), - destructorFunction: null - }) -} - -function __embind_register_memory_view(rawType, dataTypeIndex, name) { - var typeMapping = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; - var TA = typeMapping[dataTypeIndex]; - - function decodeMemoryView(handle) { - handle = handle >> 2; - var heap = HEAPU32; - var size = heap[handle]; - var data = heap[handle + 1]; - return new TA(heap["buffer"], data, size) - } - - name = readLatin1String(name); - registerType(rawType, { - name: name, - "fromWireType": decodeMemoryView, - "argPackAdvance": 8, - "readValueFromPointer": decodeMemoryView - }, {ignoreDuplicateRegistrations: true}) -} - -function __embind_register_std_string(rawType, name) { - name = readLatin1String(name); - var stdStringIsUTF8 = name === "std::string"; - registerType(rawType, { - name: name, - "fromWireType": (function (value) { - var length = HEAPU32[value >> 2]; - var str; - if (stdStringIsUTF8) { - var endChar = HEAPU8[value + 4 + length]; - var endCharSwap = 0; - if (endChar != 0) { - endCharSwap = endChar; - HEAPU8[value + 4 + length] = 0 - } - var decodeStartPtr = value + 4; - for (var i = 0; i <= length; ++i) { - var currentBytePtr = value + 4 + i; - if (HEAPU8[currentBytePtr] == 0) { - var stringSegment = UTF8ToString(decodeStartPtr); - if (str === undefined) str = stringSegment; else { - str += String.fromCharCode(0); - str += stringSegment - } - decodeStartPtr = currentBytePtr + 1 - } - } - if (endCharSwap != 0) HEAPU8[value + 4 + length] = endCharSwap - } else { - var a = new Array(length); - for (var i = 0; i < length; ++i) { - a[i] = String.fromCharCode(HEAPU8[value + 4 + i]) - } - str = a.join("") - } - _free(value); - return str - }), - "toWireType": (function (destructors, value) { - if (value instanceof ArrayBuffer) { - value = new Uint8Array(value) - } - var getLength; - var valueIsOfTypeString = typeof value === "string"; - if (!(valueIsOfTypeString || value instanceof Uint8Array || value instanceof Uint8ClampedArray || value instanceof Int8Array)) { - throwBindingError("Cannot pass non-string to std::string") - } - if (stdStringIsUTF8 && valueIsOfTypeString) { - getLength = (function () { - return lengthBytesUTF8(value) - }) - } else { - getLength = (function () { - return value.length - }) - } - var length = getLength(); - var ptr = _malloc(4 + length + 1); - HEAPU32[ptr >> 2] = length; - if (stdStringIsUTF8 && valueIsOfTypeString) { - stringToUTF8(value, ptr + 4, length + 1) - } else { - if (valueIsOfTypeString) { - for (var i = 0; i < length; ++i) { - var charCode = value.charCodeAt(i); - if (charCode > 255) { - _free(ptr); - throwBindingError("String has UTF-16 code units that do not fit in 8 bits") - } - HEAPU8[ptr + 4 + i] = charCode - } - } else { - for (var i = 0; i < length; ++i) { - HEAPU8[ptr + 4 + i] = value[i] - } - } - } - if (destructors !== null) { - destructors.push(_free, ptr) - } - return ptr - }), - "argPackAdvance": 8, - "readValueFromPointer": simpleReadValueFromPointer, - destructorFunction: (function (ptr) { - _free(ptr) - }) - }) -} - -function __embind_register_std_wstring(rawType, charSize, name) { - name = readLatin1String(name); - var getHeap, shift; - if (charSize === 2) { - getHeap = (function () { - return HEAPU16 - }); - shift = 1 - } else if (charSize === 4) { - getHeap = (function () { - return HEAPU32 - }); - shift = 2 - } - registerType(rawType, { - name: name, - "fromWireType": (function (value) { - var HEAP = getHeap(); - var length = HEAPU32[value >> 2]; - var a = new Array(length); - var start = value + 4 >> shift; - for (var i = 0; i < length; ++i) { - a[i] = String.fromCharCode(HEAP[start + i]) - } - _free(value); - return a.join("") - }), - "toWireType": (function (destructors, value) { - var HEAP = getHeap(); - var length = value.length; - var ptr = _malloc(4 + length * charSize); - HEAPU32[ptr >> 2] = length; - var start = ptr + 4 >> shift; - for (var i = 0; i < length; ++i) { - HEAP[start + i] = value.charCodeAt(i) - } - if (destructors !== null) { - destructors.push(_free, ptr) - } - return ptr - }), - "argPackAdvance": 8, - "readValueFromPointer": simpleReadValueFromPointer, - destructorFunction: (function (ptr) { - _free(ptr) - }) - }) -} - -function __embind_register_void(rawType, name) { - name = readLatin1String(name); - registerType(rawType, { - isVoid: true, name: name, "argPackAdvance": 0, "fromWireType": (function () { - return undefined - }), "toWireType": (function (destructors, o) { - return undefined - }) - }) -} - -function _abort() { - Module["abort"]() -} - -function _emscripten_get_now() { - abort() -} - -function _emscripten_get_now_is_monotonic() { - return ENVIRONMENT_IS_NODE || typeof dateNow !== "undefined" || (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && self["performance"] && self["performance"]["now"] -} - -function _clock_gettime(clk_id, tp) { - var now; - if (clk_id === 0) { - now = Date.now() - } else if (clk_id === 1 && _emscripten_get_now_is_monotonic()) { - now = _emscripten_get_now() - } else { - ___setErrNo(ERRNO_CODES.EINVAL); - return -1 - } - HEAP32[tp >> 2] = now / 1e3 | 0; - HEAP32[tp + 4 >> 2] = now % 1e3 * 1e3 * 1e3 | 0; - return 0 -} - -function __exit(status) { - exit(status) -} - -function _exit(status) { - __exit(status) -} - -function _getenv(name) { - if (name === 0) return 0; - name = Pointer_stringify(name); - if (!ENV.hasOwnProperty(name)) return 0; - if (_getenv.ret) _free(_getenv.ret); - _getenv.ret = allocateUTF8(ENV[name]); - return _getenv.ret -} - -function _llvm_bswap_i64(l, h) { - var retl = _llvm_bswap_i32(h) >>> 0; - var reth = _llvm_bswap_i32(l) >>> 0; - return (setTempRet0(reth), retl) | 0 -} - -function _llvm_eh_typeid_for(type) { - return type -} - -function _llvm_log10_f32(x) { - return Math.log(x) / Math.LN10 -} - -function _llvm_log10_f64() { - return _llvm_log10_f32.apply(null, arguments) -} - -function _llvm_stackrestore(p) { - var self = _llvm_stacksave; - var ret = self.LLVM_SAVEDSTACKS[p]; - self.LLVM_SAVEDSTACKS.splice(p, 1); - stackRestore(ret) -} - -function _llvm_stacksave() { - var self = _llvm_stacksave; - if (!self.LLVM_SAVEDSTACKS) { - self.LLVM_SAVEDSTACKS = [] - } - self.LLVM_SAVEDSTACKS.push(stackSave()); - return self.LLVM_SAVEDSTACKS.length - 1 -} - -var ___tm_current = STATICTOP; -STATICTOP += 48; -var ___tm_timezone = allocate(intArrayFromString("GMT"), "i8", ALLOC_STATIC); - -function _tzset() { - if (_tzset.called) return; - _tzset.called = true; - HEAP32[__get_timezone() >> 2] = (new Date).getTimezoneOffset() * 60; - var winter = new Date(2e3, 0, 1); - var summer = new Date(2e3, 6, 1); - HEAP32[__get_daylight() >> 2] = Number(winter.getTimezoneOffset() != summer.getTimezoneOffset()); - - function extractZone(date) { - var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/); - return match ? match[1] : "GMT" - } - - var winterName = extractZone(winter); - var summerName = extractZone(summer); - var winterNamePtr = allocate(intArrayFromString(winterName), "i8", ALLOC_NORMAL); - var summerNamePtr = allocate(intArrayFromString(summerName), "i8", ALLOC_NORMAL); - if (summer.getTimezoneOffset() < winter.getTimezoneOffset()) { - HEAP32[__get_tzname() >> 2] = winterNamePtr; - HEAP32[__get_tzname() + 4 >> 2] = summerNamePtr - } else { - HEAP32[__get_tzname() >> 2] = summerNamePtr; - HEAP32[__get_tzname() + 4 >> 2] = winterNamePtr - } -} - -function _localtime_r(time, tmPtr) { - _tzset(); - var date = new Date(HEAP32[time >> 2] * 1e3); - HEAP32[tmPtr >> 2] = date.getSeconds(); - HEAP32[tmPtr + 4 >> 2] = date.getMinutes(); - HEAP32[tmPtr + 8 >> 2] = date.getHours(); - HEAP32[tmPtr + 12 >> 2] = date.getDate(); - HEAP32[tmPtr + 16 >> 2] = date.getMonth(); - HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900; - HEAP32[tmPtr + 24 >> 2] = date.getDay(); - var start = new Date(date.getFullYear(), 0, 1); - var yday = (date.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24) | 0; - HEAP32[tmPtr + 28 >> 2] = yday; - HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60); - var summerOffset = (new Date(2e3, 6, 1)).getTimezoneOffset(); - var winterOffset = start.getTimezoneOffset(); - var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0; - HEAP32[tmPtr + 32 >> 2] = dst; - var zonePtr = HEAP32[__get_tzname() + (dst ? 4 : 0) >> 2]; - HEAP32[tmPtr + 40 >> 2] = zonePtr; - return tmPtr -} - -function _localtime(time) { - return _localtime_r(time, ___tm_current) -} - -function _emscripten_memcpy_big(dest, src, num) { - HEAPU8.set(HEAPU8.subarray(src, src + num), dest); - return dest -} - -function _usleep(useconds) { - var msec = useconds / 1e3; - if ((ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && self["performance"] && self["performance"]["now"]) { - var start = self["performance"]["now"](); - while (self["performance"]["now"]() - start < msec) { - } - } else { - var start = Date.now(); - while (Date.now() - start < msec) { - } - } - return 0 -} - -function _nanosleep(rqtp, rmtp) { - var seconds = HEAP32[rqtp >> 2]; - var nanoseconds = HEAP32[rqtp + 4 >> 2]; - if (rmtp !== 0) { - HEAP32[rmtp >> 2] = 0; - HEAP32[rmtp + 4 >> 2] = 0 - } - return _usleep(seconds * 1e6 + nanoseconds / 1e3) -} - -function _pthread_cond_destroy() { - return 0 -} - -function _pthread_cond_signal() { - return 0 -} - -function _pthread_cond_wait() { - return 0 -} - -function _pthread_create() { - return 11 -} - -var PTHREAD_SPECIFIC = {}; - -function _pthread_getspecific(key) { - return PTHREAD_SPECIFIC[key] || 0 -} - -function _pthread_join() { -} - -var PTHREAD_SPECIFIC_NEXT_KEY = 1; - -function _pthread_key_create(key, destructor) { - if (key == 0) { - return ERRNO_CODES.EINVAL - } - HEAP32[key >> 2] = PTHREAD_SPECIFIC_NEXT_KEY; - PTHREAD_SPECIFIC[PTHREAD_SPECIFIC_NEXT_KEY] = 0; - PTHREAD_SPECIFIC_NEXT_KEY++; - return 0 -} - -function _pthread_mutex_destroy() { -} - -function _pthread_once(ptr, func) { - if (!_pthread_once.seen) _pthread_once.seen = {}; - if (ptr in _pthread_once.seen) return; - Module["dynCall_v"](func); - _pthread_once.seen[ptr] = 1 -} - -function _pthread_setspecific(key, value) { - if (!(key in PTHREAD_SPECIFIC)) { - return ERRNO_CODES.EINVAL - } - PTHREAD_SPECIFIC[key] = value; - return 0 -} - -function __isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) -} - -function __arraySum(array, index) { - var sum = 0; - for (var i = 0; i <= index; sum += array[i++]) ; - return sum -} - -var __MONTH_DAYS_LEAP = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var __MONTH_DAYS_REGULAR = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - -function __addDays(date, days) { - var newDate = new Date(date.getTime()); - while (days > 0) { - var leap = __isLeapYear(newDate.getFullYear()); - var currentMonth = newDate.getMonth(); - var daysInCurrentMonth = (leap ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR)[currentMonth]; - if (days > daysInCurrentMonth - newDate.getDate()) { - days -= daysInCurrentMonth - newDate.getDate() + 1; - newDate.setDate(1); - if (currentMonth < 11) { - newDate.setMonth(currentMonth + 1) - } else { - newDate.setMonth(0); - newDate.setFullYear(newDate.getFullYear() + 1) - } - } else { - newDate.setDate(newDate.getDate() + days); - return newDate - } - } - return newDate -} - -function _strftime(s, maxsize, format, tm) { - var tm_zone = HEAP32[tm + 40 >> 2]; - var date = { - tm_sec: HEAP32[tm >> 2], - tm_min: HEAP32[tm + 4 >> 2], - tm_hour: HEAP32[tm + 8 >> 2], - tm_mday: HEAP32[tm + 12 >> 2], - tm_mon: HEAP32[tm + 16 >> 2], - tm_year: HEAP32[tm + 20 >> 2], - tm_wday: HEAP32[tm + 24 >> 2], - tm_yday: HEAP32[tm + 28 >> 2], - tm_isdst: HEAP32[tm + 32 >> 2], - tm_gmtoff: HEAP32[tm + 36 >> 2], - tm_zone: tm_zone ? Pointer_stringify(tm_zone) : "" - }; - var pattern = Pointer_stringify(format); - var EXPANSION_RULES_1 = { - "%c": "%a %b %d %H:%M:%S %Y", - "%D": "%m/%d/%y", - "%F": "%Y-%m-%d", - "%h": "%b", - "%r": "%I:%M:%S %p", - "%R": "%H:%M", - "%T": "%H:%M:%S", - "%x": "%m/%d/%y", - "%X": "%H:%M:%S" - }; - for (var rule in EXPANSION_RULES_1) { - pattern = pattern.replace(new RegExp(rule, "g"), EXPANSION_RULES_1[rule]) - } - var WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; - var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; - - function leadingSomething(value, digits, character) { - var str = typeof value === "number" ? value.toString() : value || ""; - while (str.length < digits) { - str = character[0] + str - } - return str - } - - function leadingNulls(value, digits) { - return leadingSomething(value, digits, "0") - } - - function compareByDay(date1, date2) { - function sgn(value) { - return value < 0 ? -1 : value > 0 ? 1 : 0 - } - - var compare; - if ((compare = sgn(date1.getFullYear() - date2.getFullYear())) === 0) { - if ((compare = sgn(date1.getMonth() - date2.getMonth())) === 0) { - compare = sgn(date1.getDate() - date2.getDate()) - } - } - return compare - } - - function getFirstWeekStartDate(janFourth) { - switch (janFourth.getDay()) { - case 0: - return new Date(janFourth.getFullYear() - 1, 11, 29); - case 1: - return janFourth; - case 2: - return new Date(janFourth.getFullYear(), 0, 3); - case 3: - return new Date(janFourth.getFullYear(), 0, 2); - case 4: - return new Date(janFourth.getFullYear(), 0, 1); - case 5: - return new Date(janFourth.getFullYear() - 1, 11, 31); - case 6: - return new Date(janFourth.getFullYear() - 1, 11, 30) - } - } - - function getWeekBasedYear(date) { - var thisDate = __addDays(new Date(date.tm_year + 1900, 0, 1), date.tm_yday); - var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4); - var janFourthNextYear = new Date(thisDate.getFullYear() + 1, 0, 4); - var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear); - var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear); - if (compareByDay(firstWeekStartThisYear, thisDate) <= 0) { - if (compareByDay(firstWeekStartNextYear, thisDate) <= 0) { - return thisDate.getFullYear() + 1 - } else { - return thisDate.getFullYear() - } - } else { - return thisDate.getFullYear() - 1 - } - } - - var EXPANSION_RULES_2 = { - "%a": (function (date) { - return WEEKDAYS[date.tm_wday].substring(0, 3) - }), "%A": (function (date) { - return WEEKDAYS[date.tm_wday] - }), "%b": (function (date) { - return MONTHS[date.tm_mon].substring(0, 3) - }), "%B": (function (date) { - return MONTHS[date.tm_mon] - }), "%C": (function (date) { - var year = date.tm_year + 1900; - return leadingNulls(year / 100 | 0, 2) - }), "%d": (function (date) { - return leadingNulls(date.tm_mday, 2) - }), "%e": (function (date) { - return leadingSomething(date.tm_mday, 2, " ") - }), "%g": (function (date) { - return getWeekBasedYear(date).toString().substring(2) - }), "%G": (function (date) { - return getWeekBasedYear(date) - }), "%H": (function (date) { - return leadingNulls(date.tm_hour, 2) - }), "%I": (function (date) { - var twelveHour = date.tm_hour; - if (twelveHour == 0) twelveHour = 12; else if (twelveHour > 12) twelveHour -= 12; - return leadingNulls(twelveHour, 2) - }), "%j": (function (date) { - return leadingNulls(date.tm_mday + __arraySum(__isLeapYear(date.tm_year + 1900) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, date.tm_mon - 1), 3) - }), "%m": (function (date) { - return leadingNulls(date.tm_mon + 1, 2) - }), "%M": (function (date) { - return leadingNulls(date.tm_min, 2) - }), "%n": (function () { - return "\n" - }), "%p": (function (date) { - if (date.tm_hour >= 0 && date.tm_hour < 12) { - return "AM" - } else { - return "PM" - } - }), "%S": (function (date) { - return leadingNulls(date.tm_sec, 2) - }), "%t": (function () { - return "\t" - }), "%u": (function (date) { - var day = new Date(date.tm_year + 1900, date.tm_mon + 1, date.tm_mday, 0, 0, 0, 0); - return day.getDay() || 7 - }), "%U": (function (date) { - var janFirst = new Date(date.tm_year + 1900, 0, 1); - var firstSunday = janFirst.getDay() === 0 ? janFirst : __addDays(janFirst, 7 - janFirst.getDay()); - var endDate = new Date(date.tm_year + 1900, date.tm_mon, date.tm_mday); - if (compareByDay(firstSunday, endDate) < 0) { - var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth() - 1) - 31; - var firstSundayUntilEndJanuary = 31 - firstSunday.getDate(); - var days = firstSundayUntilEndJanuary + februaryFirstUntilEndMonth + endDate.getDate(); - return leadingNulls(Math.ceil(days / 7), 2) - } - return compareByDay(firstSunday, janFirst) === 0 ? "01" : "00" - }), "%V": (function (date) { - var janFourthThisYear = new Date(date.tm_year + 1900, 0, 4); - var janFourthNextYear = new Date(date.tm_year + 1901, 0, 4); - var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear); - var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear); - var endDate = __addDays(new Date(date.tm_year + 1900, 0, 1), date.tm_yday); - if (compareByDay(endDate, firstWeekStartThisYear) < 0) { - return "53" - } - if (compareByDay(firstWeekStartNextYear, endDate) <= 0) { - return "01" - } - var daysDifference; - if (firstWeekStartThisYear.getFullYear() < date.tm_year + 1900) { - daysDifference = date.tm_yday + 32 - firstWeekStartThisYear.getDate() - } else { - daysDifference = date.tm_yday + 1 - firstWeekStartThisYear.getDate() - } - return leadingNulls(Math.ceil(daysDifference / 7), 2) - }), "%w": (function (date) { - var day = new Date(date.tm_year + 1900, date.tm_mon + 1, date.tm_mday, 0, 0, 0, 0); - return day.getDay() - }), "%W": (function (date) { - var janFirst = new Date(date.tm_year, 0, 1); - var firstMonday = janFirst.getDay() === 1 ? janFirst : __addDays(janFirst, janFirst.getDay() === 0 ? 1 : 7 - janFirst.getDay() + 1); - var endDate = new Date(date.tm_year + 1900, date.tm_mon, date.tm_mday); - if (compareByDay(firstMonday, endDate) < 0) { - var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) ? __MONTH_DAYS_LEAP : __MONTH_DAYS_REGULAR, endDate.getMonth() - 1) - 31; - var firstMondayUntilEndJanuary = 31 - firstMonday.getDate(); - var days = firstMondayUntilEndJanuary + februaryFirstUntilEndMonth + endDate.getDate(); - return leadingNulls(Math.ceil(days / 7), 2) - } - return compareByDay(firstMonday, janFirst) === 0 ? "01" : "00" - }), "%y": (function (date) { - return (date.tm_year + 1900).toString().substring(2) - }), "%Y": (function (date) { - return date.tm_year + 1900 - }), "%z": (function (date) { - var off = date.tm_gmtoff; - var ahead = off >= 0; - off = Math.abs(off) / 60; - off = off / 60 * 100 + off % 60; - return (ahead ? "+" : "-") + String("0000" + off).slice(-4) - }), "%Z": (function (date) { - return date.tm_zone - }), "%%": (function () { - return "%" - }) - }; - for (var rule in EXPANSION_RULES_2) { - if (pattern.indexOf(rule) >= 0) { - pattern = pattern.replace(new RegExp(rule, "g"), EXPANSION_RULES_2[rule](date)) - } - } - var bytes = intArrayFromString(pattern, false); - if (bytes.length > maxsize) { - return 0 - } - writeArrayToMemory(bytes, s); - return bytes.length - 1 -} - -function _strftime_l(s, maxsize, format, tm) { - return _strftime(s, maxsize, format, tm) -} - -FS.staticInit(); -__ATINIT__.unshift((function () { - if (!Module["noFSInit"] && !FS.init.initialized) FS.init() -})); -__ATMAIN__.push((function () { - FS.ignorePermissions = false -})); -__ATEXIT__.push((function () { - FS.quit() -})); -__ATINIT__.unshift((function () { - TTY.init() -})); -__ATEXIT__.push((function () { - TTY.shutdown() -})); -if (ENVIRONMENT_IS_NODE) { - var fs = require("fs"); - var NODEJS_PATH = require("path"); - NODEFS.staticInit() -} -embind_init_charCodes(); -BindingError = Module["BindingError"] = extendError(Error, "BindingError"); -InternalError = Module["InternalError"] = extendError(Error, "InternalError"); -init_ClassHandle(); -init_RegisteredPointer(); -init_embind(); -UnboundTypeError = Module["UnboundTypeError"] = extendError(Error, "UnboundTypeError"); -init_emval(); -if (ENVIRONMENT_IS_NODE) { - _emscripten_get_now = function _emscripten_get_now_actual() { - var t = process["hrtime"](); - return t[0] * 1e3 + t[1] / 1e6 - } -} else if (typeof dateNow !== "undefined") { - _emscripten_get_now = dateNow -} else if (typeof self === "object" && self["performance"] && typeof self["performance"]["now"] === "function") { - _emscripten_get_now = (function () { - return self["performance"]["now"]() - }) -} else if (typeof performance === "object" && typeof performance["now"] === "function") { - _emscripten_get_now = (function () { - return performance["now"]() - }) -} else { - _emscripten_get_now = Date.now -} -DYNAMICTOP_PTR = staticAlloc(4); -STACK_BASE = STACKTOP = alignMemory(STATICTOP); -STACK_MAX = STACK_BASE + TOTAL_STACK; -DYNAMIC_BASE = alignMemory(STACK_MAX); -HEAP32[DYNAMICTOP_PTR >> 2] = DYNAMIC_BASE; -staticSealed = true; - -function intArrayFromString(stringy, dontAddNull, length) { - var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1; - var u8array = new Array(len); - var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length); - if (dontAddNull) u8array.length = numBytesWritten; - return u8array -} - -Module["wasmTableSize"] = 1618; -Module["wasmMaxTableSize"] = 1618; - -function invoke_didd(index, a1, a2, a3) { - var sp = stackSave(); - try { - return Module["dynCall_didd"](index, a1, a2, a3) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_diii(index, a1, a2, a3) { - var sp = stackSave(); - try { - return Module["dynCall_diii"](index, a1, a2, a3) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_fif(index, a1, a2) { - var sp = stackSave(); - try { - return Module["dynCall_fif"](index, a1, a2) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_fii(index, a1, a2) { - var sp = stackSave(); - try { - return Module["dynCall_fii"](index, a1, a2) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_fiii(index, a1, a2, a3) { - var sp = stackSave(); - try { - return Module["dynCall_fiii"](index, a1, a2, a3) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_i(index) { - var sp = stackSave(); - try { - return Module["dynCall_i"](index) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_ii(index, a1) { - var sp = stackSave(); - try { - return Module["dynCall_ii"](index, a1) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iid(index, a1, a2) { - var sp = stackSave(); - try { - return Module["dynCall_iid"](index, a1, a2) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iif(index, a1, a2) { - var sp = stackSave(); - try { - return Module["dynCall_iif"](index, a1, a2) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iii(index, a1, a2) { - var sp = stackSave(); - try { - return Module["dynCall_iii"](index, a1, a2) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiii(index, a1, a2, a3) { - var sp = stackSave(); - try { - return Module["dynCall_iiii"](index, a1, a2, a3) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiii(index, a1, a2, a3, a4) { - var sp = stackSave(); - try { - return Module["dynCall_iiiii"](index, a1, a2, a3, a4) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiid(index, a1, a2, a3, a4, a5) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiid"](index, a1, a2, a3, a4, a5) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiii(index, a1, a2, a3, a4, a5) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiii"](index, a1, a2, a3, a4, a5) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiiii(index, a1, a2, a3, a4, a5, a6) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiiii"](index, a1, a2, a3, a4, a5, a6) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiiiii(index, a1, a2, a3, a4, a5, a6, a7) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7, a8) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiiiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiiiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiiiiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iiiiij(index, a1, a2, a3, a4, a5, a6) { - var sp = stackSave(); - try { - return Module["dynCall_iiiiij"](index, a1, a2, a3, a4, a5, a6) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iij(index, a1, a2, a3) { - var sp = stackSave(); - try { - return Module["dynCall_iij"](index, a1, a2, a3) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_iijii(index, a1, a2, a3, a4, a5) { - var sp = stackSave(); - try { - return Module["dynCall_iijii"](index, a1, a2, a3, a4, a5) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_ji(index, a1) { - var sp = stackSave(); - try { - return Module["dynCall_ji"](index, a1) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_jii(index, a1, a2) { - var sp = stackSave(); - try { - return Module["dynCall_jii"](index, a1, a2) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_jiiii(index, a1, a2, a3, a4) { - var sp = stackSave(); - try { - return Module["dynCall_jiiii"](index, a1, a2, a3, a4) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_v(index) { - var sp = stackSave(); - try { - Module["dynCall_v"](index) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_vi(index, a1) { - var sp = stackSave(); - try { - Module["dynCall_vi"](index, a1) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_vii(index, a1, a2) { - var sp = stackSave(); - try { - Module["dynCall_vii"](index, a1, a2) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viif(index, a1, a2, a3) { - var sp = stackSave(); - try { - Module["dynCall_viif"](index, a1, a2, a3) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viii(index, a1, a2, a3) { - var sp = stackSave(); - try { - Module["dynCall_viii"](index, a1, a2, a3) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viiii(index, a1, a2, a3, a4) { - var sp = stackSave(); - try { - Module["dynCall_viiii"](index, a1, a2, a3, a4) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viiiii(index, a1, a2, a3, a4, a5) { - var sp = stackSave(); - try { - Module["dynCall_viiiii"](index, a1, a2, a3, a4, a5) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viiiiii(index, a1, a2, a3, a4, a5, a6) { - var sp = stackSave(); - try { - Module["dynCall_viiiiii"](index, a1, a2, a3, a4, a5, a6) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viiiiiii(index, a1, a2, a3, a4, a5, a6, a7) { - var sp = stackSave(); - try { - Module["dynCall_viiiiiii"](index, a1, a2, a3, a4, a5, a6, a7) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9) { - var sp = stackSave(); - try { - Module["dynCall_viiiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7, a8, a9) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viiiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { - var sp = stackSave(); - try { - Module["dynCall_viiiiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viiiiiiiiiiiiiii(index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) { - var sp = stackSave(); - try { - Module["dynCall_viiiiiiiiiiiiiii"](index, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viij(index, a1, a2, a3, a4) { - var sp = stackSave(); - try { - Module["dynCall_viij"](index, a1, a2, a3, a4) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_vij(index, a1, a2, a3) { - var sp = stackSave(); - try { - Module["dynCall_vij"](index, a1, a2, a3) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_viji(index, a1, a2, a3, a4) { - var sp = stackSave(); - try { - Module["dynCall_viji"](index, a1, a2, a3, a4) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -function invoke_vijii(index, a1, a2, a3, a4, a5) { - var sp = stackSave(); - try { - Module["dynCall_vijii"](index, a1, a2, a3, a4, a5) - } catch (e) { - stackRestore(sp); - if (typeof e !== "number" && e !== "longjmp") throw e; - Module["setThrew"](1, 0) - } -} - -Module.asmGlobalArg = {}; -Module.asmLibraryArg = { - "t": abort, - "db": enlargeMemory, - "Ua": getTotalMemory, - "S": setTempRet0, - "c": getTempRet0, - "Qa": abortOnCannotGrowMemory, - "Na": invoke_didd, - "N": invoke_diii, - "Ba": invoke_fif, - "x": invoke_fii, - "I": invoke_fiii, - "v": invoke_i, - "g": invoke_ii, - "O": invoke_iid, - "C": invoke_iif, - "i": invoke_iii, - "j": invoke_iiii, - "s": invoke_iiiii, - "ia": invoke_iiiiid, - "p": invoke_iiiiii, - "D": invoke_iiiiiii, - "V": invoke_iiiiiiii, - "ha": invoke_iiiiiiiii, - "B": invoke_iiiiiiiiiii, - "R": invoke_iiiiiiiiiiii, - "L": invoke_iiiiiiiiiiiii, - "ja": invoke_iiiiij, - "cb": invoke_iij, - "bb": invoke_iijii, - "ab": invoke_ji, - "$a": invoke_jii, - "_a": invoke_jiiii, - "o": invoke_v, - "l": invoke_vi, - "f": invoke_vii, - "Ta": invoke_viif, - "k": invoke_viii, - "r": invoke_viiii, - "w": invoke_viiiii, - "H": invoke_viiiiii, - "A": invoke_viiiiiii, - "Sa": invoke_viiiiiiiii, - "K": invoke_viiiiiiiiii, - "Q": invoke_viiiiiiiiiiiiiii, - "Za": invoke_viij, - "Ya": invoke_vij, - "Xa": invoke_viji, - "Wa": invoke_vijii, - "Ra": ___buildEnvironment, - "m": ___cxa_allocate_exception, - "u": ___cxa_begin_catch, - "y": ___cxa_end_catch, - "d": ___cxa_find_matching_catch_2, - "h": ___cxa_find_matching_catch_3, - "n": ___cxa_free_exception, - "ga": ___cxa_rethrow, - "q": ___cxa_throw, - "Pa": ___cxa_uncaught_exception, - "fa": ___lock, - "Oa": ___map_file, - "e": ___resumeException, - "ea": ___setErrNo, - "Ma": ___syscall140, - "La": ___syscall145, - "da": ___syscall146, - "Ka": ___syscall192, - "Ja": ___syscall195, - "Ia": ___syscall197, - "J": ___syscall221, - "Ha": ___syscall3, - "ca": ___syscall5, - "ba": ___syscall54, - "U": ___syscall6, - "Ga": ___syscall91, - "M": ___unlock, - "Fa": __embind_register_bool, - "Ea": __embind_register_class, - "Da": __embind_register_class_constructor, - "T": __embind_register_class_function, - "Ca": __embind_register_emval, - "aa": __embind_register_float, - "E": __embind_register_integer, - "z": __embind_register_memory_view, - "$": __embind_register_std_string, - "Aa": __embind_register_std_wstring, - "za": __embind_register_void, - "_": _abort, - "ya": _clock_gettime, - "xa": _emscripten_asm_const_iiiii, - "wa": _emscripten_memcpy_big, - "va": _exit, - "P": _getenv, - "Va": _llvm_bswap_i64, - "Z": _llvm_eh_typeid_for, - "ua": _llvm_log10_f64, - "G": _llvm_stackrestore, - "F": _llvm_stacksave, - "ta": _localtime, - "sa": _nanosleep, - "ra": _pthread_cond_destroy, - "qa": _pthread_cond_signal, - "Y": _pthread_cond_wait, - "pa": _pthread_create, - "oa": _pthread_getspecific, - "na": _pthread_join, - "X": _pthread_key_create, - "ma": _pthread_mutex_destroy, - "la": _pthread_once, - "W": _pthread_setspecific, - "ka": _strftime_l, - "a": DYNAMICTOP_PTR, - "b": STACKTOP -}; -var asm = Module["asm"](Module.asmGlobalArg, Module.asmLibraryArg, buffer); -Module["asm"] = asm; -var __GLOBAL__I_000101 = Module["__GLOBAL__I_000101"] = (function () { - return Module["asm"]["eb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_bind_cpp = Module["__GLOBAL__sub_I_bind_cpp"] = (function () { - return Module["asm"]["fb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_bindings_cc = Module["__GLOBAL__sub_I_bindings_cc"] = (function () { - return Module["asm"]["gb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_bitboard_cc = Module["__GLOBAL__sub_I_bitboard_cc"] = (function () { - return Module["asm"]["hb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_board_cc = Module["__GLOBAL__sub_I_board_cc"] = (function () { - return Module["asm"]["ib"].apply(null, arguments) -}); -var __GLOBAL__sub_I_commandline_cc = Module["__GLOBAL__sub_I_commandline_cc"] = (function () { - return Module["asm"]["jb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_configfile_cc = Module["__GLOBAL__sub_I_configfile_cc"] = (function () { - return Module["asm"]["kb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_iostream_cpp = Module["__GLOBAL__sub_I_iostream_cpp"] = (function () { - return Module["asm"]["lb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_network_blas_cc = Module["__GLOBAL__sub_I_network_blas_cc"] = (function () { - return Module["asm"]["mb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_network_check_cc = Module["__GLOBAL__sub_I_network_check_cc"] = (function () { - return Module["asm"]["nb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_network_mux_cc = Module["__GLOBAL__sub_I_network_mux_cc"] = (function () { - return Module["asm"]["ob"].apply(null, arguments) -}); -var __GLOBAL__sub_I_network_random_cc = Module["__GLOBAL__sub_I_network_random_cc"] = (function () { - return Module["asm"]["pb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_network_tsjs_cc = Module["__GLOBAL__sub_I_network_tsjs_cc"] = (function () { - return Module["asm"]["qb"].apply(null, arguments) -}); -var __GLOBAL__sub_I_uciloop_cc = Module["__GLOBAL__sub_I_uciloop_cc"] = (function () { - return Module["asm"]["rb"].apply(null, arguments) -}); -var __ZSt18uncaught_exceptionv = Module["__ZSt18uncaught_exceptionv"] = (function () { - return Module["asm"]["sb"].apply(null, arguments) -}); -var ___cxa_can_catch = Module["___cxa_can_catch"] = (function () { - return Module["asm"]["tb"].apply(null, arguments) -}); -var ___cxa_is_pointer_type = Module["___cxa_is_pointer_type"] = (function () { - return Module["asm"]["ub"].apply(null, arguments) -}); -var ___emscripten_environ_constructor = Module["___emscripten_environ_constructor"] = (function () { - return Module["asm"]["vb"].apply(null, arguments) -}); -var ___errno_location = Module["___errno_location"] = (function () { - return Module["asm"]["wb"].apply(null, arguments) -}); -var ___getTypeName = Module["___getTypeName"] = (function () { - return Module["asm"]["xb"].apply(null, arguments) -}); -var __get_daylight = Module["__get_daylight"] = (function () { - return Module["asm"]["yb"].apply(null, arguments) -}); -var __get_timezone = Module["__get_timezone"] = (function () { - return Module["asm"]["zb"].apply(null, arguments) -}); -var __get_tzname = Module["__get_tzname"] = (function () { - return Module["asm"]["Ab"].apply(null, arguments) -}); -var _emscripten_replace_memory = Module["_emscripten_replace_memory"] = (function () { - return Module["asm"]["_emscripten_replace_memory"].apply(null, arguments) -}); -var _free = Module["_free"] = (function () { - return Module["asm"]["Bb"].apply(null, arguments) -}); -var _llvm_bswap_i32 = Module["_llvm_bswap_i32"] = (function () { - return Module["asm"]["Cb"].apply(null, arguments) -}); -var _malloc = Module["_malloc"] = (function () { - return Module["asm"]["Db"].apply(null, arguments) -}); -var _memalign = Module["_memalign"] = (function () { - return Module["asm"]["Eb"].apply(null, arguments) -}); -var _memset = Module["_memset"] = (function () { - return Module["asm"]["Fb"].apply(null, arguments) -}); -var setThrew = Module["setThrew"] = (function () { - return Module["asm"]["wc"].apply(null, arguments) -}); -var stackAlloc = Module["stackAlloc"] = (function () { - return Module["asm"]["xc"].apply(null, arguments) -}); -var stackRestore = Module["stackRestore"] = (function () { - return Module["asm"]["yc"].apply(null, arguments) -}); -var stackSave = Module["stackSave"] = (function () { - return Module["asm"]["zc"].apply(null, arguments) -}); -var dynCall_didd = Module["dynCall_didd"] = (function () { - return Module["asm"]["Gb"].apply(null, arguments) -}); -var dynCall_diii = Module["dynCall_diii"] = (function () { - return Module["asm"]["Hb"].apply(null, arguments) -}); -var dynCall_fif = Module["dynCall_fif"] = (function () { - return Module["asm"]["Ib"].apply(null, arguments) -}); -var dynCall_fii = Module["dynCall_fii"] = (function () { - return Module["asm"]["Jb"].apply(null, arguments) -}); -var dynCall_fiii = Module["dynCall_fiii"] = (function () { - return Module["asm"]["Kb"].apply(null, arguments) -}); -var dynCall_i = Module["dynCall_i"] = (function () { - return Module["asm"]["Lb"].apply(null, arguments) -}); -var dynCall_ii = Module["dynCall_ii"] = (function () { - return Module["asm"]["Mb"].apply(null, arguments) -}); -var dynCall_iid = Module["dynCall_iid"] = (function () { - return Module["asm"]["Nb"].apply(null, arguments) -}); -var dynCall_iif = Module["dynCall_iif"] = (function () { - return Module["asm"]["Ob"].apply(null, arguments) -}); -var dynCall_iii = Module["dynCall_iii"] = (function () { - return Module["asm"]["Pb"].apply(null, arguments) -}); -var dynCall_iiii = Module["dynCall_iiii"] = (function () { - return Module["asm"]["Qb"].apply(null, arguments) -}); -var dynCall_iiiii = Module["dynCall_iiiii"] = (function () { - return Module["asm"]["Rb"].apply(null, arguments) -}); -var dynCall_iiiiid = Module["dynCall_iiiiid"] = (function () { - return Module["asm"]["Sb"].apply(null, arguments) -}); -var dynCall_iiiiii = Module["dynCall_iiiiii"] = (function () { - return Module["asm"]["Tb"].apply(null, arguments) -}); -var dynCall_iiiiiid = Module["dynCall_iiiiiid"] = (function () { - return Module["asm"]["Ub"].apply(null, arguments) -}); -var dynCall_iiiiiii = Module["dynCall_iiiiiii"] = (function () { - return Module["asm"]["Vb"].apply(null, arguments) -}); -var dynCall_iiiiiiii = Module["dynCall_iiiiiiii"] = (function () { - return Module["asm"]["Wb"].apply(null, arguments) -}); -var dynCall_iiiiiiiii = Module["dynCall_iiiiiiiii"] = (function () { - return Module["asm"]["Xb"].apply(null, arguments) -}); -var dynCall_iiiiiiiiiii = Module["dynCall_iiiiiiiiiii"] = (function () { - return Module["asm"]["Yb"].apply(null, arguments) -}); -var dynCall_iiiiiiiiiiii = Module["dynCall_iiiiiiiiiiii"] = (function () { - return Module["asm"]["Zb"].apply(null, arguments) -}); -var dynCall_iiiiiiiiiiiii = Module["dynCall_iiiiiiiiiiiii"] = (function () { - return Module["asm"]["_b"].apply(null, arguments) -}); -var dynCall_iiiiij = Module["dynCall_iiiiij"] = (function () { - return Module["asm"]["$b"].apply(null, arguments) -}); -var dynCall_iij = Module["dynCall_iij"] = (function () { - return Module["asm"]["ac"].apply(null, arguments) -}); -var dynCall_iijii = Module["dynCall_iijii"] = (function () { - return Module["asm"]["bc"].apply(null, arguments) -}); -var dynCall_ji = Module["dynCall_ji"] = (function () { - return Module["asm"]["cc"].apply(null, arguments) -}); -var dynCall_jii = Module["dynCall_jii"] = (function () { - return Module["asm"]["dc"].apply(null, arguments) -}); -var dynCall_jiiii = Module["dynCall_jiiii"] = (function () { - return Module["asm"]["ec"].apply(null, arguments) -}); -var dynCall_v = Module["dynCall_v"] = (function () { - return Module["asm"]["fc"].apply(null, arguments) -}); -var dynCall_vi = Module["dynCall_vi"] = (function () { - return Module["asm"]["gc"].apply(null, arguments) -}); -var dynCall_vii = Module["dynCall_vii"] = (function () { - return Module["asm"]["hc"].apply(null, arguments) -}); -var dynCall_viif = Module["dynCall_viif"] = (function () { - return Module["asm"]["ic"].apply(null, arguments) -}); -var dynCall_viii = Module["dynCall_viii"] = (function () { - return Module["asm"]["jc"].apply(null, arguments) -}); -var dynCall_viiii = Module["dynCall_viiii"] = (function () { - return Module["asm"]["kc"].apply(null, arguments) -}); -var dynCall_viiiii = Module["dynCall_viiiii"] = (function () { - return Module["asm"]["lc"].apply(null, arguments) -}); -var dynCall_viiiiii = Module["dynCall_viiiiii"] = (function () { - return Module["asm"]["mc"].apply(null, arguments) -}); -var dynCall_viiiiiii = Module["dynCall_viiiiiii"] = (function () { - return Module["asm"]["nc"].apply(null, arguments) -}); -var dynCall_viiiiiiiii = Module["dynCall_viiiiiiiii"] = (function () { - return Module["asm"]["oc"].apply(null, arguments) -}); -var dynCall_viiiiiiiiii = Module["dynCall_viiiiiiiiii"] = (function () { - return Module["asm"]["pc"].apply(null, arguments) -}); -var dynCall_viiiiiiiiiiiiiii = Module["dynCall_viiiiiiiiiiiiiii"] = (function () { - return Module["asm"]["qc"].apply(null, arguments) -}); -var dynCall_viij = Module["dynCall_viij"] = (function () { - return Module["asm"]["rc"].apply(null, arguments) -}); -var dynCall_viijii = Module["dynCall_viijii"] = (function () { - return Module["asm"]["sc"].apply(null, arguments) -}); -var dynCall_vij = Module["dynCall_vij"] = (function () { - return Module["asm"]["tc"].apply(null, arguments) -}); -var dynCall_viji = Module["dynCall_viji"] = (function () { - return Module["asm"]["uc"].apply(null, arguments) -}); -var dynCall_vijii = Module["dynCall_vijii"] = (function () { - return Module["asm"]["vc"].apply(null, arguments) -}); -Module["asm"] = asm; - -function ExitStatus(status) { - this.name = "ExitStatus"; - this.message = "Program terminated with exit(" + status + ")"; - this.status = status -} - -ExitStatus.prototype = new Error; -ExitStatus.prototype.constructor = ExitStatus; -var initialStackTop; -dependenciesFulfilled = function runCaller() { - if (!Module["calledRun"]) run(); - if (!Module["calledRun"]) dependenciesFulfilled = runCaller -}; - -function run(args) { - args = args || Module["arguments"]; - if (runDependencies > 0) { - return - } - preRun(); - if (runDependencies > 0) return; - if (Module["calledRun"]) return; - - function doRun() { - if (Module["calledRun"]) return; - Module["calledRun"] = true; - if (ABORT) return; - ensureInitRuntime(); - preMain(); - if (Module["onRuntimeInitialized"]) Module["onRuntimeInitialized"](); - postRun() - } - - if (Module["setStatus"]) { - Module["setStatus"]("Running..."); - setTimeout((function () { - setTimeout((function () { - Module["setStatus"]("") - }), 1); - doRun() - }), 1) - } else { - doRun() - } -} - -Module["run"] = run; - -function exit(status, implicit) { - if (implicit && Module["noExitRuntime"] && status === 0) { - return - } - if (Module["noExitRuntime"]) { - } else { - ABORT = true; - EXITSTATUS = status; - STACKTOP = initialStackTop; - exitRuntime(); - if (Module["onExit"]) Module["onExit"](status) - } - Module["quit"](status, new ExitStatus(status)) -} - -function abort(what) { - if (Module["onAbort"]) { - Module["onAbort"](what) - } - if (what !== undefined) { - out(what); - err(what); - what = JSON.stringify(what) - } else { - what = "" - } - ABORT = true; - EXITSTATUS = 1; - throw "abort(" + what + "). Build with -s ASSERTIONS=1 for more info." -} - -Module["abort"] = abort; -if (Module["preInit"]) { - if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]]; - while (Module["preInit"].length > 0) { - Module["preInit"].pop()() - } -} -Module["noExitRuntime"] = true; -run() - - - diff --git a/lib/engine/lc0/lc0.wasm b/lib/engine/lc0/lc0.wasm deleted file mode 100644 index dd1084ac..00000000 Binary files a/lib/engine/lc0/lc0.wasm and /dev/null differ diff --git a/lib/engine/lc0/lib/pako.min.js b/lib/engine/lc0/lib/pako.min.js deleted file mode 100644 index 92405bd2..00000000 --- a/lib/engine/lc0/lib/pako.min.js +++ /dev/null @@ -1,3 +0,0 @@ -/* pako 1.0.3 nodeca/pako */ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.pako=t()}}(function(){return function t(e,a,i){function n(s,o){if(!a[s]){if(!e[s]){var l="function"==typeof require&&require;if(!o&&l)return l(s,!0);if(r)return r(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var d=a[s]={exports:{}};e[s][0].call(d.exports,function(t){var a=e[s][1][t];return n(a?a:t)},d,d.exports,t,e,a,i)}return a[s].exports}for(var r="function"==typeof require&&require,s=0;s0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new f,this.strm.avail_out=0;var a=o.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==b)throw new Error(d[a]);if(e.header&&o.deflateSetHeader(this.strm,e.header),e.dictionary){var n;if(n="string"==typeof e.dictionary?h.string2buf(e.dictionary):"[object ArrayBuffer]"===_.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=o.deflateSetDictionary(this.strm,n),a!==b)throw new Error(d[a]);this._dict_set=!0}}function n(t,e){var a=new i(e);if(a.push(t,!0),a.err)throw a.msg;return a.result}function r(t,e){return e=e||{},e.raw=!0,n(t,e)}function s(t,e){return e=e||{},e.gzip=!0,n(t,e)}var o=t("./zlib/deflate"),l=t("./utils/common"),h=t("./utils/strings"),d=t("./zlib/messages"),f=t("./zlib/zstream"),_=Object.prototype.toString,u=0,c=4,b=0,g=1,m=2,w=-1,p=0,v=8;i.prototype.push=function(t,e){var a,i,n=this.strm,r=this.options.chunkSize;if(this.ended)return!1;i=e===~~e?e:e===!0?c:u,"string"==typeof t?n.input=h.string2buf(t):"[object ArrayBuffer]"===_.call(t)?n.input=new Uint8Array(t):n.input=t,n.next_in=0,n.avail_in=n.input.length;do{if(0===n.avail_out&&(n.output=new l.Buf8(r),n.next_out=0,n.avail_out=r),a=o.deflate(n,i),a!==g&&a!==b)return this.onEnd(a),this.ended=!0,!1;0!==n.avail_out&&(0!==n.avail_in||i!==c&&i!==m)||("string"===this.options.to?this.onData(h.buf2binstring(l.shrinkBuf(n.output,n.next_out))):this.onData(l.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||0===n.avail_out)&&a!==g);return i===c?(a=o.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===b):i!==m||(this.onEnd(b),n.avail_out=0,!0)},i.prototype.onData=function(t){this.chunks.push(t)},i.prototype.onEnd=function(t){t===b&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=l.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},a.Deflate=i,a.deflate=n,a.deflateRaw=r,a.gzip=s},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(t,e,a){"use strict";function i(t){if(!(this instanceof i))return new i(t);this.options=o.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0===(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new f,this.strm.avail_out=0;var a=s.inflateInit2(this.strm,e.windowBits);if(a!==h.Z_OK)throw new Error(d[a]);this.header=new _,s.inflateGetHeader(this.strm,this.header)}function n(t,e){var a=new i(e);if(a.push(t,!0),a.err)throw a.msg;return a.result}function r(t,e){return e=e||{},e.raw=!0,n(t,e)}var s=t("./zlib/inflate"),o=t("./utils/common"),l=t("./utils/strings"),h=t("./zlib/constants"),d=t("./zlib/messages"),f=t("./zlib/zstream"),_=t("./zlib/gzheader"),u=Object.prototype.toString;i.prototype.push=function(t,e){var a,i,n,r,d,f,_=this.strm,c=this.options.chunkSize,b=this.options.dictionary,g=!1;if(this.ended)return!1;i=e===~~e?e:e===!0?h.Z_FINISH:h.Z_NO_FLUSH,"string"==typeof t?_.input=l.binstring2buf(t):"[object ArrayBuffer]"===u.call(t)?_.input=new Uint8Array(t):_.input=t,_.next_in=0,_.avail_in=_.input.length;do{if(0===_.avail_out&&(_.output=new o.Buf8(c),_.next_out=0,_.avail_out=c),a=s.inflate(_,h.Z_NO_FLUSH),a===h.Z_NEED_DICT&&b&&(f="string"==typeof b?l.string2buf(b):"[object ArrayBuffer]"===u.call(b)?new Uint8Array(b):b,a=s.inflateSetDictionary(this.strm,f)),a===h.Z_BUF_ERROR&&g===!0&&(a=h.Z_OK,g=!1),a!==h.Z_STREAM_END&&a!==h.Z_OK)return this.onEnd(a),this.ended=!0,!1;_.next_out&&(0!==_.avail_out&&a!==h.Z_STREAM_END&&(0!==_.avail_in||i!==h.Z_FINISH&&i!==h.Z_SYNC_FLUSH)||("string"===this.options.to?(n=l.utf8border(_.output,_.next_out),r=_.next_out-n,d=l.buf2string(_.output,n),_.next_out=r,_.avail_out=c-r,r&&o.arraySet(_.output,_.output,n,r,0),this.onData(d)):this.onData(o.shrinkBuf(_.output,_.next_out)))),0===_.avail_in&&0===_.avail_out&&(g=!0)}while((_.avail_in>0||0===_.avail_out)&&a!==h.Z_STREAM_END);return a===h.Z_STREAM_END&&(i=h.Z_FINISH),i===h.Z_FINISH?(a=s.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===h.Z_OK):i!==h.Z_SYNC_FLUSH||(this.onEnd(h.Z_OK),_.avail_out=0,!0)},i.prototype.onData=function(t){this.chunks.push(t)},i.prototype.onEnd=function(t){t===h.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},a.Inflate=i,a.inflate=n,a.inflateRaw=r,a.ungzip=n},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(t,e,a){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;a.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(var i in a)a.hasOwnProperty(i)&&(t[i]=a[i])}}return t},a.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,a,i,n){if(e.subarray&&t.subarray)return void t.set(e.subarray(a,a+i),n);for(var r=0;r=252?6:l>=248?5:l>=240?4:l>=224?3:l>=192?2:1;o[254]=o[254]=1,a.string2buf=function(t){var e,a,i,r,s,o=t.length,l=0;for(r=0;r>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},a.buf2binstring=function(t){return i(t,t.length)},a.binstring2buf=function(t){for(var e=new n.Buf8(t.length),a=0,i=e.length;a4)h[n++]=65533,a+=s-1;else{for(r&=2===s?31:3===s?15:7;s>1&&a1?h[n++]=65533:r<65536?h[n++]=r:(r-=65536,h[n++]=55296|r>>10&1023,h[n++]=56320|1023&r)}return i(h,n)},a.utf8border=function(t,e){var a;for(e=e||t.length,e>t.length&&(e=t.length),a=e-1;a>=0&&128===(192&t[a]);)a--;return a<0?e:0===a?e:a+o[t[a]]>e?a:e}},{"./common":3}],5:[function(t,e,a){"use strict";function i(t,e,a,i){for(var n=65535&t|0,r=t>>>16&65535|0,s=0;0!==a;){s=a>2e3?2e3:a,a-=s;do n=n+e[i++]|0,r=r+n|0;while(--s);n%=65521,r%=65521}return n|r<<16|0}e.exports=i},{}],6:[function(t,e,a){"use strict";e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],7:[function(t,e,a){"use strict";function i(){for(var t,e=[],a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e}function n(t,e,a,i){var n=r,s=i+a;t^=-1;for(var o=i;o>>8^n[255&(t^e[o])];return t^-1}var r=i();e.exports=n},{}],8:[function(t,e,a){"use strict";function i(t,e){return t.msg=D[e],e}function n(t){return(t<<1)-(t>4?9:0)}function r(t){for(var e=t.length;--e>=0;)t[e]=0}function s(t){var e=t.state,a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(R.arraySet(t.output,e.pending_buf,e.pending_out,a,t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))}function o(t,e){C._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,s(t.strm)}function l(t,e){t.pending_buf[t.pending++]=e}function h(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function d(t,e,a,i){var n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,R.arraySet(e,t.input,t.next_in,n,a),1===t.state.wrap?t.adler=N(t.adler,e,n,a):2===t.state.wrap&&(t.adler=O(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)}function f(t,e){var a,i,n=t.max_chain_length,r=t.strstart,s=t.prev_length,o=t.nice_match,l=t.strstart>t.w_size-ft?t.strstart-(t.w_size-ft):0,h=t.window,d=t.w_mask,f=t.prev,_=t.strstart+dt,u=h[r+s-1],c=h[r+s];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do if(a=e,h[a+s]===c&&h[a+s-1]===u&&h[a]===h[r]&&h[++a]===h[r+1]){r+=2,a++;do;while(h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&r<_);if(i=dt-(_-r),r=_-dt,i>s){if(t.match_start=e,s=i,i>=o)break;u=h[r+s-1],c=h[r+s]}}while((e=f[e&d])>l&&0!==--n);return s<=t.lookahead?s:t.lookahead}function _(t){var e,a,i,n,r,s=t.w_size;do{if(n=t.window_size-t.lookahead-t.strstart,t.strstart>=s+(s-ft)){R.arraySet(t.window,t.window,s,s,0),t.match_start-=s,t.strstart-=s,t.block_start-=s,a=t.hash_size,e=a;do i=t.head[--e],t.head[e]=i>=s?i-s:0;while(--a);a=s,e=a;do i=t.prev[--e],t.prev[e]=i>=s?i-s:0;while(--a);n+=s}if(0===t.strm.avail_in)break;if(a=d(t.strm,t.window,t.strstart+t.lookahead,n),t.lookahead+=a,t.lookahead+t.insert>=ht)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(_(t),0===t.lookahead&&e===I)return vt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+a;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,o(t,!1),0===t.strm.avail_out))return vt;if(t.strstart-t.block_start>=t.w_size-ft&&(o(t,!1),0===t.strm.avail_out))return vt}return t.insert=0,e===F?(o(t,!0),0===t.strm.avail_out?yt:xt):t.strstart>t.block_start&&(o(t,!1),0===t.strm.avail_out)?vt:vt}function c(t,e){for(var a,i;;){if(t.lookahead=ht&&(t.ins_h=(t.ins_h<=ht)if(i=C._tr_tally(t,t.strstart-t.match_start,t.match_length-ht),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ht){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=ht&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=ht-1)),t.prev_length>=ht&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-ht,i=C._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ht),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=n&&(t.ins_h=(t.ins_h<=ht&&t.strstart>0&&(n=t.strstart-1,i=s[n],i===s[++n]&&i===s[++n]&&i===s[++n])){r=t.strstart+dt;do;while(i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ht?(a=C._tr_tally(t,1,t.match_length-ht),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=C._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(o(t,!1),0===t.strm.avail_out))return vt}return t.insert=0,e===F?(o(t,!0),0===t.strm.avail_out?yt:xt):t.last_lit&&(o(t,!1),0===t.strm.avail_out)?vt:kt}function m(t,e){for(var a;;){if(0===t.lookahead&&(_(t),0===t.lookahead)){if(e===I)return vt;break}if(t.match_length=0,a=C._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(o(t,!1),0===t.strm.avail_out))return vt}return t.insert=0,e===F?(o(t,!0),0===t.strm.avail_out?yt:xt):t.last_lit&&(o(t,!1),0===t.strm.avail_out)?vt:kt}function w(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}function p(t){t.window_size=2*t.w_size,r(t.head),t.max_lazy_match=Z[t.level].max_lazy,t.good_match=Z[t.level].good_length,t.nice_match=Z[t.level].nice_length,t.max_chain_length=Z[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ht-1,t.match_available=0,t.ins_h=0}function v(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=V,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new R.Buf16(2*ot),this.dyn_dtree=new R.Buf16(2*(2*rt+1)),this.bl_tree=new R.Buf16(2*(2*st+1)),r(this.dyn_ltree),r(this.dyn_dtree),r(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new R.Buf16(lt+1),this.heap=new R.Buf16(2*nt+1),r(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new R.Buf16(2*nt+1),r(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function k(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=Q,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?ut:wt,t.adler=2===e.wrap?0:1,e.last_flush=I,C._tr_init(e),H):i(t,K)}function y(t){var e=k(t);return e===H&&p(t.state),e}function x(t,e){return t&&t.state?2!==t.state.wrap?K:(t.state.gzhead=e,H):K}function z(t,e,a,n,r,s){if(!t)return K;var o=1;if(e===Y&&(e=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>$||a!==V||n<8||n>15||e<0||e>9||s<0||s>W)return i(t,K);8===n&&(n=9);var l=new v;return t.state=l,l.strm=t,l.wrap=o,l.gzhead=null,l.w_bits=n,l.w_size=1<L||e<0)return t?i(t,K):K;if(o=t.state,!t.output||!t.input&&0!==t.avail_in||o.status===pt&&e!==F)return i(t,0===t.avail_out?P:K);if(o.strm=t,a=o.last_flush,o.last_flush=e,o.status===ut)if(2===o.wrap)t.adler=0,l(o,31),l(o,139),l(o,8),o.gzhead?(l(o,(o.gzhead.text?1:0)+(o.gzhead.hcrc?2:0)+(o.gzhead.extra?4:0)+(o.gzhead.name?8:0)+(o.gzhead.comment?16:0)),l(o,255&o.gzhead.time),l(o,o.gzhead.time>>8&255),l(o,o.gzhead.time>>16&255),l(o,o.gzhead.time>>24&255),l(o,9===o.level?2:o.strategy>=G||o.level<2?4:0),l(o,255&o.gzhead.os),o.gzhead.extra&&o.gzhead.extra.length&&(l(o,255&o.gzhead.extra.length),l(o,o.gzhead.extra.length>>8&255)),o.gzhead.hcrc&&(t.adler=O(t.adler,o.pending_buf,o.pending,0)),o.gzindex=0,o.status=ct):(l(o,0),l(o,0),l(o,0),l(o,0),l(o,0),l(o,9===o.level?2:o.strategy>=G||o.level<2?4:0),l(o,zt),o.status=wt);else{var _=V+(o.w_bits-8<<4)<<8,u=-1;u=o.strategy>=G||o.level<2?0:o.level<6?1:6===o.level?2:3,_|=u<<6,0!==o.strstart&&(_|=_t),_+=31-_%31,o.status=wt,h(o,_),0!==o.strstart&&(h(o,t.adler>>>16),h(o,65535&t.adler)),t.adler=1}if(o.status===ct)if(o.gzhead.extra){for(d=o.pending;o.gzindex<(65535&o.gzhead.extra.length)&&(o.pending!==o.pending_buf_size||(o.gzhead.hcrc&&o.pending>d&&(t.adler=O(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending!==o.pending_buf_size));)l(o,255&o.gzhead.extra[o.gzindex]),o.gzindex++;o.gzhead.hcrc&&o.pending>d&&(t.adler=O(t.adler,o.pending_buf,o.pending-d,d)),o.gzindex===o.gzhead.extra.length&&(o.gzindex=0,o.status=bt)}else o.status=bt;if(o.status===bt)if(o.gzhead.name){d=o.pending;do{if(o.pending===o.pending_buf_size&&(o.gzhead.hcrc&&o.pending>d&&(t.adler=O(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending===o.pending_buf_size)){f=1;break}f=o.gzindexd&&(t.adler=O(t.adler,o.pending_buf,o.pending-d,d)),0===f&&(o.gzindex=0,o.status=gt)}else o.status=gt;if(o.status===gt)if(o.gzhead.comment){d=o.pending;do{if(o.pending===o.pending_buf_size&&(o.gzhead.hcrc&&o.pending>d&&(t.adler=O(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending===o.pending_buf_size)){f=1;break}f=o.gzindexd&&(t.adler=O(t.adler,o.pending_buf,o.pending-d,d)),0===f&&(o.status=mt)}else o.status=mt;if(o.status===mt&&(o.gzhead.hcrc?(o.pending+2>o.pending_buf_size&&s(t),o.pending+2<=o.pending_buf_size&&(l(o,255&t.adler),l(o,t.adler>>8&255),t.adler=0,o.status=wt)):o.status=wt),0!==o.pending){if(s(t),0===t.avail_out)return o.last_flush=-1,H}else if(0===t.avail_in&&n(e)<=n(a)&&e!==F)return i(t,P);if(o.status===pt&&0!==t.avail_in)return i(t,P);if(0!==t.avail_in||0!==o.lookahead||e!==I&&o.status!==pt){var c=o.strategy===G?m(o,e):o.strategy===X?g(o,e):Z[o.level].func(o,e);if(c!==yt&&c!==xt||(o.status=pt),c===vt||c===yt)return 0===t.avail_out&&(o.last_flush=-1),H;if(c===kt&&(e===U?C._tr_align(o):e!==L&&(C._tr_stored_block(o,0,0,!1),e===T&&(r(o.head),0===o.lookahead&&(o.strstart=0,o.block_start=0,o.insert=0))),s(t),0===t.avail_out))return o.last_flush=-1,H}return e!==F?H:o.wrap<=0?j:(2===o.wrap?(l(o,255&t.adler),l(o,t.adler>>8&255),l(o,t.adler>>16&255),l(o,t.adler>>24&255),l(o,255&t.total_in),l(o,t.total_in>>8&255),l(o,t.total_in>>16&255),l(o,t.total_in>>24&255)):(h(o,t.adler>>>16),h(o,65535&t.adler)),s(t),o.wrap>0&&(o.wrap=-o.wrap),0!==o.pending?H:j)}function E(t){var e;return t&&t.state?(e=t.state.status,e!==ut&&e!==ct&&e!==bt&&e!==gt&&e!==mt&&e!==wt&&e!==pt?i(t,K):(t.state=null,e===wt?i(t,M):H)):K}function A(t,e){var a,i,n,s,o,l,h,d,f=e.length;if(!t||!t.state)return K;if(a=t.state,s=a.wrap,2===s||1===s&&a.status!==ut||a.lookahead)return K;for(1===s&&(t.adler=N(t.adler,e,f,0)),a.wrap=0,f>=a.w_size&&(0===s&&(r(a.head),a.strstart=0,a.block_start=0,a.insert=0),d=new R.Buf8(a.w_size),R.arraySet(d,e,f-a.w_size,a.w_size,0),e=d,f=a.w_size),o=t.avail_in,l=t.next_in,h=t.input,t.avail_in=f,t.next_in=0,t.input=e,_(a);a.lookahead>=ht;){i=a.strstart,n=a.lookahead-(ht-1);do a.ins_h=(a.ins_h<>>24,b>>>=y,g-=y,y=k>>>16&255,0===y)A[o++]=65535&k;else{if(!(16&y)){if(0===(64&y)){k=m[(65535&k)+(b&(1<>>=y,g-=y),g<15&&(b+=E[r++]<>>24,b>>>=y,g-=y,y=k>>>16&255,!(16&y)){if(0===(64&y)){k=w[(65535&k)+(b&(1<d){t.msg="invalid distance too far back",a.mode=i;break t}if(b>>>=y,g-=y,y=o-l,z>y){if(y=z-y,y>_&&a.sane){t.msg="invalid distance too far back",a.mode=i;break t}if(B=0,S=c,0===u){if(B+=f-y,y2;)A[o++]=S[B++],A[o++]=S[B++],A[o++]=S[B++],x-=3;x&&(A[o++]=S[B++],x>1&&(A[o++]=S[B++]))}else{B=o-z;do A[o++]=A[B++],A[o++]=A[B++],A[o++]=A[B++],x-=3;while(x>2);x&&(A[o++]=A[B++],x>1&&(A[o++]=A[B++]))}break}}break}}while(r>3,r-=x,g-=x<<3,b&=(1<>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new w.Buf16(320),this.work=new w.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function r(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=T,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new w.Buf32(bt),e.distcode=e.distdyn=new w.Buf32(gt),e.sane=1,e.back=-1,Z):N}function s(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,r(t)):N}function o(t,e){var a,i;return t&&t.state?(i=t.state,e<0?(a=0,e=-e):(a=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15)?N:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,s(t))):N}function l(t,e){var a,i;return t?(i=new n,t.state=i,i.window=null,a=o(t,e),a!==Z&&(t.state=null),a):N}function h(t){return l(t,wt)}function d(t){if(pt){var e;for(g=new w.Buf32(512),m=new w.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(y(z,t.lens,0,288,g,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;y(B,t.lens,0,32,m,0,t.work,{bits:5}),pt=!1}t.lencode=g,t.lenbits=9,t.distcode=m,t.distbits=5}function f(t,e,a,i){var n,r=t.state;return null===r.window&&(r.wsize=1<=r.wsize?(w.arraySet(r.window,e,a-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(n=r.wsize-r.wnext,n>i&&(n=i),w.arraySet(r.window,e,a-i,n,r.wnext),i-=n,i?(w.arraySet(r.window,e,a-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=n,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,a.check=v(a.check,Et,2,0),_=0,u=0,a.mode=F;break}if(a.flags=0,a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&_)<<8)+(_>>8))%31){t.msg="incorrect header check",a.mode=_t;break}if((15&_)!==U){t.msg="unknown compression method",a.mode=_t;break}if(_>>>=4,u-=4,yt=(15&_)+8,0===a.wbits)a.wbits=yt;else if(yt>a.wbits){t.msg="invalid window size",a.mode=_t;break}a.dmax=1<>8&1),512&a.flags&&(Et[0]=255&_,Et[1]=_>>>8&255,a.check=v(a.check,Et,2,0)),_=0,u=0,a.mode=L;case L:for(;u<32;){if(0===l)break t;l--,_+=n[s++]<>>8&255,Et[2]=_>>>16&255,Et[3]=_>>>24&255,a.check=v(a.check,Et,4,0)),_=0,u=0,a.mode=H;case H:for(;u<16;){if(0===l)break t;l--,_+=n[s++]<>8),512&a.flags&&(Et[0]=255&_,Et[1]=_>>>8&255,a.check=v(a.check,Et,2,0)),_=0,u=0,a.mode=j;case j:if(1024&a.flags){for(;u<16;){if(0===l)break t;l--,_+=n[s++]<>>8&255,a.check=v(a.check,Et,2,0)),_=0,u=0}else a.head&&(a.head.extra=null);a.mode=K;case K:if(1024&a.flags&&(g=a.length,g>l&&(g=l),g&&(a.head&&(yt=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Array(a.head.extra_len)),w.arraySet(a.head.extra,n,s,g,yt)),512&a.flags&&(a.check=v(a.check,n,g,s)),l-=g,s+=g,a.length-=g),a.length))break t;a.length=0,a.mode=M;case M:if(2048&a.flags){if(0===l)break t;g=0;do yt=n[s+g++],a.head&&yt&&a.length<65536&&(a.head.name+=String.fromCharCode(yt));while(yt&&g>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=X;break;case q:for(;u<32;){if(0===l)break t;l--,_+=n[s++]<>>=7&u,u-=7&u,a.mode=ht;break}for(;u<3;){if(0===l)break t;l--,_+=n[s++]<>>=1,u-=1,3&_){case 0:a.mode=J;break;case 1:if(d(a),a.mode=at,e===A){_>>>=2,u-=2;break t}break;case 2:a.mode=$;break;case 3:t.msg="invalid block type",a.mode=_t}_>>>=2,u-=2;break;case J:for(_>>>=7&u,u-=7&u;u<32;){if(0===l)break t;l--,_+=n[s++]<>>16^65535)){t.msg="invalid stored block lengths",a.mode=_t;break}if(a.length=65535&_,_=0,u=0,a.mode=Q,e===A)break t;case Q:a.mode=V;case V:if(g=a.length){if(g>l&&(g=l),g>h&&(g=h),0===g)break t;w.arraySet(r,n,s,g,o),l-=g,s+=g,h-=g,o+=g,a.length-=g;break}a.mode=X;break;case $:for(;u<14;){if(0===l)break t; -l--,_+=n[s++]<>>=5,u-=5,a.ndist=(31&_)+1,_>>>=5,u-=5,a.ncode=(15&_)+4,_>>>=4,u-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=_t;break}a.have=0,a.mode=tt;case tt:for(;a.have>>=3,u-=3}for(;a.have<19;)a.lens[At[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,zt={bits:a.lenbits},xt=y(x,a.lens,0,19,a.lencode,0,a.work,zt),a.lenbits=zt.bits,xt){t.msg="invalid code lengths set",a.mode=_t;break}a.have=0,a.mode=et;case et:for(;a.have>>24,mt=St>>>16&255,wt=65535&St,!(gt<=u);){if(0===l)break t;l--,_+=n[s++]<>>=gt,u-=gt,a.lens[a.have++]=wt;else{if(16===wt){for(Bt=gt+2;u>>=gt,u-=gt,0===a.have){t.msg="invalid bit length repeat",a.mode=_t;break}yt=a.lens[a.have-1],g=3+(3&_),_>>>=2,u-=2}else if(17===wt){for(Bt=gt+3;u>>=gt,u-=gt,yt=0,g=3+(7&_),_>>>=3,u-=3}else{for(Bt=gt+7;u>>=gt,u-=gt,yt=0,g=11+(127&_),_>>>=7,u-=7}if(a.have+g>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=_t;break}for(;g--;)a.lens[a.have++]=yt}}if(a.mode===_t)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=_t;break}if(a.lenbits=9,zt={bits:a.lenbits},xt=y(z,a.lens,0,a.nlen,a.lencode,0,a.work,zt),a.lenbits=zt.bits,xt){t.msg="invalid literal/lengths set",a.mode=_t;break}if(a.distbits=6,a.distcode=a.distdyn,zt={bits:a.distbits},xt=y(B,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,zt),a.distbits=zt.bits,xt){t.msg="invalid distances set",a.mode=_t;break}if(a.mode=at,e===A)break t;case at:a.mode=it;case it:if(l>=6&&h>=258){t.next_out=o,t.avail_out=h,t.next_in=s,t.avail_in=l,a.hold=_,a.bits=u,k(t,b),o=t.next_out,r=t.output,h=t.avail_out,s=t.next_in,n=t.input,l=t.avail_in,_=a.hold,u=a.bits,a.mode===X&&(a.back=-1);break}for(a.back=0;St=a.lencode[_&(1<>>24,mt=St>>>16&255,wt=65535&St,!(gt<=u);){if(0===l)break t;l--,_+=n[s++]<>pt)],gt=St>>>24,mt=St>>>16&255,wt=65535&St,!(pt+gt<=u);){if(0===l)break t;l--,_+=n[s++]<>>=pt,u-=pt,a.back+=pt}if(_>>>=gt,u-=gt,a.back+=gt,a.length=wt,0===mt){a.mode=lt;break}if(32&mt){a.back=-1,a.mode=X;break}if(64&mt){t.msg="invalid literal/length code",a.mode=_t;break}a.extra=15&mt,a.mode=nt;case nt:if(a.extra){for(Bt=a.extra;u>>=a.extra,u-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=rt;case rt:for(;St=a.distcode[_&(1<>>24,mt=St>>>16&255,wt=65535&St,!(gt<=u);){if(0===l)break t;l--,_+=n[s++]<>pt)],gt=St>>>24,mt=St>>>16&255,wt=65535&St,!(pt+gt<=u);){if(0===l)break t;l--,_+=n[s++]<>>=pt,u-=pt,a.back+=pt}if(_>>>=gt,u-=gt,a.back+=gt,64&mt){t.msg="invalid distance code",a.mode=_t;break}a.offset=wt,a.extra=15&mt,a.mode=st;case st:if(a.extra){for(Bt=a.extra;u>>=a.extra,u-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=_t;break}a.mode=ot;case ot:if(0===h)break t;if(g=b-h,a.offset>g){if(g=a.offset-g,g>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=_t;break}g>a.wnext?(g-=a.wnext,m=a.wsize-g):m=a.wnext-g,g>a.length&&(g=a.length),bt=a.window}else bt=r,m=o-a.offset,g=a.length;g>h&&(g=h),h-=g,a.length-=g;do r[o++]=bt[m++];while(--g);0===a.length&&(a.mode=it);break;case lt:if(0===h)break t;r[o++]=a.length,h--,a.mode=it;break;case ht:if(a.wrap){for(;u<32;){if(0===l)break t;l--,_|=n[s++]<=1&&0===j[N];N--);if(O>N&&(O=N),0===N)return b[g++]=20971520,b[g++]=20971520,w.bits=1,0;for(C=1;C0&&(t===o||1!==N))return-1;for(K[1]=0,Z=1;Zr||t===h&&T>s)return 1;for(var Y=0;;){Y++,B=Z-I,m[R]z?(S=M[P+m[R]],E=L[H+m[R]]):(S=96,E=0),p=1<>I)+v]=B<<24|S<<16|E|0;while(0!==v);for(p=1<>=1;if(0!==p?(F&=p-1,F+=p):F=0,R++,0===--j[Z]){if(Z===N)break;Z=e[a+m[R]]}if(Z>O&&(F&y)!==k){for(0===I&&(I=O),x+=C,D=Z-I,U=1<r||t===h&&T>s)return 1;k=F&y,b[k]=O<<24|D<<16|x-g|0}}return 0!==F&&(b[x+F]=Z-I<<24|64<<16|0),w.bits=O,0}},{"../utils/common":3}],13:[function(t,e,a){"use strict";e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],14:[function(t,e,a){"use strict";function i(t){for(var e=t.length;--e>=0;)t[e]=0}function n(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}function r(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function s(t){return t<256?lt[t]:lt[256+(t>>>7)]}function o(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function l(t,e,a){t.bi_valid>W-a?(t.bi_buf|=e<>W-t.bi_valid,t.bi_valid+=a-W):(t.bi_buf|=e<>>=1,a<<=1;while(--e>0);return a>>>1}function f(t){16===t.bi_valid?(o(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function _(t,e){var a,i,n,r,s,o,l=e.dyn_tree,h=e.max_code,d=e.stat_desc.static_tree,f=e.stat_desc.has_stree,_=e.stat_desc.extra_bits,u=e.stat_desc.extra_base,c=e.stat_desc.max_length,b=0;for(r=0;r<=X;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;ac&&(r=c,b++),l[2*i+1]=r,i>h||(t.bl_count[r]++,s=0,i>=u&&(s=_[i-u]),o=l[2*i],t.opt_len+=o*(r+s),f&&(t.static_len+=o*(d[2*i+1]+s)));if(0!==b){do{for(r=c-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[c]--,b-=2}while(b>0);for(r=c;0!==r;r--)for(i=t.bl_count[r];0!==i;)n=t.heap[--a],n>h||(l[2*n+1]!==r&&(t.opt_len+=(r-l[2*n+1])*l[2*n],l[2*n+1]=r),i--)}}function u(t,e,a){var i,n,r=new Array(X+1),s=0;for(i=1;i<=X;i++)r[i]=s=s+a[i-1]<<1;for(n=0;n<=e;n++){var o=t[2*n+1];0!==o&&(t[2*n]=d(r[o]++,o))}}function c(){var t,e,a,i,r,s=new Array(X+1);for(a=0,i=0;i>=7;i8?o(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function m(t,e,a,i){g(t),i&&(o(t,a),o(t,~a)),N.arraySet(t.pending_buf,t.window,e,a,t.pending),t.pending+=a}function w(t,e,a,i){var n=2*e,r=2*a;return t[n]>1;a>=1;a--)p(t,r,a);n=l;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],p(t,r,1),i=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=i,r[2*n]=r[2*a]+r[2*i],t.depth[n]=(t.depth[a]>=t.depth[i]?t.depth[a]:t.depth[i])+1,r[2*a+1]=r[2*i+1]=n,t.heap[1]=n++,p(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],_(t,e),u(r,h,t.bl_count)}function y(t,e,a){var i,n,r=-1,s=e[1],o=0,l=7,h=4;for(0===s&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=s,s=e[2*(i+1)+1],++o=3&&0===t.bl_tree[2*nt[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function B(t,e,a,i){var n;for(l(t,e-257,5),l(t,a-1,5),l(t,i-4,4),n=0;n>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return D;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return I;for(e=32;e0?(t.strm.data_type===U&&(t.strm.data_type=S(t)),k(t,t.l_desc),k(t,t.d_desc),s=z(t),n=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=n&&(n=r)):n=r=a+5,a+4<=n&&e!==-1?A(t,e,a,i):t.strategy===O||r===n?(l(t,(F<<1)+(i?1:0),3),v(t,st,ot)):(l(t,(L<<1)+(i?1:0),3),B(t,t.l_desc.max_code+1,t.d_desc.max_code+1,s+1),v(t,t.dyn_ltree,t.dyn_dtree)),b(t),i&&g(t)}function C(t,e,a){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(ht[a]+M+1)]++,t.dyn_dtree[2*s(e)]++),t.last_lit===t.lit_bufsize-1}var N=t("../utils/common"),O=4,D=0,I=1,U=2,T=0,F=1,L=2,H=3,j=258,K=29,M=256,P=M+1+K,Y=30,q=19,G=2*P+1,X=15,W=16,J=7,Q=256,V=16,$=17,tt=18,et=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],at=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],it=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],nt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],rt=512,st=new Array(2*(P+2));i(st);var ot=new Array(2*Y);i(ot);var lt=new Array(rt);i(lt);var ht=new Array(j-H+1);i(ht);var dt=new Array(K);i(dt);var ft=new Array(Y);i(ft);var _t,ut,ct,bt=!1;a._tr_init=E,a._tr_stored_block=A,a._tr_flush_block=R,a._tr_tally=C,a._tr_align=Z},{"../utils/common":3}],15:[function(t,e,a){"use strict";function i(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}e.exports=i},{}],"/":[function(t,e,a){"use strict";var i=t("./lib/utils/common").assign,n=t("./lib/deflate"),r=t("./lib/inflate"),s=t("./lib/zlib/constants"),o={};i(o,n,r,s),e.exports=o},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")}); diff --git a/lib/engine/lc0/lib/protobuf.min.js b/lib/engine/lc0/lib/protobuf.min.js deleted file mode 100644 index 9be32b62..00000000 --- a/lib/engine/lc0/lib/protobuf.min.js +++ /dev/null @@ -1,8 +0,0 @@ -/*! - * protobuf.js v6.8.8 (c) 2016, daniel wirtz - * compiled thu, 19 jul 2018 00:33:26 utc - * licensed under the bsd-3-clause license - * see: https://github.com/dcodeio/protobuf.js for details - */ -!function(tt){"use strict";var r,e,t,i;r={1:[function(t,i){i.exports=function(t,i){var n=Array(arguments.length-1),s=0,r=2,u=!0;for(;r>2],r=(3&f)<<4,o=1;break;case 1:s[u++]=h[r|f>>4],r=(15&f)<<2,o=2;break;case 2:s[u++]=h[r|f>>6],s[u++]=h[63&f],o=0}8191>4,r=o,s=2;break;case 2:i[n++]=(15&r)<<4|(60&o)>>2,r=o,s=3;break;case 3:i[n++]=(3&r)<<6|o,s=0}}if(1===s)throw Error(a);return n-e},r.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,i){function c(i,n){"string"==typeof i&&(n=i,i=tt);var f=[];function h(t){if("string"!=typeof t){var i=a();if(c.verbose&&console.log("codegen: "+i),i="return "+i,t){for(var n=Object.keys(t),r=Array(n.length+1),e=Array(n.length),s=0;s>>0,n,r);else if(i<11754943508222875e-54)t((e<<31|Math.round(i/1401298464324817e-60))>>>0,n,r);else{var s=Math.floor(Math.log(i)/Math.LN2);t((e<<31|s+127<<23|8388607&Math.round(i*Math.pow(2,-s)*8388608))>>>0,n,r)}}function i(t,i,n){var r=t(i,n),e=2*(r>>31)+1,s=r>>>23&255,u=8388607&r;return 255===s?u?NaN:e*(1/0):0===s?1401298464324817e-60*e*u:e*Math.pow(2,s-150)*(u+8388608)}o.writeFloatLE=t.bind(null,r),o.writeFloatBE=t.bind(null,e),o.readFloatLE=i.bind(null,s),o.readFloatBE=i.bind(null,u)}(),"undefined"!=typeof Float64Array?function(){var r=new Float64Array([-0]),e=new Uint8Array(r.buffer),t=128===e[7];function i(t,i,n){r[0]=t,i[n]=e[0],i[n+1]=e[1],i[n+2]=e[2],i[n+3]=e[3],i[n+4]=e[4],i[n+5]=e[5],i[n+6]=e[6],i[n+7]=e[7]}function n(t,i,n){r[0]=t,i[n]=e[7],i[n+1]=e[6],i[n+2]=e[5],i[n+3]=e[4],i[n+4]=e[3],i[n+5]=e[2],i[n+6]=e[1],i[n+7]=e[0]}function s(t,i){return e[0]=t[i],e[1]=t[i+1],e[2]=t[i+2],e[3]=t[i+3],e[4]=t[i+4],e[5]=t[i+5],e[6]=t[i+6],e[7]=t[i+7],r[0]}function u(t,i){return e[7]=t[i],e[6]=t[i+1],e[5]=t[i+2],e[4]=t[i+3],e[3]=t[i+4],e[2]=t[i+5],e[1]=t[i+6],e[0]=t[i+7],r[0]}o.writeDoubleLE=t?i:n,o.writeDoubleBE=t?n:i,o.readDoubleLE=t?s:u,o.readDoubleBE=t?u:s}():function(){function t(t,i,n,r,e,s){var u=r<0?1:0;if(u&&(r=-r),0===r)t(0,e,s+i),t(0<1/r?0:2147483648,e,s+n);else if(isNaN(r))t(0,e,s+i),t(2146959360,e,s+n);else if(17976931348623157e292>>0,e,s+n);else{var o;if(r<22250738585072014e-324)t((o=r/5e-324)>>>0,e,s+i),t((u<<31|o/4294967296)>>>0,e,s+n);else{var f=Math.floor(Math.log(r)/Math.LN2);1024===f&&(f=1023),t(4503599627370496*(o=r*Math.pow(2,-f))>>>0,e,s+i),t((u<<31|f+1023<<20|1048576*o&1048575)>>>0,e,s+n)}}}function i(t,i,n,r,e){var s=t(r,e+i),u=t(r,e+n),o=2*(u>>31)+1,f=u>>>20&2047,h=4294967296*(1048575&u)+s;return 2047===f?h?NaN:o*(1/0):0===f?5e-324*o*h:o*Math.pow(2,f-1075)*(h+4503599627370496)}o.writeDoubleLE=t.bind(null,r,0,4),o.writeDoubleBE=t.bind(null,e,4,0),o.readDoubleLE=i.bind(null,s,0,4),o.readDoubleBE=i.bind(null,u,4,0)}(),o}function r(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}function e(t,i,n){i[n]=t>>>24,i[n+1]=t>>>16&255,i[n+2]=t>>>8&255,i[n+3]=255&t}function s(t,i){return(t[i]|t[i+1]<<8|t[i+2]<<16|t[i+3]<<24)>>>0}function u(t,i){return(t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3])>>>0}i.exports=n(n)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,i,n){var r=n,s=r.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},e=r.normalize=function(t){var i=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=s(t),r="";n&&(r=i.shift()+"/");for(var e=0;e>>1,u=null,o=e;return function(t){if(t<1||s>10),s[u++]=56320+(1023&r)):s[u++]=(15&r)<<12|(63&t[i++])<<6|63&t[i++],8191>6|192:(55296==(64512&r)&&56320==(64512&(e=t.charCodeAt(u+1)))?(r=65536+((1023&r)<<10)+(1023&e),++u,i[n++]=r>>18|240,i[n++]=r>>12&63|128):i[n++]=r>>12|224,i[n++]=r>>6&63|128),i[n++]=63&r|128);return n-s}},{}],11:[function(t,i){i.exports=e;var n,r=/\/|\./;function e(t,i){r.test(t)||(t="google/protobuf/"+t+".proto",i={nested:{google:{nested:{protobuf:{nested:i}}}}}),e[t]=i}e("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),e("duration",{Duration:n={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),e("timestamp",{Timestamp:n}),e("empty",{Empty:{fields:{}}}),e("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),e("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),e("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),e.get=function(t){return e[t]||null}},{}],12:[function(t,i,n){var r=n,l=t(15),v=t(37);function u(t,i,n,r){if(i.resolvedType)if(i.resolvedType instanceof l){t("switch(d%s){",r);for(var e=i.resolvedType.values,s=Object.keys(e),u=0;u>>0",r,r);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",r,r);break;case"uint64":o=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",r,r,o)('else if(typeof d%s==="string")',r)("m%s=parseInt(d%s,10)",r,r)('else if(typeof d%s==="number")',r)("m%s=d%s",r,r)('else if(typeof d%s==="object")',r)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",r,r,r,o?"true":"");break;case"bytes":t('if(typeof d%s==="string")',r)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",r,r,r)("else if(d%s.length)",r)("m%s=d%s",r,r);break;case"string":t("m%s=String(d%s)",r,r);break;case"bool":t("m%s=Boolean(d%s)",r,r)}}return t}function d(t,i,n,r){if(i.resolvedType)i.resolvedType instanceof l?t("d%s=o.enums===String?types[%i].values[m%s]:m%s",r,n,r,r):t("d%s=types[%i].toObject(m%s,o)",r,n,r);else{var e=!1;switch(i.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",r,r,r,r);break;case"uint64":e=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',r)("d%s=o.longs===String?String(m%s):m%s",r,r,r)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",r,r,r,r,e?"true":"",r);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",r,r,r,r,r);break;default:t("d%s=m%s",r,r)}}return t}r.fromObject=function(t){var i=t.fieldsArray,n=v.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!i.length)return n("return new this.ctor");n("var m=new this.ctor");for(var r=0;r>>3){");for(var n=0;n>>0,8|a.mapKey[s.keyType],s.keyType),f===tt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,i):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|f,o,i),n("}")("}")):s.repeated?(n("if(%s!=null&&%s.length){",i,i),s.packed&&a.packed[o]!==tt?n("w.uint32(%i).fork()",(s.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",o,i)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",i),f===tt?l(n,s,u,i+"[i]"):n("w.uint32(%i).%s(%s[i])",(s.id<<3|f)>>>0,o,i)),n("}")):(s.optional&&n("if(%s!=null&&m.hasOwnProperty(%j))",i,s.name),f===tt?l(n,s,u,i):n("w.uint32(%i).%s(%s)",(s.id<<3|f)>>>0,o,i))}return n("return w")};var h=t(15),a=t(36),c=t(37);function l(t,i,n,r){return i.resolvedType.group?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(i.id<<3|3)>>>0,(i.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(i.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,i){i.exports=e;var o=t(24);((e.prototype=Object.create(o.prototype)).constructor=e).className="Enum";var n=t(23),r=t(37);function e(t,i,n,r,e){if(o.call(this,t,n),i&&"object"!=typeof i)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=r,this.comments=e||{},this.reserved=tt,i)for(var s=Object.keys(i),u=0;u=i)return!0;return!1},h.isReservedName=function(t,i){if(t)for(var n=0;n");var r=h();if(!G.test(r))throw b(r,"name");l("=");var e=new U(y(r),k(h()),i,n);S(e,function(t){if("option"!==t)throw b(t);N(e,t),l(";")},function(){$(e)}),t.add(e)}(n);break;case"required":case"optional":case"repeated":T(n,t);break;case"oneof":!function(t,i){if(!G.test(i=h()))throw b(i,"name");var n=new _(y(i));S(n,function(t){"option"===t?(N(n,t),l(";")):(a(t),T(n,"optional"))}),t.add(n)}(n,t);break;case"extensions":j(n.extensions||(n.extensions=[]));break;case"reserved":j(n.reserved||(n.reserved=[]),!0);break;default:if(!p||!K.test(t))throw b(t);a(t),T(n,"optional")}}),t.add(n)}(t,i),!0;case"enum":return function(t,i){if(!G.test(i=h()))throw b(i,"name");var n=new q(i);S(n,function(t){switch(t){case"option":N(n,t),l(";");break;case"reserved":j(n.reserved||(n.reserved=[]),!0);break;default:!function(t,i){if(!G.test(i))throw b(i,"name");l("=");var n=k(h(),!0),r={};S(r,function(t){if("option"!==t)throw b(t);N(r,t),l(";")},function(){$(r)}),t.add(i,n,r.comment)}(n,t)}}),t.add(n)}(t,i),!0;case"service":return function(t,i){if(!G.test(i=h()))throw b(i,"service name");var n=new R(i);S(n,function(t){if(!x(n,t)){if("rpc"!==t)throw b(t);!function(t,i){var n=i;if(!G.test(i=h()))throw b(i,"name");var r,e,s,u,o=i;l("("),l("stream",!0)&&(e=!0);if(!K.test(i=h()))throw b(i);r=i,l(")"),l("returns"),l("("),l("stream",!0)&&(u=!0);if(!K.test(i=h()))throw b(i);s=i,l(")");var f=new z(o,n,r,s,e,u);S(f,function(t){if("option"!==t)throw b(t);N(f,t),l(";")}),t.add(f)}(n,t)}}),t.add(n)}(t,i),!0;case"extend":return function(i,t){if(!K.test(t=h()))throw b(t,"reference");var n=t;S(null,function(t){switch(t){case"required":case"repeated":case"optional":T(i,t,n);break;default:if(!p||!K.test(t))throw b(t);a(t),T(i,"optional",n)}})}(t,i),!0}return!1}function S(t,i,n){var r=f.line;if(t&&(t.comment=v(),t.filename=Y.filename),l("{",!0)){for(var e;"}"!==(e=h());)i(e);l(";",!0)}else n&&n(),l(";"),t&&"string"!=typeof t.comment&&(t.comment=v(r))}function T(t,i,n){var r=h();if("group"!==r){if(!K.test(r))throw b(r,"type");var e=h();if(!G.test(e))throw b(e,"name");e=y(e),l("=");var s=new L(e,k(h()),r,i,n);S(s,function(t){if("option"!==t)throw b(t);N(s,t),l(";")},function(){$(s)}),t.add(s),p||!s.repeated||Z.packed[r]===tt&&Z.basic[r]!==tt||s.setOption("packed",!1,!0)}else!function(t,i){var n=h();if(!G.test(n))throw b(n,"name");var r=B.lcFirst(n);n===r&&(n=B.ucFirst(n));l("=");var e=k(h()),s=new F(n);s.group=!0;var u=new L(r,e,n,i);u.filename=Y.filename,S(s,function(t){switch(t){case"option":N(s,t),l(";");break;case"required":case"optional":case"repeated":T(s,t);break;default:throw b(t)}}),t.add(s).add(u)}(t,i)}function N(t,i){var n=l("(",!0);if(!K.test(i=h()))throw b(i,"name");var r=i;n&&(l(")"),r="("+r+")",i=c(),Q.test(i)&&(r+=i,h())),l("="),function t(i,n){if(l("{",!0))do{if(!G.test(o=h()))throw b(o,"name");"{"===c()?t(i,n+"."+o):(l(":"),"{"===c()?t(i,n+"."+o):V(i,n+"."+o,g(!0))),l(",",!0)}while(!l("}",!0));else V(i,n,g(!0))}(t,r)}function V(t,i,n){t.setOption&&t.setOption(i,n)}function $(t){if(l("[",!0)){for(;N(t,"option"),l(",",!0););l("]")}return t}for(;null!==(o=h());)switch(o){case"package":if(!d)throw b(o);E();break;case"import":if(!d)throw b(o);O();break;case"syntax":if(!d)throw b(o);A();break;case"option":if(!d)throw b(o);N(w,o),l(";");break;default:if(x(w,o)){d=!1;continue}throw b(o)}return Y.filename=null,{package:r,imports:e,weakImports:s,syntax:u,root:i}}},{15:15,16:16,20:20,22:22,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(t,i){i.exports=o;var n,r=t(39),e=r.LongBits,s=r.utf8;function u(t,i){return RangeError("index out of range: "+t.pos+" + "+(i||1)+" > "+t.len)}function o(t){this.buf=t,this.pos=0,this.len=t.length}var f,h="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new o(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new o(t);throw Error("illegal buffer")};function a(){var t=new e(0,0),i=0;if(!(4=this.len)throw u(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(i=0,4>>0,this.buf[this.pos++]<128)return t}else for(;i<5;++i){if(this.pos>=this.len)throw u(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*i+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function c(t,i){return(t[i-4]|t[i-3]<<8|t[i-2]<<16|t[i-1]<<24)>>>0}function l(){if(this.pos+8>this.len)throw u(this,8);return new e(c(this.buf,this.pos+=4),c(this.buf,this.pos+=4))}o.create=r.Buffer?function(t){return(o.create=function(t){return r.Buffer.isBuffer(t)?new n(t):h(t)})(t)}:h,o.prototype.c=r.Array.prototype.subarray||r.Array.prototype.slice,o.prototype.uint32=(f=4294967295,function(){if(f=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return f;if(f=(f|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return f;if(f=(f|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return f;if(f=(f|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return f;if(f=(f|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return f;if((this.pos+=5)>this.len)throw this.pos=this.len,u(this,10);return f}),o.prototype.int32=function(){return 0|this.uint32()},o.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},o.prototype.bool=function(){return 0!==this.uint32()},o.prototype.fixed32=function(){if(this.pos+4>this.len)throw u(this,4);return c(this.buf,this.pos+=4)},o.prototype.sfixed32=function(){if(this.pos+4>this.len)throw u(this,4);return 0|c(this.buf,this.pos+=4)},o.prototype.float=function(){if(this.pos+4>this.len)throw u(this,4);var t=r.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},o.prototype.double=function(){if(this.pos+8>this.len)throw u(this,4);var t=r.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},o.prototype.bytes=function(){var t=this.uint32(),i=this.pos,n=this.pos+t;if(n>this.len)throw u(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(i,n):i===n?new this.buf.constructor(0):this.c.call(this.buf,i,n)},o.prototype.string=function(){var t=this.bytes();return s.read(t,0,t.length)},o.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw u(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw u(this)}while(128&this.buf[this.pos++]);return this},o.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},o.o=function(t){n=t;var i=r.Long?"toLong":"toNumber";r.merge(o.prototype,{int64:function(){return a.call(this)[i](!1)},uint64:function(){return a.call(this)[i](!0)},sint64:function(){return a.call(this).zzDecode()[i](!1)},fixed64:function(){return l.call(this)[i](!0)},sfixed64:function(){return l.call(this)[i](!1)}})}},{39:39}],28:[function(t,i){i.exports=e;var n=t(27);(e.prototype=Object.create(n.prototype)).constructor=e;var r=t(39);function e(t){n.call(this,t)}r.Buffer&&(e.prototype.c=r.Buffer.prototype.slice),e.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len))}},{27:27,39:39}],29:[function(t,i){i.exports=n;var r=t(23);((n.prototype=Object.create(r.prototype)).constructor=n).className="Root";var e,v,d,s=t(16),u=t(15),o=t(25),p=t(37);function n(t){r.call(this,"",t),this.deferred=[],this.files=[]}function w(){}n.fromJSON=function(t,i){return i||(i=new n),t.options&&i.setOptions(t.options),i.addJSON(t.nested)},n.prototype.resolvePath=p.path.resolve,n.prototype.load=function t(i,s,u){"function"==typeof s&&(u=s,s=tt);var o=this;if(!u)return p.asPromise(t,o,i,s);var f=u===w;function h(t,i){if(u){var n=u;if(u=null,f)throw t;n(t,i)}}function a(t,i){try{if(p.isString(i)&&"{"===i.charAt(0)&&(i=JSON.parse(i)),p.isString(i)){v.filename=t;var n,r=v(i,o,s),e=0;if(r.imports)for(;e]/g,O=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,A=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,x=/^ *[*/]+ */,S=/^\s*\*?\/*/,T=/\n/g,N=/\s/,n=/\\(.?)/g,r={0:"\0",r:"\r",n:"\n",t:"\t"};function V(t){return t.replace(n,function(t,i){switch(i){case"\\":case"":return i;default:return r[i]||""}})}function e(o,f){o=o.toString();var h=0,a=o.length,c=1,u=null,l=null,v=0,d=!1,p=[],w=null;function y(t){return Error("illegal "+t+" (line "+c+")")}function b(t){return o.charAt(t)}function m(t,i){u=o.charAt(t++),v=c,d=!1;var n,r=t-(f?2:3);do{if(--r<0||"\n"===(n=o.charAt(r))){d=!0;break}}while(" "===n||"\t"===n);for(var e=o.substring(t,i).split(T),s=0;s>>0,this.hi=i>>>0}var s=e.zero=new e(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var r=e.zeroHash="\0\0\0\0\0\0\0\0";e.fromNumber=function(t){if(0===t)return s;var i=t<0;i&&(t=-t);var n=t>>>0,r=(t-n)/4294967296>>>0;return i&&(r=~r>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++r&&(r=0))),new e(n,r)},e.from=function(t){if("number"==typeof t)return e.fromNumber(t);if(n.isString(t)){if(!n.Long)return e.fromNumber(parseInt(t,10));t=n.Long.fromString(t)}return t.low||t.high?new e(t.low>>>0,t.high>>>0):s},e.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var i=1+~this.lo>>>0,n=~this.hi>>>0;return i||(n=n+1>>>0),-(i+4294967296*n)}return this.lo+4294967296*this.hi},e.prototype.toLong=function(t){return n.Long?new n.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}};var u=String.prototype.charCodeAt;e.fromHash=function(t){return t===r?s:new e((u.call(t,0)|u.call(t,1)<<8|u.call(t,2)<<16|u.call(t,3)<<24)>>>0,(u.call(t,4)|u.call(t,5)<<8|u.call(t,6)<<16|u.call(t,7)<<24)>>>0)},e.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},e.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},e.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},e.prototype.length=function(){var t=this.lo,i=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===i?t<16384?t<128?1:2:t<2097152?3:4:i<16384?i<128?5:6:i<2097152?7:8:n<128?9:10}},{39:39}],39:[function(t,i,n){var r=n;function e(t,i,n){for(var r=Object.keys(i),e=0;e>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127>>7;i[n++]=t.lo}function d(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}a.create=r.Buffer?function(){return(a.create=function(){return new n})()}:function(){return new a},a.alloc=function(t){return new r.Array(t)},r.Array!==Array&&(a.alloc=r.pool(a.alloc,r.Array.prototype.subarray)),a.prototype.g=function(t,i,n){return this.tail=this.tail.next=new o(t,i,n),this.len+=i,this},(l.prototype=Object.create(o.prototype)).fn=function(t,i,n){for(;127>>=7;i[n]=t},a.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new l((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},a.prototype.int32=function(t){return t<0?this.g(v,10,e.fromNumber(t)):this.uint32(t)},a.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},a.prototype.int64=a.prototype.uint64=function(t){var i=e.from(t);return this.g(v,i.length(),i)},a.prototype.sint64=function(t){var i=e.from(t).zzEncode();return this.g(v,i.length(),i)},a.prototype.bool=function(t){return this.g(c,1,t?1:0)},a.prototype.sfixed32=a.prototype.fixed32=function(t){return this.g(d,4,t>>>0)},a.prototype.sfixed64=a.prototype.fixed64=function(t){var i=e.from(t);return this.g(d,4,i.lo).g(d,4,i.hi)},a.prototype.float=function(t){return this.g(r.float.writeFloatLE,4,t)},a.prototype.double=function(t){return this.g(r.float.writeDoubleLE,8,t)};var p=r.Array.prototype.set?function(t,i,n){i.set(t,n)}:function(t,i,n){for(var r=0;r>>0;if(!i)return this.g(c,1,0);if(r.isString(t)){var n=a.alloc(i=s.length(t));s.decode(t,n,0),t=n}return this.uint32(i).g(p,i,t)},a.prototype.string=function(t){var i=u.length(t);return i?this.uint32(i).g(u.write,i,t):this.g(c,1,0)},a.prototype.fork=function(){return this.states=new h(this),this.head=this.tail=new o(f,0,0),this.len=0,this},a.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new o(f,0,0),this.len=0),this},a.prototype.ldelim=function(){var t=this.head,i=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=i,this.len+=n),this},a.prototype.finish=function(){for(var t=this.head.next,i=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,i,n),n+=t.len,t=t.next;return i},a.o=function(t){n=t}},{39:39}],43:[function(t,i){i.exports=s;var n=t(42);(s.prototype=Object.create(n.prototype)).constructor=s;var r=t(39),e=r.Buffer;function s(){n.call(this)}s.alloc=function(t){return(s.alloc=r.b)(t)};var u=e&&e.prototype instanceof Uint8Array&&"set"===e.prototype.set.name?function(t,i,n){i.set(t,n)}:function(t,i,n){if(t.copy)t.copy(i,n,0,t.length);else for(var r=0;r>>0;return this.uint32(i),i&&this.g(u,i,t),this},s.prototype.string=function(t){var i=e.byteLength(t);return this.uint32(i),i&&this.g(o,i,t),this}},{39:39,42:42}]},e={},t=[19],i=function t(i){var n=e[i];return n||r[i][0].call(n=e[i]={exports:{}},t,n,n.exports),n.exports}(t[0]),i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}(); -//# sourceMappingURL=protobuf.min.js.map diff --git a/lib/engine/lc0/lib/tf.min.js b/lib/engine/lc0/lib/tf.min.js deleted file mode 100644 index fb7a5231..00000000 --- a/lib/engine/lc0/lib/tf.min.js +++ /dev/null @@ -1,3 +0,0 @@ -// @tensorflow/tfjs Copyright 2018 Google -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.tf=e.tf||{})}(this,function(exports){"use strict";var extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};function __extends(e,t){function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]0;)n=Math.random()*t|0,r=e[--t],e[t]=e[n],e[n]=r}function clamp(e,t,r){return Math.max(e,Math.min(t,r))}function nearestLargerEven(e){return e%2==0?e:e+1}function sum(e){for(var t=0,r=0;r1;--t)if(e%t==0)return[t,e/t];return[1,e]}function createShuffledIndices(e){for(var t=new Uint32Array(e),r=0;r=r?a():setTimeout(i,s)}};i()})}function inferFromImplicitShape(e,t){for(var r=1,n=-1,a=0;a=0)r*=e[a];else if(-1===e[a]){if(-1!==n)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+n+" and dim "+a);n=a}else if(e[a]<0)throw Error("Shapes can not be < 0. Found "+e[a]+" at dim "+a);if(-1===n){if(t>0&&t!==r)throw Error("Size("+t+") must match the product of shape "+e);return e}if(0===r)throw Error("Cannot infer the missing size in ["+e+"] when there are 0 elements");if(t%r!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+r);var o=e.slice();return o[n]=t/r,o}function squeezeShape(e,t){for(var r=[],n=[],a=0,o=0;oo)&&1===e[o]&&(r.push(e[o]),n.push(o)),t[a]<=o&&a++}1!==e[o]&&(r.push(e[o]),n.push(o))}return{newShape:r,keptDims:n}}function getTypedArrayFromDType(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);r=new Uint8Array(t)}return r}function getArrayFromDType(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else if("bool"===e)r=new Uint8Array(t);else{if("string"!==e)throw new Error("Unknown data type "+e);r=new Array(t)}return r}function checkComputationForNaN(e,t,r){if("float32"===t)for(var n=0;n=0;--n)r[n]=r[n+1]*e[n+1];return r}function toTypedArray(e,t,r){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(noConversionNeeded(e,t))return e;if(Array.isArray(e)&&(e=flatten(e)),null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return r&&checkConversionForNaN(e,t),new Int32Array(e);if("bool"===t){for(var n=new Uint8Array(e.length),a=0;a1)for(var l=0;lFORMAT_LIMIT_NUM_VALS){var l=FORMAT_NUM_FIRST_LAST_VALS*i,p=Array.from(e.slice(0,l)),c=Array.from(e.slice(s-FORMAT_NUM_FIRST_LAST_VALS*i,s));return"complex64"===r&&(p=createComplexTuples(p),c=createComplexTuples(c)),["["+p.map(function(e,t){return valToString(e,a[t])}).join(", ")+", ..., "+c.map(function(e,t){return valToString(e,a[s-FORMAT_NUM_FIRST_LAST_VALS+t])}).join(", ")+"]"]}return["["+("complex64"===r?createComplexTuples(e):Array.from(e)).map(function(e,t){return valToString(e,a[t])}).join(", ")+"]"]}var d=t.slice(1),h=n.slice(1),f=n[0]*i,m=[];if(s>FORMAT_LIMIT_NUM_VALS){for(var g=0;g=0;o--)for(i=(f=e[o]).inputs,p=0;p=0;n--)r(n)}e=exports.Rank||(exports.Rank={}),e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6",function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(UpcastInt32AndMap||(UpcastInt32AndMap={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(UpcastBoolAndMap||(UpcastBoolAndMap={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(UpcastFloat32AndMap||(UpcastFloat32AndMap={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(UpcastComplex64AndMap||(UpcastComplex64AndMap={}));var upcastTypeMap={float32:UpcastFloat32AndMap,int32:UpcastInt32AndMap,bool:UpcastBoolAndMap,complex64:UpcastComplex64AndMap};function upcastType(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error("Can not upcast "+e+" with "+t)}return upcastTypeMap[e][t]}function sumOutType(e){return upcastType(e,"int32")}function makeTypesMatch(e,t){if(e.dtype===t.dtype)return[e,t];var r=upcastType(e.dtype,t.dtype);return[e.cast(r),t.cast(r)]}function assertTypesMatch(e,t){assert(e.dtype===t.dtype,"The dtypes of the first("+e.dtype+") and second("+t.dtype+") input must match")}function isTensorInList(e,t){for(var r=0;r0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e},e.prototype.profile=function(e){return __awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(n){return this.profiling=!0,t=this.numBytes,r=this.numTensors,this.activeProfile.kernels=[],this.activeProfile.result=e(),this.profiling=!1,this.activeProfile.peakBytes=Math.max.apply(Math,this.activeProfile.kernels.map(function(e){return e.totalBytesSnapshot})),this.activeProfile.newBytes=this.numBytes-t,this.activeProfile.newTensors=this.numTensors-r,[2,this.activeProfile]})})},e.prototype.shouldRecord=function(){return null!=this.activeTape&&0===this.customGradientDepth},e.prototype.addTapeNode=function(e,t,r){var n={};e.forEach(function(e,t){n[t]=e});var a={id:this.nextTapeNodeId++,name:this.activeScope.name,inputs:n,outputs:[t],gradient:function(e){var t={};return r(e).forEach(function(e,r){t[r]=function(){return e}}),t}};this.activeTape.push(a)},e.prototype.keep=function(e){if(1===this.scopeStack.length&&this.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {...}) to avoid memory leaks.");return this.keepTensors.add(e.id),e},e.prototype.startScope=function(e,t){void 0===t&&(t=!1),t&&0===this.gradientScopeCount&&(this.activeTape=[]),t&&this.gradientScopeCount++;var r={track:[],name:"unnamed scope"};e&&(r.name=e),this.scopeStack.push(r),this.activeScope=r},e.prototype.endScope=function(e,t){var r=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var n=new Set(this.keepTensors),a=getTensorsInContainer(e);a.forEach(function(e){return n.add(e.id)});for(var o=0;o0,"gradients() received an empty list of xs."),null!=r&&"float32"!==r.dtype)throw new Error("dy must have 'float32' dtype, but has '"+r.dtype+"'");return this.tidy("gradients",function(){var o=e();assert(o instanceof Tensor,"The result y returned by f() must be a tensor.");var i=getFilteredNodesXToY(a.activeTape,t,o);if(!n&&0===i.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");var s={};return s[o.id]=null==r?ones(o.shape):r,backpropagateGradients(s,i),{value:o,grads:t.map(function(e){return s[e.id]})}},!0)},e.prototype.customGrad=function(e){var t=this;return assert(isFunction(e),"The f passed in customGrad(f) must be a function."),function(){for(var r,n,a=[],o=0;o {op();...}); to avoid memory leaks.");return null!=this.activeScope&&this.activeScope.track.push(e),e},e.nextTensorId=0,e.nextVariableId=0,e}();function ones(e){var t=makeOnesTypedArray(sizeFromShape(e),"float32");return Tensor.make(e,{values:t})}!function(e){e[e.NUMBER=0]="NUMBER",e[e.BOOLEAN=1]="BOOLEAN",e[e.STRING=2]="STRING"}(Type||(Type={}));var MAX_TEXTURE_SIZE,URL_PROPERTIES=[{name:"DEBUG",type:Type.BOOLEAN},{name:"IS_BROWSER",type:Type.BOOLEAN},{name:"WEBGL_LAZILY_UNPACK",type:Type.BOOLEAN},{name:"WEBGL_CPU_FORWARD",type:Type.BOOLEAN},{name:"WEBGL_PACK",type:Type.BOOLEAN},{name:"WEBGL_PACK_BATCHNORMALIZATION",type:Type.BOOLEAN},{name:"WEBGL_PACK_CLIP",type:Type.BOOLEAN},{name:"WEBGL_PACK_DEPTHWISECONV",type:Type.BOOLEAN},{name:"WEBGL_CONV_IM2COL",type:Type.BOOLEAN},{name:"WEBGL_MAX_TEXTURE_SIZE",type:Type.NUMBER},{name:"WEBGL_PAGING_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:Type.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:Type.BOOLEAN},{name:"WEBGL_VERSION",type:Type.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_SIZE_UPLOAD_UNIFORM",type:Type.NUMBER},{name:"BACKEND",type:Type.STRING},{name:"EPSILON",type:Type.NUMBER},{name:"PROD",type:Type.BOOLEAN},{name:"TENSORLIKE_CHECK_SHAPE_CONSISTENCY",type:Type.BOOLEAN}];function isWebGLVersionEnabled(e){try{if(null!=getWebGLContext(e))return!0}catch(e){return!1}return!1}function getWebGLMaxTextureSize(e){if(null==MAX_TEXTURE_SIZE){var t=getWebGLContext(e);MAX_TEXTURE_SIZE=t.getParameter(t.MAX_TEXTURE_SIZE)}return MAX_TEXTURE_SIZE}function getWebGLDisjointQueryTimerVersion(e){if(0===e)return 0;var t=getWebGLContext(e);return hasExtension(t,"EXT_disjoint_timer_query_webgl2")&&2===e?2:hasExtension(t,"EXT_disjoint_timer_query")?1:0}function isRenderToFloatTextureEnabled(e){if(0===e)return!1;var t=getWebGLContext(e);if(1===e){if(!hasExtension(t,"OES_texture_float"))return!1}else if(!hasExtension(t,"EXT_color_buffer_float"))return!1;return createFloatTextureAndBindToFramebuffer(t,e)}function isDownloadFloatTextureEnabled(e){if(0===e)return!1;var t=getWebGLContext(e);if(1===e){if(!hasExtension(t,"OES_texture_float"))return!1;if(!hasExtension(t,"WEBGL_color_buffer_float"))return!1}else if(!hasExtension(t,"EXT_color_buffer_float"))return!1;return createFloatTextureAndBindToFramebuffer(t,e)}function isWebGLFenceEnabled(e){return 2===e&&null!=getWebGLContext(e).fenceSync}function isChrome(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}var TENSORFLOWJS_FLAGS_PREFIX="tfjsflags";function getFeaturesFromURL(){var e={};if("undefined"==typeof window||void 0===window.location||void 0===window.location.search)return e;var t=getQueryParams(window.location.search);if(TENSORFLOWJS_FLAGS_PREFIX in t){var r={};t[TENSORFLOWJS_FLAGS_PREFIX].split(",").forEach(function(e){var t=e.split(":"),n=t[0],a=t[1];r[n]=a}),URL_PROPERTIES.forEach(function(t){t.name in r&&(console.log("Setting feature override from URL "+t.name+": "+r[t.name]),t.type===Type.NUMBER?e[t.name]=+r[t.name]:t.type===Type.BOOLEAN?e[t.name]="true"===r[t.name]:t.type===Type.STRING?e[t.name]=r[t.name]:console.warn("Unknown URL param: "+t.name+"."))})}return e}function hasExtension(e,t){return null!=e.getExtension(t)}function createFloatTextureAndBindToFramebuffer(e,t){var r=e.createFramebuffer(),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);var a=2===t?e.RGBA32F:e.RGBA;e.texImage2D(e.TEXTURE_2D,0,a,1,1,0,e.RGBA,e.FLOAT,null),e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);var o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),o}function getQueryParams(e){var t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(e){for(var r=[],n=1;n0&&!isMobile();if("HAS_WEBGL"===e)return this.get("WEBGL_VERSION")>0;if("WEBGL_VERSION"===e)return isWebGLVersionEnabled(2)?2:isWebGLVersionEnabled(1)?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===e)return isRenderToFloatTextureEnabled(this.get("WEBGL_VERSION"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===e)return isDownloadFloatTextureEnabled(this.get("WEBGL_VERSION"));if("WEBGL_FENCE_API_ENABLED"===e)return isWebGLFenceEnabled(this.get("WEBGL_VERSION"));if("WEBGL_SIZE_UPLOAD_UNIFORM"===e)return this.get("WEBGL_RENDER_FLOAT32_ENABLED")?4:0;if("TEST_EPSILON"===e)return 32===this.backend.floatPrecision()?TEST_EPSILON_FLOAT32:TEST_EPSILON_FLOAT16;if("EPSILON"===e)return 32===this.backend.floatPrecision()?EPSILON_FLOAT32:EPSILON_FLOAT16;if("PROD"===e)return!1;if("TENSORLIKE_CHECK_SHAPE_CONSISTENCY"===e)return!this.get("PROD");throw new Error("Unknown feature "+e+".")},e.prototype.setFeatures=function(e){this.features=Object.assign({},e)},e.prototype.reset=function(){this.features=getFeaturesFromURL(),null!=this.globalEngine&&(this.globalEngine=null)},Object.defineProperty(e.prototype,"backend",{get:function(){return this.engine.backend},enumerable:!0,configurable:!0}),e.prototype.findBackend=function(e){return e in this.registry?this.registry[e].backend:null},e.prototype.registerBackend=function(e,t,r,n){var a=this;if(void 0===r&&(r=1),e in this.registry)return console.warn(e+" backend was already registered. Reusing existing backend"),null!=n&&n(function(){return a.engine}),!1;try{var o=t();return o.setDataMover({moveData:function(e){return a.engine.moveData(e)}}),this.registry[e]={backend:o,priority:r},!0}catch(t){return console.warn("Registration of backend "+e+" failed"),console.warn(t.stack||t.message),!1}},e.prototype.removeBackend=function(e){if(!(e in this.registry))throw new Error(e+" backend not found in registry");this.registry[e].backend.dispose(),delete this.registry[e]},Object.defineProperty(e.prototype,"engine",{get:function(){return this.initEngine(),this.globalEngine},enumerable:!0,configurable:!0}),e.prototype.initEngine=function(){var e=this;if(null==this.globalEngine){this.backendName=this.get("BACKEND");var t=this.findBackend(this.backendName);this.globalEngine=new Engine(t,!1,function(){return e.get("DEBUG")})}},e}();function getGlobalNamespace(){var e;if("undefined"!=typeof window)e=window;else{if("undefined"==typeof process)throw new Error("Could not find a global object");e=process}return e}function getOrMakeEnvironment(){var e=getGlobalNamespace();return null==e.ENV&&(e.ENV=new Environment(getFeaturesFromURL()),setTensorTracker(function(){return e.ENV.engine})),e.ENV}var ENV=getOrMakeEnvironment(),environment=Object.freeze({EPSILON_FLOAT16:EPSILON_FLOAT16,EPSILON_FLOAT32:EPSILON_FLOAT32,Environment:Environment,ENV:ENV});function grad(e){return assert(isFunction(e),"The f passed in grad(f) must be a function"),function(t,r){return assert(t instanceof Tensor,"The x passed in grad(f)(x) must be a tensor"),assert(null==r||r instanceof Tensor,"The dy passed in grad(f)(x, dy) must be a tensor"),ENV.engine.tidy(function(){var n=ENV.engine.gradients(function(){return e(t)},[t],r),a=n.value,o=n.grads;return null!=r&&assertShapesMatch(a.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),checkGrads(o),o[0]})}}function grads(e){return assert(isFunction(e),"The f passed in grads(f) must be a function"),function(t,r){return assert(Array.isArray(t)&&t.every(function(e){return e instanceof Tensor}),"The args passed in grads(f)(args) must be an array of tensors"),assert(null==r||r instanceof Tensor,"The dy passed in grads(f)(args, dy) must be a tensor"),ENV.engine.tidy(function(){var n=ENV.engine.gradients(function(){return e.apply(void 0,t)},t,r),a=n.value,o=n.grads;return null!=r&&assertShapesMatch(a.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),checkGrads(o),o})}}function valueAndGrad(e){return assert(isFunction(e),"The f passed in valueAndGrad(f) must be a function"),function(t,r){assert(t instanceof Tensor,"The x passed in valueAndGrad(f)(x) must be a tensor"),assert(null==r||r instanceof Tensor,"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");var n=ENV.engine.gradients(function(){return e(t)},[t],r),a=n.grads,o=n.value;return checkGrads(a),{grad:a[0],value:o}}}function valueAndGrads(e){return assert(isFunction(e),"The f passed in valueAndGrads(f) must be a function"),function(t,r){assert(Array.isArray(t)&&t.every(function(e){return e instanceof Tensor}),"The args passed in valueAndGrads(f)(args) must be array of tensors"),assert(null==r||r instanceof Tensor,"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");var n=ENV.engine.gradients(function(){return e.apply(void 0,t)},t,r);return null!=r&&assertShapesMatch(n.value.shape,r.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),checkGrads(n.grads),n}}function variableGrads(e,t){if(assert(isFunction(e),"The f passed in variableGrads(f) must be a function"),assert(null==t||Array.isArray(t)&&t.every(function(e){return e instanceof Variable}),"The varList passed in variableGrads(f, varList) must be an array of variables"),null==t)for(var r in t=[],ENV.engine.registeredVariables)t.push(ENV.engine.registeredVariables[r]);var n=t.length;assert((t=t.filter(function(e){return e.trainable})).length>0,"variableGrads() expects at least one of the input variables to be trainable, but none of the "+n+" variables is trainable.");var a=ENV.engine.gradients(e,t,null,!0),o=a.value,i=a.grads;assert(i.some(function(e){return null!=e}),"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),assert(0===o.rank,"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+o.rank+" tensor");var s={};return t.forEach(function(e,t){null!=i[t]&&(s[e.name]=i[t])}),{value:o,grads:s}}function customGrad(e){return ENV.engine.customGrad(e)}function checkGrads(e){if(e.filter(function(e){return null==e}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var tidy=Environment.tidy,keep=Environment.keep,dispose=Environment.dispose,time=Environment.time,profile=Environment.profile;function warn(){for(var e=[],t=0;t=2*t+1||a%2==1?i.push(a):o.push(a);n.push.apply(n,o),n.push(0),n.push.apply(n,i)}return n}function getReshapedPermuted(e,t,r,n){void 0===n&&(n=!0);var a=[];n?a.push(e[0]/r):a.push(e[0]*r);for(var o=1;o=-r&&e=0&&te.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+t.shape[t.rank-1]+" vs. "+e.rank);if(0===e.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+e.shape+".");for(var r=t.shape,n=r[r.length-1],a=1,o=0;o1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+r.shape+", indices.shape: "+t.shape+", shape: "+e+", sliceDim: "+n+", and batchDim: "+a+".";if(r.rank1?t.shape[t.rank-1]:1,a=r.length,o=1,i=n;it||r===e){n=!0;break}r=nearestDivisor(e,r+1)}return r}function computeOutShape$1(e,t,r){for(var n=[],a=e.length,o=0;o0?a>=p[t]:a<=p[t]);a+=n[t])r+=1;return r}),[l,h,c]}function startForAxis(e,t,r,n,a){var o=t[a];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var i=n[a];return o<0&&(o+=i),clamp(0,o,i-1)}function stopForAxis(e,t,r,n,a){var o=t[a];e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var i=n[a];return o<0&&(o+=i),r[a]>0?clamp(0,o,i):clamp(-1,o,i-1)}function inferShape(e){var t=e;if(isTypedArray(e))return[e.length];if(!Array.isArray(e))return[];for(var r=[];t instanceof Array||isTypedArray(t);)r.push(t.length),t=t[0];return e instanceof Array&&ENV.get("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&deepAssertShapeConsistency(e,r,[]),r}function deepAssertShapeConsistency(e,t,r){if(r=r||[],e instanceof Array||isTypedArray(e)){assert(t.length>0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),assert(e.length===t[0],function(){return"Element arr["+r.join("][")+"] should have "+t[0]+" elements, but has "+e.length+" elements"});for(var n=t.slice(1),a=0;a=0&&(a=n),assertDtype(n,a,t,r),!isTypedArray(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("Argument '"+t+"' passed to '"+r+"' must be a Tensor or TensorLike, but got '"+e.constructor.name+"'");var o=inferShape(e);isTypedArray(e)||Array.isArray(e)||(e=[e]);var i="string"!==a?toTypedArray(e,a,ENV.get("DEBUG")):flatten(e);return Tensor.make(o,{values:i},a)}function convertToTensorArray(e,t,r){if(!Array.isArray(e))throw new Error("Argument "+t+" passed to "+r+" must be a `Tensor[]` or `TensorLike[]`");return e.map(function(e,n){return convertToTensor(e,t+"["+n+"]",r)})}function op(e){var t=Object.keys(e);if(1!==t.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+t.length+" keys.");var r=t[0],n=e[r];r.endsWith("_")&&(r=r.substring(0,r.length-1));var a=function(){for(var e=[],t=0;t1)return zeros([0],n);var a=makeZerosTypedArray(Math.abs(Math.ceil((t-e)/r)),n);ta}).sort(function(e,t){return t.score-e.score}),i=[],s=0;s=0;--d)if(intersectionOverUnion(e,p,i[d])>=n){c=!0;break}if(!c&&(i.push(p),i.length>=r))break}return tensor1d(i,"int32")}function intersectionOverUnion(e,t,r){var n=e.subarray(4*t,4*t+4),a=e.subarray(4*r,4*r+4),o=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),s=Math.max(n[0],n[2]),u=Math.max(n[1],n[3]),l=Math.min(a[0],a[2]),p=Math.min(a[1],a[3]),c=Math.max(a[0],a[2]),d=Math.max(a[1],a[3]),h=(s-o)*(u-i),f=(c-l)*(d-p);if(h<=0||f<=0)return 0;var m=Math.max(o,l),g=Math.max(i,p),y=Math.min(s,c),v=Math.min(u,d),x=Math.max(y-m,0)*Math.max(v-g,0);return x/(h+f-x)}function split(e,t,r){var n=Array(e.rank).fill(0),a=e.shape.slice();return t.map(function(t){a[r]=t;var o=e.slice(n,a);return n[r]+=t,o})}function topkImpl(e,t,r,n,a){for(var o=t[t.length-1],i=[e.length/o,o],s=i[0],u=i[1],l=getTypedArrayFromDType(r,s*n),p=getTypedArrayFromDType("int32",s*n),c=0;c":"<",u=r?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+n+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "},AvgPool2DBackpropProgram=function(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,o=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=s-1-e.padInfo.top,p=u-1-e.padInfo.left,c=1/(t*r);this.userCode="\n const ivec2 pads = ivec2("+l+", "+p+");\n const float avgMultiplier = float("+c+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+i+") {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "};function getBroadcastDims(e,t){for(var r=e.length,n=[],a=0;a1&&1===i&&n.unshift(o)}return n}function getReductionAxes(e,t){for(var r=[],n=0;n1)&&r.unshift(o)}return r}function broadcastDimsAreOuter(e){for(var t=0;t= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+a+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Conv2DDerInputProgram=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,o=t-1-e.padInfo.top,i=r-1-e.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+o+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+t+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+e.outChannels+"; d2++) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Conv3DDerFilterProgram=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,a=e.padInfo.front,o=e.padInfo.top,i=e.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yF = 0; yF < "+e.outDepth+"; yF++) {\n int xF = wF + yF * "+t+" - "+a+";\n\n if (xF < 0 || xF >= "+e.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+r+" - "+o+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Conv3DDerInputProgram=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,a=e.strideDepth,o=e.strideHeight,i=e.strideWidth,s=t-1-e.padInfo.front,u=r-1-e.padInfo.top,l=n-1-e.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+t+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+a+".0;\n\n if (dyF < 0.0 || dyF >= "+e.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+t+" - 1 - wF;\n\n for (int wR = 0; wR < "+r+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+o+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+r+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+e.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},DepthwiseConv2DDerFilterProgram=function(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+o+" + dm;\n\n float dotProd = 0.0;\n\n // TODO: Vec4 over the batch size\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+n+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+a+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},DepthwiseConv2DDerInputProgram=function(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,o=t-1-e.padInfo.top,i=r-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+o+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+t+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Conv2DProgram=function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.top,r=e.padInfo.left,n=e.strideHeight,a=e.strideWidth,o=e.dilationHeight,i=e.dilationWidth,s=e.filterHeight,u=e.filterWidth,l=4*Math.floor(e.inChannels/4),p=e.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+n+", "+a+");\n const ivec2 pads = ivec2("+t+", "+r+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+"; wR++) {\n int xR = xRCorner + wR * "+o+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+i+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+l+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===p)+") {\n dotProd +=\n getX(batch, xR, xC, "+l+") *\n getW(wR, wC, "+l+", d2);\n } else if ("+(2===p)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===p)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1),\n getX(batch, xR, xC, "+l+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2),\n getW(wR, wC, "+l+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Conv3DProgram=function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.front,r=e.padInfo.top,n=e.padInfo.left,a=e.strideDepth,o=e.strideHeight,i=e.strideWidth,s=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,p=e.filterDepth,c=e.filterHeight,d=e.filterWidth,h=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+a+", "+o+", "+i+");\n const ivec3 pads = ivec3("+t+", "+r+", "+n+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+p+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+e.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+h+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===f)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+h+") *\n getW(wF, wR, wC, "+h+", d2);\n } else if ("+(2===f)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+h+"),\n getX(batch, xF, xR, xC, "+h+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+h+", d2),\n getW(wF, wR, wC, "+h+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===f)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+h+"),\n getX(batch, xF, xR, xC, "+h+" + 1),\n getX(batch, xF, xR, xC, "+h+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+h+", d2),\n getW(wF, wR, wC, "+h+" + 1, d2),\n getW(wF, wR, wC, "+h+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},DepthwiseConv2DProgram=function(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.inHeight,r=e.inWidth,n=e.padInfo.top,a=e.padInfo.left,o=e.strideHeight,i=e.strideWidth,s=e.dilationHeight,u=e.dilationWidth,l=e.filterHeight,p=e.filterWidth,c=e.outChannels/e.inChannels;this.userCode="\n const ivec2 strides = ivec2("+o+", "+i+");\n const ivec2 pads = ivec2("+n+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+c+";\n int q = d2 - d1 * "+c+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+t+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+r+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n "},DepthwiseConvPacked2DProgram=function(e){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=e.outShape;for(var t=e.inHeight,r=e.inWidth,n=e.padInfo.top,a=e.padInfo.left,o=e.strideHeight,i=e.strideWidth,s=e.filterHeight,u=e.filterWidth,l=Math.ceil((u+1)/2),p="int xR; int xC;",c=0;c= 0 && xR < "+t+" && xC >= 0 && xC < "+r+") {\n "+xTexelName(c,f)+" = getX(batch, xR, xC, d1);\n }",0===a?h1&&(p+="\n vec4 "+xTexelName(c,f+2)+" = vec4(0.);\n\n if(xR >= 0 && xR < "+t+" && xC + 2 < "+r+") {\n "+xTexelName(c,f+2)+" = getX(batch, xR, xC + 2, d1);\n }"),p+="\n xR"+c+"C"+f+" = "+constructTexel(c,f,i,a)+";\n "):0===d&&(p+="\n if(xR >= 0 && xR < "+t+" && xC - 2 >= 0) {\n "+xTexelName(c,f-2)+" = getX(batch, xR, xC - 2, d1);\n }"),h>0&&(p+="xR"+c+"C"+(f-2)+" =\n "+constructTexel(c,f-2,i,a)+";"),f-1>=0&&f-11?[""+(i-1)/(p-1),"(y2-y1) * height_ratio","y1*"+f+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+f],y=g[0],v=g[1],x=g[2],b=c>1?[""+(s-1)/(c-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],w=b[0],N=b[1],S=b[2];this.userCode="\n const float height_ratio = float("+y+");\n const float width_ratio = float("+w+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+o+") {\n return;\n }\n\n float height_scale = "+v+";\n float width_scale = "+N+";\n\n float in_y = "+x+";\n if( in_y < 0.0 || in_y > "+f+" ) {\n setOutput(float("+a+"));\n return;\n }\n float in_x = "+S+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+a+"));\n return;\n }\n\n vec2 sourceFracIndexRC = vec2(in_y,in_x);\n if("+d+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getImage(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(floor(\n sourceFracIndexRC + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n setOutput(newValue);\n }\n }\n "};function getLogicalCoordinatesFromFlatIndex(e,t,r){void 0===r&&(r="index");var n=computeStrides(t);return n.map(function(t,a){return"int "+e[a]+" = "+r+" / "+t+"; "+(a===n.length-1?"int "+e[a+1]+" = "+r+" - "+e[a]+" * "+t:"index -= "+e[a]+" * "+t)+";"}).join("")}function buildVec(e){return 1===e.length?""+e[0]:"vec"+e.length+"("+e.join(",")+")"}function dotify(e,t){if(e.length!==t.length)throw new Error("Vectors to be dotted must be of the same length -got "+e.length+" and "+t.length);for(var r=[],n=Math.floor(e.length/4),a=e.length%4,o=0;o1?"["+t+"]":"")+";":"uniform sampler2D "+e.name+";"});o=o.join("\n");var i,s,u=e.map(function(e){return getInputSamplingSnippet(e,t,n,a)}).join("\n"),l=t.texShape,p=SHADER_PREFIX;return t.isPacked?(i=getPackedOutputSamplingSnippet(t.logicalShape,l),s=FLOAT_TEXTURE_SET_RGBA_SNIPPET):(i=getOutputSamplingSnippet(t.logicalShape,l),s=FLOAT_TEXTURE_SET_R_SNIPPET),a&&(p+=SHADER_PACKED_PREFIX),[p,FLOAT_TEXTURE_SAMPLE_SNIPPET,s,o,i,u,r].join("\n")}function getSamplerFromInInfo(e){var t=e.shapeInfo.logicalShape;switch(t.length){case 0:return getSamplerScalar(e);case 1:return getSampler1D(e);case 2:return getSampler2D(e);case 3:return getSampler3D(e);case 4:return getSampler4D(e);case 5:return getSampler5D(e);case 6:return getSampler6D(e);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function getPackedSamplerFromInInfo(e){var t=e.shapeInfo.logicalShape;switch(t.length){case 0:return getPackedSamplerScalar(e);case 1:return getPackedSampler1D(e);case 2:return getPackedSampler2D(e);case 3:return getPackedSampler3D(e);case 4:return getPackedSampler4D(e);default:throw new Error("Packed "+t.length+"-D input sampling is not yet supported")}}function getInputSamplingSnippet(e,t,r,n){void 0===n&&(n=!1);var a=getSamplerFlat(e);return a+=n?getPackedSamplerFromInInfo(e):getSamplerFromInInfo(e),(r||arraysEqual(e.shapeInfo.logicalShape,t.logicalShape))&&(a+=n?getPackedSamplerAtOutputCoords(e,t,r):getSamplerAtOutputCoords(e,t,r)),a}function getPackedOutputSamplingSnippet(e,t){switch(e.length){case 0:return getOutputScalarCoords();case 1:return getOutputPacked1DCoords(e,t);case 2:return getOutputPacked2DCoords(e,t);case 3:return getOutputPacked3DCoords(e,t);case 4:return getOutputPacked4DCoords(e,t);default:throw new Error(e.length+"-D packed output coordinate fetching is not yet supported")}}function getOutputSamplingSnippet(e,t){switch(e.length){case 0:return getOutputScalarCoords();case 1:return getOutput1DCoords(e,t);case 2:return getOutput2DCoords(e,t);case 3:return getOutput3DCoords(e,t);case 4:return getOutput4DCoords(e,t);case 5:return getOutput5DCoords(e,t);case 6:return getOutput6DCoords(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported")}}var SAMPLE_1D_SNIPPET="\nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_2D_SNIPPET="\nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_3D_SNIPPET="\nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_4D_SNIPPET="\nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom4D(int texNumR, int texNumC, int texelsInBatch2,\n int texelsInBatch, int texelsInLogicalRow, int b2, int b,\n int row, int col) {\n int index = b2 * texelsInBatch2 + b * texelsInBatch +\n (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_5D_SNIPPET="\nvec2 UVfrom5D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int row, int col, int depth,\n int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2 * stride3 + depth3;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_6D_SNIPPET="\nvec2 UVfrom6D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int stride4,\n int row, int col, int depth, int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2 *\n stride3 + depth3 * stride4 + depth4;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",FLOAT_TEXTURE_SAMPLE_SNIPPET="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n",FLOAT_TEXTURE_SET_R_SNIPPET="\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n",FLOAT_TEXTURE_SET_RGBA_SNIPPET="\n void setOutput(vec4 val) {\n gl_FragColor = val;\n }\n",NAN_CHECKS="",SHADER_PREFIX="\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n "+(NAN_CHECKS=ENV.get("PROD")?"\n bool isNaN(float val) {\n return false;\n }\n\n bool hasNaN(vec4 values) {\n return false;\n }\n ":"\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n return any(bvec4(\n isNaN(values.x),\n isNaN(values.y),\n isNaN(values.z),\n isNaN(values.w)\n ));\n }\n ")+"\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+SAMPLE_1D_SNIPPET+"\n "+SAMPLE_2D_SNIPPET+"\n "+SAMPLE_3D_SNIPPET+"\n "+SAMPLE_4D_SNIPPET+"\n "+SAMPLE_5D_SNIPPET+"\n "+SAMPLE_6D_SNIPPET+"\n",SHADER_PACKED_PREFIX="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function getOutputScalarCoords(){return"\n int getOutputCoords() {\n return 0;\n }\n "}function getOutputPacked1DCoords(e,t){var r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===t[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+r[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+r[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+r[0]+", "+r[1]+"));\n return resTexRC.x * "+r[1]+" + resTexRC.y;\n }\n "}function getOutput1DCoords(e,t){return 1===t[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+t[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+t[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n return resTexRC.x * "+t[1]+" + resTexRC.y;\n }\n "}function getOutputPacked3DCoords(e,t){var r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[2]/2),a=n*Math.ceil(e[1]/2);return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+r[0]+", "+r[1]+"));\n int index = resTexRC.x * "+r[1]+" + resTexRC.y;\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+n+");\n int c = imod(index, "+n+") * 2;\n\n return ivec3(b, r, c);\n }\n "}function getOutput3DCoords(e,t){var r=getLogicalCoordinatesFromFlatIndex(["r","c","d"],e);return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n "+r+"\n return ivec3(r, c, d);\n }\n "}function getOutputPacked4DCoords(e,t){var r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[3]/2),a=n*Math.ceil(e[2]/2),o=a*e[1];return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+r[0]+", "+r[1]+"));\n int index = resTexRC.x * "+r[1]+" + resTexRC.y;\n\n int b2 = index / "+o+";\n index -= b2 * "+o+";\n\n int b = index / "+a+";\n index -= b * "+a+";\n\n int r = 2 * (index / "+n+");\n int c = imod(index, "+n+") * 2;\n\n return ivec4(b2, b, r, c);\n }\n "}function getOutput4DCoords(e,t){var r=getLogicalCoordinatesFromFlatIndex(["r","c","d","d2"],e);return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n "+r+"\n return ivec4(r, c, d, d2);\n }\n "}function getOutput5DCoords(e,t){var r=getLogicalCoordinatesFromFlatIndex(["r","c","d","d2","d3"],e);return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+t[0]+",\n "+t[1]+"));\n\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n "+r+"\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}function getOutput6DCoords(e,t){var r=getLogicalCoordinatesFromFlatIndex(["r","c","d","d2","d3","d4"],e);return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n "+r+"\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}function getOutputPacked2DCoords(e,t){var r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(arraysEqual(e,t))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+r[0]+", "+r[1]+"));\n }\n ";var n=Math.ceil(e[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+r[0]+", "+r[1]+"));\n\n int index = resTexRC.x * "+r[1]+" + resTexRC.y;\n int r = 2 * (index / "+n+");\n int c = imod(index, "+n+") * 2;\n\n return ivec2(r, c);\n }\n "}function getOutput2DCoords(e,t){return arraysEqual(e,t)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n }\n ":1===e[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===e[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+e[1]+";\n int c = index - r * "+e[1]+";\n return ivec2(r, c);\n }\n "}function getPackedSamplerScalar(e){var t=e.name;return"\n vec4 get"+t.charAt(0).toUpperCase()+t.slice(1)+"() {\n return texture2D("+t+", halfCR);\n }\n "}function getSamplerScalar(e){var t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1);return e.shapeInfo.isUniform?"float "+r+"() {return "+t+";}":"\n float "+r+"() {\n return sampleTexture("+t+", halfCR);\n }\n "}function getPackedSampler1D(e){var t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e.shapeInfo.texShape,a=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)];return"\n vec4 "+r+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+a[0]+", "+a[1]+", index);\n return texture2D("+t+", uv);\n }\n "}function getSampler1D(e){var t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1);return"\n float "+r+"(int index) {\n return "+r+"Flat(index);\n }\n "}function getPackedSampler2D(e){var t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=a[0],i=a[1];if(null!=a&&arraysEqual(t,a))return"\n vec4 "+n+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+o+".0);\n\n return texture2D("+r+", uv);\n }\n ";var s=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return"\n vec4 "+n+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+Math.ceil(t[1]/2)+", "+s[0]+", "+s[1]+", row, col);\n return texture2D("+r+", uv);\n }\n "}function getSampler2D(e){var t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(null!=a&&arraysEqual(t,a)){var o=a[0];return"\n float "+n+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+a[1]+".0, "+o+".0);\n return sampleTexture("+r+", uv);\n }\n "}var i=squeezeShape(t),s=i.newShape,u=i.keptDims,l=s;if(l.length=1?"coords = 0;":s.map(function(e){return"coords["+(e+u)+"] = 0;"}).join("\n"))+"\n return get"+r+"("+(o<2&&a>0?"coords":e.shapeInfo.logicalShape.map(function(e,t){return"coords["+(t+u)+"]"}).join(", "))+");\n }\n "}function getPackedSamplerAtOutputCoords(e,t,r){var n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),o=e.shapeInfo.texShape,i="get"+a+"AtOutCoords",s=t.texShape,u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],l=u[0],p=u[1],c=getBroadcastDims(e.shapeInfo.logicalShape,t.logicalShape),d=e.shapeInfo.logicalShape.length,h=t.logicalShape.length;if(c.length)throw Error("Packed broadcast sampling is not implemented yet.");if(arraysEqual(e.shapeInfo.texShape,s))return"\n vec4 "+i+"() {\n return texture2D("+n+", resultUV);\n }\n ";var f="return texture2D("+n+", uv)";return 1===d&&h>1?f="\n vec4 sample = texture2D("+n+", uv);\n return vec4(sample.xy, sample.xy);\n ":0===d&&h>0&&(f=1===h?"\n vec4 sample = texture2D("+n+", uv);\n return vec4(sample.x, sample.x, 0., 0.);\n ":"\n vec4 sample = texture2D("+n+", uv);\n return vec4(sample.x);\n "),"\n vec4 "+i+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+u[0]+", "+u[1]+"));\n int index = resTexRC.x * "+u[1]+" + resTexRC.y;\n\n int texR = index / "+p+";\n int texC = index - texR * "+p+";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+p+", "+l+");\n\n "+f+";\n }\n "}function getSamplerAtOutputCoords(e,t,r){var n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),o="get"+a+"AtOutCoords",i=getBroadcastDims(e.shapeInfo.logicalShape,t.logicalShape),s=e.shapeInfo.logicalShape.length,u=t.logicalShape.length,l=r&&(u>s||i.length>0),p=broadcastDimsAreOuter(i),c=e.shapeInfo.isUniform;if(l&&!p)return getBroadcastOutputCoordsSampler(e,t,a,o);var d=sizeFromShape(e.shapeInfo.logicalShape),h="";l&&p&&(h="\n int mainPart = index / "+d+";\n index -= mainPart * "+d+";\n ");var f=t.texShape;if(c)return 1===d?"float "+o+"() {return "+n+";}":"\n float "+o+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+f[0]+", "+f[1]+"));\n int index = resTexRC.x * "+f[1]+" + resTexRC.y;\n "+h+"\n return get"+a+"Flat(index);\n }\n ";var m=e.shapeInfo.texShape;return arraysEqual(m,f)?"\n float "+o+"() {\n return sampleTexture("+n+", resultUV);\n }\n ":"\n float "+o+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+f[0]+", "+f[1]+"));\n int index = resTexRC.x * "+f[1]+" + resTexRC.y;\n "+h+"\n int texR = index / "+m[1]+";\n int texC = index - texR * "+m[1]+";\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m[1]+".0, "+m[0]+".0);\n\n return sampleTexture("+n+", uv);\n }\n "}function getCoordsDataType(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error("GPU for rank "+e+" is not yet supported")}function squeezeInputInfo(e,t){var r=JSON.parse(JSON.stringify(e));return r.shapeInfo.logicalShape=t,r}function getSqueezedParams(e,t){return t.map(function(t){return e[t]}).join(", ")}var CumSumProgram=function(e,t,r){this.variableNames=["x"],this.outputShape=e;var n=e.length,a=e[e.length-1],o=r?"<":">";this.userCode="\n int getIndex(int i) {\n "+(r?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+getCoordsDataType(n)+" coords = getOutputCoords();\n int end = "+getFinalCoord(n,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+o+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+getFinalCoord(n,"coords")+" = idx;\n val += getX("+getCoords(n,"coords")+");\n }\n setOutput(val);\n }\n "};function getCoords(e,t){if(1===e)return""+t;if(2===e)return t+".x, "+t+".y";if(3===e)return t+".x, "+t+".y, "+t+".z";if(4===e)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported")}function getFinalCoord(e,t){if(1===e)return""+t;if(2===e)return t+".y";if(3===e)return t+".z";if(4===e)return t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported")}var DepthToSpaceProgram=function(){function e(e,t,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=r,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+t+";\n int offset_h = imod(h, "+t+");\n int in_w = w / "+t+";\n int offset_w = imod(w, "+t+");\n int offset_d = (offset_h * "+t+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return e.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},e.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},e.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},e.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},e}(),EncodeFloatProgram=function(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n "},COMPLEX_FFT={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"},FFTProgram=function(e,t,r){this.variableNames=["real","imag"];var n=t[1];this.outputShape=t;var a=r?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,o=r?n+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+a+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+e+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+n+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+n+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+o+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},FromPixelsProgram=function(e){this.variableNames=["A"];var t=e[0],r=e[1];this.outputShape=e,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+t+".0);\n\n vec4 values = texture2D(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},GatherProgram=function(e,t,r){this.variableNames=["A","indices"];var n=e.slice();n[r]=t,this.outputShape=n,this.rank=n.length;var a=getCoordsDataType(this.rank),o=getSourceCoords(e,r);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "};function getSourceCoords(e,t){var r=e.length;if(r>4)throw Error("Gather for rank "+r+" is not yet supported");if(1===r)return"int(getIndices(resRC))";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],o=0;o1?"strides[j]":"strides";this.userCode="\n "+n+" strides = "+n+"("+this.strides+");\n void main() {\n "+a+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+o+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function getUnpackedMatrixTextureShapeWidthHeight(e,t){return[t,e]}function getUnpackedArraySizeFromMatrixSize(e,t){return e*t}function getMatrixSizeFromUnpackedArraySize(e,t){if(e%t!=0)throw new Error("unpackedSize ("+e+") must be a multiple of "+t);return e/t}function encodeMatrixToUnpackedArray(e,t,r){var n=getUnpackedArraySizeFromMatrixSize(e.length,r);if(t.length= "+n);for(var a=0,o=0;o= "+n);for(var a=0,o=0;o=\n "+o);for(var i=n%2==1,s=r%2==1,u=Math.floor(n/2),l=Math.floor(r/2),p=Math.ceil(n/2),c=p*Math.ceil(r/2),d=nearestLargerEven(r)*nearestLargerEven(n),h=0;h= "+o);for(var i=n%2==1,s=r%2==1,u=Math.floor(n/2),l=Math.floor(r/2),p=Math.ceil(n/2),c=p*Math.ceil(r/2),d=nearestLargerEven(r)*nearestLargerEven(n),h=0;hr||t>r)throw n="["+e+"x"+t+"]",new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU ["+r+"x"+r+"].")}function createFramebuffer(e){return throwIfNull(e,function(){return e.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function bindVertexBufferToProgramAttribute(e,t,r,n,a,o,i){var s=e.getAttribLocation(t,r);return-1!==s&&(callAndCheck(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,n)}),callAndCheck(e,function(){return e.vertexAttribPointer(s,a,e.FLOAT,!1,o,i)}),callAndCheck(e,function(){return e.enableVertexAttribArray(s)}),!0)}function bindTextureUnit(e,t,r){validateTextureUnit(e,r),callAndCheck(e,function(){return e.activeTexture(e.TEXTURE0+r)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,t)})}function unbindTextureUnit(e,t){validateTextureUnit(e,t),callAndCheck(e,function(){return e.activeTexture(e.TEXTURE0+t)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function getProgramUniformLocationOrThrow(e,t,r){return throwIfNull(e,function(){return e.getUniformLocation(t,r)},'uniform "'+r+'" not present in program.')}function getProgramUniformLocation(e,t,r){return e.getUniformLocation(t,r)}function bindTextureToProgramUniformSampler(e,t,r,n,a){callAndCheck(e,function(){return bindTextureUnit(e,r,a)}),callAndCheck(e,function(){return e.uniform1i(n,a)})}function bindCanvasToFramebuffer(e){callAndCheck(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),callAndCheck(e,function(){return e.viewport(0,0,e.canvas.width,e.canvas.height)}),callAndCheck(e,function(){return e.scissor(0,0,e.canvas.width,e.canvas.height)})}function bindColorTextureToFramebuffer(e,t,r){callAndCheck(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,r)}),callAndCheck(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)})}function unbindColorTextureFromFramebuffer(e,t){callAndCheck(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,t)}),callAndCheck(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)})}function validateFramebuffer(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+getFramebufferErrorMessage(e,t))}function getFramebufferErrorMessage(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function throwIfNull(e,t,r){var n=callAndCheck(e,function(){return t()});if(null==n)throw new Error(r);return n}function validateTextureUnit(e,t){var r=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(nr)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+r+"].")}function getTextureShapeFromLogicalShape(e,t){void 0===t&&(t=!1);var r=ENV.get("WEBGL_MAX_TEXTURE_SIZE");if(t&&(r*=2,e=e.map(function(t,r){return r>=e.length-2?nearestLargerEven(e[r]):e[r]})),2!==e.length){var n=squeezeShape(e);e=n.newShape}var a=sizeFromShape(e);return e.length<=1&&a<=r?[1,a]:2===e.length&&e[0]<=r&&e[1]<=r?e:3===e.length&&e[0]*e[1]<=r&&e[2]<=r?[e[0]*e[1],e[2]]:3===e.length&&e[0]<=r&&e[1]*e[2]<=r?[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=r&&e[3]<=r?[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=r&&e[1]*e[2]*e[3]<=r?[e[0],e[1]*e[2]*e[3]]:sizeToSquarishShape(a)}function isEven(e){return e%2==0}function isReshapeFree(e,t){if(arraysEqual(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){var r=e.slice(-1)[0],n=t.slice(-1)[0];if(r===n)return!0;if(isEven(r)&&isEven(n)&&(1===e[0]||1===t[0]))return!0}else if(isEven(e[0])&&isEven(t[0])){if(isEven(e[1])&&isEven(t[1]))return!0;if(e[1]===t[1])return!0}return!1}var webgl_util=Object.freeze({callAndCheck:callAndCheck,enableDebugWebGLErrorChecking:enableDebugWebGLErrorChecking,checkWebGLError:checkWebGLError,getWebGLErrorMessage:getWebGLErrorMessage,getExtensionOrThrow:getExtensionOrThrow,createVertexShader:createVertexShader,createFragmentShader:createFragmentShader,createProgram:createProgram,linkProgram:linkProgram,validateProgram:validateProgram,createStaticVertexBuffer:createStaticVertexBuffer,createStaticIndexBuffer:createStaticIndexBuffer,getNumChannels:getNumChannels,createTexture:createTexture,validateTextureSize:validateTextureSize,createFramebuffer:createFramebuffer,bindVertexBufferToProgramAttribute:bindVertexBufferToProgramAttribute,bindTextureUnit:bindTextureUnit,unbindTextureUnit:unbindTextureUnit,getProgramUniformLocationOrThrow:getProgramUniformLocationOrThrow,getProgramUniformLocation:getProgramUniformLocation,bindTextureToProgramUniformSampler:bindTextureToProgramUniformSampler,bindCanvasToFramebuffer:bindCanvasToFramebuffer,bindColorTextureToFramebuffer:bindColorTextureToFramebuffer,unbindColorTextureFromFramebuffer:unbindColorTextureFromFramebuffer,validateFramebuffer:validateFramebuffer,getFramebufferErrorMessage:getFramebufferErrorMessage,getTextureShapeFromLogicalShape:getTextureShapeFromLogicalShape,isReshapeFree:isReshapeFree});function createVertexShader$1(e){return createVertexShader(e,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function createVertexBuffer(e){return createStaticVertexBuffer(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function createIndexBuffer(e){return createStaticIndexBuffer(e,new Uint16Array([0,1,2,2,1,3]))}function getTextureConfig(e,t){var r,n,a,o,i,s,u,l=e;return 2===ENV.get("WEBGL_VERSION")?(r=l.R32F,n=l.R16F,a=l.RGBA32F,o=l.RED,i=4,s=1,u=l.HALF_FLOAT):(r=e.RGBA,n=e.RGBA,a=l.RGBA,o=e.RGBA,i=4,s=4,u=null!=t?t.HALF_FLOAT_OES:null),{internalFormatFloat:r,internalFormatHalfFloat:n,internalFormatPackedFloat:a,textureFormatFloat:o,downloadTextureFormat:e.RGBA,downloadUnpackNumChannels:i,defaultNumChannels:s,textureTypeHalfFloat:u}}function createAndConfigureTexture(e,t,r,n,a,o){validateTextureSize(t,r);var i=createTexture(e),s=e.TEXTURE_2D;return callAndCheck(e,function(){return e.bindTexture(s,i)}),callAndCheck(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)}),callAndCheck(e,function(){return e.texParameteri(s,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}),callAndCheck(e,function(){return e.texParameteri(s,e.TEXTURE_MIN_FILTER,e.NEAREST)}),callAndCheck(e,function(){return e.texParameteri(s,e.TEXTURE_MAG_FILTER,e.NEAREST)}),callAndCheck(e,function(){return e.texImage2D(s,0,n,t,r,0,a,o,null)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,null)}),i}function createFloat32MatrixTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],n.internalFormatFloat,n.textureFormatFloat,e.FLOAT)}function createFloat16MatrixTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],n.internalFormatFloat,n.textureFormatFloat,n.textureTypeHalfFloat)}function createUnsignedBytesMatrixTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],e.RGBA,e.RGBA,e.UNSIGNED_BYTE)}function createPackedMatrixTexture(e,t,r,n){var a=getPackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],n.internalFormatPackedFloat,e.RGBA,e.FLOAT)}function createFloat16PackedMatrixTexture(e,t,r,n){var a=getPackedMatrixTextureShapeWidthHeight(t,r);return createAndConfigureTexture(e,a[0],a[1],n.internalFormatHalfFloat,e.RGBA,n.textureTypeHalfFloat)}function bindVertexProgramAttributeStreams(e,t,r){return callAndCheck(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,r)}),bindVertexBufferToProgramAttribute(e,t,"clipSpacePos",r,3,20,0)&&bindVertexBufferToProgramAttribute(e,t,"uv",r,2,20,12)}function uploadPixelDataToTexture(e,t,r){callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),callAndCheck(e,function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function uploadDataToTexture(e,t,r,n,a,o){validateTextureSize(r,n),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,t)}),callAndCheck(e,function(){return e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,o,e.FLOAT,a)}),callAndCheck(e,function(){return e.bindTexture(e.TEXTURE_2D,null)})}function uploadMatrixToTexture(e,t,r,n,a,o,i){var s,u=getUnpackedMatrixTextureShapeWidthHeight(r,n),l=u[0],p=u[1];1===i.defaultNumChannels?s=a:encodeMatrixToUnpackedArray(a,s=new Float32Array(getUnpackedArraySizeFromMatrixSize(a.length,o)),o),uploadDataToTexture(e,t,l,p,s,i.textureFormatFloat)}function uploadMatrixToPackedTexture(e,t,r,n,a,o,i,s,u){var l=getPackedMatrixTextureShapeWidthHeight(o,i),p=l[0],c=l[1],d=new Float32Array(r*getPackedRGBAArraySizeFromMatrixShape(n,a));encodeMatrixToPackedRGBA(s,r,n,a,d),uploadDataToTexture(e,t,p,c,d,e.RGBA)}function maybeCreateBufferFromOutputTexture(e,t,r,n,a){var o=t;if(2===ENV.get("WEBGL_VERSION")){var i=e,s=i.createBuffer();callAndCheck(e,function(){return e.bindBuffer(i.PIXEL_PACK_BUFFER,s)});var u=4*getUnpackedArraySizeFromMatrixSize(r*n,a.downloadUnpackNumChannels);callAndCheck(e,function(){return e.bufferData(i.PIXEL_PACK_BUFFER,u,e.STATIC_DRAW)}),callAndCheck(e,function(){return i.readPixels(0,0,n,r,e.RGBA,e.FLOAT,0)}),callAndCheck(e,function(){return e.bindBuffer(i.PIXEL_PACK_BUFFER,null)}),o=s}return o}function downloadFloat32MatrixFromBuffer(e,t,r,n,a){var o=e,i=new Float32Array(getUnpackedArraySizeFromMatrixSize(r*n,a.downloadUnpackNumChannels));o.bindBuffer(e.ARRAY_BUFFER,t),o.getBufferSubData(e.ARRAY_BUFFER,0,i),o.bindBuffer(e.ARRAY_BUFFER,null);var s=new Float32Array(r*n);return decodeMatrixFromUnpackedArray(i,s,a.downloadUnpackNumChannels),s}function downloadFloat32MatrixFromOutputTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r),o=a[0],i=a[1],s=new Float32Array(getUnpackedArraySizeFromMatrixSize(t*r,n.downloadUnpackNumChannels));callAndCheck(e,function(){return e.readPixels(0,0,o,i,n.downloadTextureFormat,e.FLOAT,s)});var u=new Float32Array(t*r);return decodeMatrixFromUnpackedArray(s,u,n.downloadUnpackNumChannels),u}function downloadByteEncodedFloatMatrixFromOutputTexture(e,t,r,n){var a=getUnpackedMatrixTextureShapeWidthHeight(t,r),o=a[0],i=a[1],s=new Uint8Array(getUnpackedArraySizeFromMatrixSize(t*r,4));return callAndCheck(e,function(){return e.readPixels(0,0,o,i,n.downloadTextureFormat,e.UNSIGNED_BYTE,s)}),new Float32Array(s.buffer)}function downloadPackedMatrixFromBuffer(e,t,r,n,a,o,i,s){var u=e,l=new Float32Array(getPackedRGBAArraySizeFromMatrixShape(o,i));u.bindBuffer(e.ARRAY_BUFFER,t),u.getBufferSubData(e.ARRAY_BUFFER,0,l),u.bindBuffer(e.ARRAY_BUFFER,null);var p=new Float32Array(sizeFromShape([r,n,a]));return decodeMatrixFromPackedRGBA(l,r,n,a,p),p}function downloadMatrixFromPackedOutputTexture(e,t,r,n,a,o,i){var s=getPackedMatrixTextureShapeWidthHeight(a,o),u=s[0],l=s[1],p=new Float32Array(getPackedRGBAArraySizeFromMatrixShape(a,o));callAndCheck(e,function(){return e.readPixels(0,0,u,l,e.RGBA,e.FLOAT,p)});var c=new Float32Array(sizeFromShape([t,r,n]));return decodeMatrixFromPackedRGBA(p,t,r,n,c)}var gpgpu_util=Object.freeze({createVertexShader:createVertexShader$1,createVertexBuffer:createVertexBuffer,createIndexBuffer:createIndexBuffer,getTextureConfig:getTextureConfig,createFloat32MatrixTexture:createFloat32MatrixTexture,createFloat16MatrixTexture:createFloat16MatrixTexture,createUnsignedBytesMatrixTexture:createUnsignedBytesMatrixTexture,createPackedMatrixTexture:createPackedMatrixTexture,createFloat16PackedMatrixTexture:createFloat16PackedMatrixTexture,bindVertexProgramAttributeStreams:bindVertexProgramAttributeStreams,uploadPixelDataToTexture:uploadPixelDataToTexture,uploadMatrixToTexture:uploadMatrixToTexture,uploadMatrixToPackedTexture:uploadMatrixToPackedTexture,maybeCreateBufferFromOutputTexture:maybeCreateBufferFromOutputTexture,downloadFloat32MatrixFromBuffer:downloadFloat32MatrixFromBuffer,downloadFloat32MatrixFromOutputTexture:downloadFloat32MatrixFromOutputTexture,downloadByteEncodedFloatMatrixFromOutputTexture:downloadByteEncodedFloatMatrixFromOutputTexture,downloadPackedMatrixFromBuffer:downloadPackedMatrixFromBuffer,downloadMatrixFromPackedOutputTexture:downloadMatrixFromPackedOutputTexture}),GPGPUContext=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.autoDebugValidate=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[],this.gl=null!=e?e:getWebGLContext(ENV.get("WEBGL_VERSION")),1===ENV.get("WEBGL_VERSION")?(this.textureFloatExtension=getExtensionOrThrow(this.gl,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")||(this.textureHalfFloatExtension=getExtensionOrThrow(this.gl,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float"))):this.colorBufferFloatExtension=getExtensionOrThrow(this.gl,"EXT_color_buffer_float"),this.vertexBuffer=createVertexBuffer(this.gl),this.indexBuffer=createIndexBuffer(this.gl),this.framebuffer=createFramebuffer(this.gl),this.textureConfig=getTextureConfig(this.gl,this.textureHalfFloatExtension)}return e.prototype.dispose=function(){var e=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var t=this.gl;callAndCheck(t,function(){return t.finish()}),callAndCheck(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),callAndCheck(t,function(){return t.deleteFramebuffer(e.framebuffer)}),callAndCheck(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,null)}),callAndCheck(t,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)}),callAndCheck(t,function(){return t.deleteBuffer(e.indexBuffer)}),this.disposed=!0}},e.prototype.enableAutomaticDebugValidation=function(e){this.autoDebugValidate=e,enableDebugWebGLErrorChecking(e)},e.prototype.createFloat32MatrixTexture=function(e,t){return this.throwIfDisposed(),createFloat32MatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(e,t){return this.throwIfDisposed(),createFloat16MatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(e,t){return this.throwIfDisposed(),createUnsignedBytesMatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(e,t){this.throwIfDisposed(),uploadPixelDataToTexture(this.gl,e,t)},e.prototype.createFloat16PackedMatrixTexture=function(e,t){return this.throwIfDisposed(),createFloat16PackedMatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(e,t){return this.throwIfDisposed(),createPackedMatrixTexture(this.gl,e,t,this.textureConfig)},e.prototype.deleteMatrixTexture=function(e){var t=this;this.throwIfDisposed(),this.outputTexture===e&&(unbindColorTextureFromFramebuffer(this.gl,this.framebuffer),this.outputTexture=null),callAndCheck(this.gl,function(){return t.gl.deleteTexture(e)})},e.prototype.uploadMatrixToTexture=function(e,t,r,n){this.throwIfDisposed();var a=getNumChannels();return uploadMatrixToTexture(this.gl,e,t,r,n,a,this.textureConfig)},e.prototype.uploadMatrixToPackedTexture=function(e,t,r,n,a,o,i){return this.throwIfDisposed(),uploadMatrixToPackedTexture(this.gl,e,t,r,n,a,o,i,this.textureConfig)},e.prototype.downloadFloat32MatrixFromOutputTexture=function(e,t,r){var n=this;return this.downloadMatrixDriver(e,function(){return downloadFloat32MatrixFromOutputTexture(n.gl,t,r,n.textureConfig)})},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(e,t,r){var n=this;return this.downloadMatrixDriver(e,function(){return downloadByteEncodedFloatMatrixFromOutputTexture(n.gl,t,r,n.textureConfig)})},e.prototype.downloadPackedMatrixFromBuffer=function(e,t,r,n,a,o){return downloadPackedMatrixFromBuffer(this.gl,e,t,r,n,a,o,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(e,t,r){return downloadFloat32MatrixFromBuffer(this.gl,e,t,r,this.textureConfig)},e.prototype.maybeCreateBufferFromTexture=function(e,t,r){this.bindTextureToFrameBuffer(e);var n=maybeCreateBufferFromOutputTexture(this.gl,e,t,r,this.textureConfig);return this.unbindTextureToFrameBuffer(),n},e.prototype.createAndWaitForFence=function(){var e=this.createFence(this.gl);return this.pollFence(e)},e.prototype.createFence=function(e){var t,r,n=this;if(ENV.get("WEBGL_FENCE_API_ENABLED")){var a=e,o=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=function(){var e=a.clientWaitSync(o,0,0);return e===a.ALREADY_SIGNALED||e===a.CONDITION_SATISFIED},t=o}else ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),r=function(){return n.isQueryAvailable(t,ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):r=function(){return!0};return{query:t,isFencePassed:r}},e.prototype.downloadMatrixFromPackedTexture=function(e,t,r,n,a,o){var i=this;return this.downloadMatrixDriver(e,function(){return downloadMatrixFromPackedOutputTexture(i.gl,t,r,n,a,o,i.textureConfig)})},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,r=createFragmentShader(t,e),n=createVertexShader$1(t),a=createProgram(t);return callAndCheck(t,function(){return t.attachShader(a,n)}),callAndCheck(t,function(){return t.attachShader(a,r)}),linkProgram(t,a),this.autoDebugValidate&&validateProgram(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=bindVertexProgramAttributeStreams(t,this.program,this.vertexBuffer)),a},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&callAndCheck(this.gl,function(){return t.gl.deleteProgram(e)})},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.autoDebugValidate&&validateProgram(this.gl,this.program),callAndCheck(this.gl,function(){return t.gl.useProgram(e)})},e.prototype.getUniformLocation=function(e,t,r){return void 0===r&&(r=!0),this.throwIfDisposed(),r?getProgramUniformLocationOrThrow(this.gl,e,t):getProgramUniformLocation(this.gl,e,t)},e.prototype.getAttributeLocation=function(e,t){var r=this;return this.throwIfDisposed(),callAndCheck(this.gl,function(){return r.gl.getAttribLocation(e,t)})},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)},e.prototype.setInputMatrixTexture=function(e,t,r){this.throwIfDisposed(),this.throwIfNoProgram(),bindTextureToProgramUniformSampler(this.gl,this.program,e,t,r)},e.prototype.setOutputMatrixTexture=function(e,t,r){this.setOutputMatrixTextureDriver(e,r,t)},e.prototype.setOutputPackedMatrixTexture=function(e,t,r){this.throwIfDisposed();var n=getPackedMatrixTextureShapeWidthHeight(t,r),a=n[0],o=n[1];this.setOutputMatrixTextureDriver(e,a,o)},e.prototype.setOutputMatrixWriteRegion=function(e,t,r,n){this.setOutputMatrixWriteRegionDriver(r,e,n,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,r,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&validateProgram(this.gl,this.program),validateFramebuffer(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.autoDebugValidate&&this.debugValidate(),callAndCheck(e,function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),callAndCheck(this.gl,function(){return e.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=getExtensionOrThrow(this.gl,2===ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),r=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,r),r}var n=this.getQueryTimerExtensionWebGL1(),a=n.createQueryEXT();return n.beginQueryEXT(n.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var t=this.gl,r=this.getQueryTimerExtensionWebGL2();t.endQuery(r.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(r){switch(r.label){case 0:return[4,repeatedTry(function(){return t.disposed||t.isQueryAvailable(e,ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return r.sent(),[2,this.getQueryTime(e,ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var r=this.gl;return r.getQueryParameter(e,r.QUERY_RESULT)/1e6}var n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var r=this.gl,n=this.getQueryTimerExtensionWebGL2(),a=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}return a=(n=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint},e.prototype.pollFence=function(e){var t=this;return new Promise(function(r){t.addItemToPoll(function(){return e.isFencePassed()},function(){return r()})})},e.prototype.pollItems=function(){for(var e=binSearchLastTrue(this.itemsToPoll.map(function(e){return e.isDoneFn})),t=0;t<=e;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(e+1)},e.prototype.addItemToPoll=function(e,t){var r=this;this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||repeatedTry(function(){return r.pollItems(),0===r.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),bindColorTextureToFramebuffer(this.gl,e,this.framebuffer),this.autoDebugValidate&&validateFramebuffer(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(bindColorTextureToFramebuffer(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&validateFramebuffer(this.gl)):unbindColorTextureFromFramebuffer(this.gl,this.framebuffer)},e.prototype.downloadMatrixDriver=function(e,t){this.bindTextureToFrameBuffer(e);var r=t();return this.unbindTextureToFrameBuffer(),r},e.prototype.setOutputMatrixTextureDriver=function(e,t,r){this.throwIfDisposed();var n=this.gl;bindColorTextureToFramebuffer(n,e,this.framebuffer),this.autoDebugValidate&&validateFramebuffer(n),this.outputTexture=e,callAndCheck(n,function(){return n.viewport(0,0,t,r)}),callAndCheck(n,function(){return n.scissor(0,0,t,r)})},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,r,n){var a=this;this.throwIfDisposed(),callAndCheck(this.gl,function(){return a.gl.scissor(e,t,r,n)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function binSearchLastTrue(e){for(var t=0,r=e.length-1,n=-1;t<=r;){var a=t+r>>1;e[a]()?(n=a,t=a+1):r=a-1}return n}function compileProgram(e,t,r,n){for(var a=t.userCode,o=r.map(function(e,r){var n={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked};return{name:t.variableNames[r],shapeInfo:n}}),i=o.map(function(e){return e.shapeInfo}),s={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked},u=makeShader(o,s,a,!0===t.supportsBroadcasting,t.usesPackedTextures),l=e.createProgram(u),p={},c=0;c= "+e[1]+" || pos >= "+e[0]+") continue;\n\n int offsetY = int(blockIndex / ("+u+")) * "+i+" - "+d+";\n int d0 = offsetY + "+p+" * (pos / "+h+");\n\n if(d0 >= "+t[0]+" || d0 < 0) continue;\n\n int offsetX = int(mod(float(blockIndex), "+u+".) * "+o+". - "+c+".);\n int d1 = offsetX + "+l+" * (int(mod(float(pos), "+h+".) / "+a+".));\n\n if(d1 >= "+t[1]+" || d1 < 0) continue;\n\n result[row * 2 + col] = getA(d0, d1, int(mod(float(pos), "+a+".)));\n }\n }\n\n gl_FragColor = result;\n }\n "},LRNProgram=function(e,t,r,n,a){this.variableNames=["x"],this.outputShape=[];var o,i=t,s=e[3]-1;this.outputShape=e;var u="float("+r+") + float("+n+") * sum";o=.5===a?"inversesqrt("+u+")":1===a?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+i+"; j <= "+i+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+o+";\n setOutput(val);\n }\n "},LRNGradProgram=function(e,t,r,n,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=r,this.alpha=n,this.beta=a,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+t+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+t+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+n+") * norm + float("+r+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+n+")\n * float("+a+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+a+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "},MaxPool2DBackpropProgram=function(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.strideHeight,r=e.strideWidth,n=e.dilationHeight,a=e.effectiveFilterHeight,o=e.effectiveFilterWidth,i=a-1-e.padInfo.top,s=o-1-e.padInfo.left,u=a*o-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+a+";\n wR += "+n+") {\n float dyR = float(dyRCorner + wR) / "+t+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+o+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+o+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},MatMulProgram=function(e,t,r,n){void 0===r&&(r=!1),void 0===n&&(n=!1),this.variableNames=["matrixA","matrixB"];var a=e[0],o=r?e[2]:e[1],i=n?t[1]:t[2],s=r?e[1]:e[2];this.outputShape=[a,o,i];var u=function(e,t){return r?"batch, "+t+" + "+e+", aRow":"batch, aRow, "+t+" + "+e},l=function(e,t){return n?"batch, bCol, "+t+" + "+e:"batch, "+t+" + "+e+", bCol"},p=4*Math.floor(s/4),c=s%4;this.userCode=" float dotARowBCol(int batch, int aRow, int bCol) {\n float result = 0.0;\n for (int i = 0; i < "+p+"; i += 4) {\n vec4 a = vec4(\n getMatrixA("+u(0,"i")+"),\n getMatrixA("+u(1,"i")+"),\n getMatrixA("+u(2,"i")+"),\n getMatrixA("+u(3,"i")+")\n );\n vec4 b = vec4(\n getMatrixB("+l(0,"i")+"),\n getMatrixB("+l(1,"i")+"),\n getMatrixB("+l(2,"i")+"),\n getMatrixB("+l(3,"i")+")\n );\n\n result += dot(a, b);\n }\n\n if ("+(1===c)+") {\n result += getMatrixA("+u(0,p)+") *\n getMatrixB("+l(0,p)+");\n } else if ("+(2===c)+") {\n vec2 a = vec2(\n getMatrixA("+u(0,p)+"),\n getMatrixA("+u(1,p)+")\n );\n vec2 b = vec2(\n getMatrixB("+l(0,p)+"),\n getMatrixB("+l(1,p)+")\n );\n result += dot(a, b);\n } else if ("+(3===c)+") {\n vec3 a = vec3(\n getMatrixA("+u(0,p)+"),\n getMatrixA("+u(1,p)+"),\n getMatrixA("+u(2,p)+")\n );\n vec3 b = vec3(\n getMatrixB("+l(0,p)+"),\n getMatrixB("+l(1,p)+"),\n getMatrixB("+l(2,p)+")\n );\n result += dot(a, b);\n }\n\n return result;\n }\n\n void main() {\n ivec3 resBRC = getOutputCoords();\n setOutput(dotARowBCol(resBRC.x, resBRC.y, resBRC.z));\n }\n "},MatMulPackedProgram=function(e,t,r,n,a){void 0===n&&(n=!1),void 0===a&&(a=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=r;var o=n?e[0]:e[1],i=Math.ceil(o/2),s=n?"i * 2, rc.x":"rc.x, i * 2",u=a?"rc.y, i * 2":"i * 2, rc.y",l=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],p=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];this.userCode="\n const float sharedDimension = "+i+".0;\n\n vec4 dot2x2ARowBCol(ivec2 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+i+"; i++) {\n vec4 a = getMatrixA("+s+");\n vec4 b = getMatrixB("+u+");\n\n result += ("+l[0]+" * "+p[0]+") + ("+l[1]+" * "+p[1]+");\n }\n return result;\n }\n\n void main() {\n ivec2 rc = getOutputCoords();\n setOutput(dot2x2ARowBCol(rc));\n }\n "},MultinomialProgram=function(){function e(e,t,r){this.variableNames=["probs"],this.outputShape=[e,r],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(t-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(t-1)+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(r,n){null==t.seedLoc&&(t.seedLoc=r.getUniformLocation(n,"seed")),r.gl.uniform1f(t.seedLoc,e)}},e}(),OneHotProgram=function(e,t,r,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+n+"), float("+r+"),\n float(index == coords.y)));\n }\n "};function getVecChannels(e,t){return["x","y","z","w","u","v"].slice(0,t).map(function(t){return e+"."+t})}function getChannels(e,t){return 1===t?[e]:getVecChannels(e,t)}function getSourceCoords$1(e,t){if(1===e)return"rc";for(var r="",n=0;n "+t[0];for(var n="",a=e-2;a= "+t[a],a= "+t+";\n bool rEdge = rp1 >= "+r+";\n "}function getOutput(e,t){var r=e.length,n=getSourceCoordsArr(r,t);return 1===r?"getA(rc),\n rc + 1 >= "+e[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+n[0]+"),\n cEdge ? 0. : getA("+n[1]+"),\n rEdge ? 0. : getA("+n[2]+"),\n rEdge || cEdge ? 0. : getA("+n[3]+")"}var PadProgram=function(e,t,r){this.variableNames=["x"],this.outputShape=t.map(function(t,r){return t[0]+e[r]+t[1]});var n=e.length,a=getCoordsDataType(n),o=t.map(function(e){return e[0]}).join(","),i=t.map(function(t,r){return t[0]+e[r]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);this.userCode=1!==n?"\n "+a+" start = "+a+"("+o+");\n "+a+" end = "+a+"("+i+");\n\n void main() {\n "+a+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+r+"));\n } else {\n "+a+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+o+";\n int end = "+i+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+r+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Pool2DProgram=function(e,t,r){if(this.variableNames=["x"],"avg"===t&&r)throw new Error("Cannot compute positions for average pool.");var n=e.filterWidth,a=e.strideHeight,o=e.strideWidth,i=e.dilationHeight,s=e.dilationWidth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,p=e.padInfo.top,c=e.padInfo.left;this.outputShape=e.outShape;var d="avg"===t,h="0.0";if(d||(h="-1.0 / 0.0"),r)this.userCode="\n const ivec2 strides = ivec2("+a+", "+o+");\n const ivec2 pads = ivec2("+p+", "+c+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+i+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+l+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var f=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(f="avgValue / count");var m=4*Math.floor(n/4),g=n%4,y="\n if ("+d+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+a+", "+o+");\n const ivec2 pads = ivec2("+p+", "+c+");\n const float initializationValue = "+h+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+e.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+h+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+i+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+y+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+y+"\n } else if ("+(2===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+y+"\n } else if ("+(3===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+y+"\n }\n }\n setOutput("+f+");\n }\n "}},ReduceProgram=function(e,t){this.variableNames=["x"];var r=e.windowSize,n=e.batchSize,a=e.inSize,o=Math.ceil(a/r);this.outputShape=[n,o];var i="0.0",s="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 0.0",s="min"):"max"===t&&(i="-1.0 / 0.0",s="max");var u=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===t?u="sumValue":"prod"===t?u="prodValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");var l=4*Math.floor(r/4),p=r%4,c="\n if ("+("sum"===t)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===t)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",d="vec4";"all"===t?(i="1.0",c="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",d="bvec4"):"any"===t&&(i="0.0",c="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",d="bvec4");var h="";a%r>0&&(h="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+i+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+h+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n vec4 minMaxValue = vec4("+i+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; i += 4) {\n int inIdx = inOffset + i;\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+c+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===p)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+c+"\n } else if ("+(2===p)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+c+"\n } else if ("+(3===p)+") {\n "+d+" values = "+d+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+c+"\n }\n setOutput("+u+");\n }\n "},ReshapePackedProgram=function(e,t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=e;for(var r="",n=0;n<4;n++){var a="thisRC = rc;";n%2==1&&(a+="thisRC.z += 1;"),n>1&&(a+="thisRC.y += 1;"),r+="\n "+a+"\n "+(n>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+n+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(n>0?"}":"")+"\n "}this.userCode="\n "+getReshapedInputCoords(t)+"\n "+getFlatIndex(e)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+e[1]+";\n int cols = "+e[2]+";\n\n "+r+"\n\n setOutput(result);\n }\n "};function getFlatIndex(e){return"\n int getFlatIndex(ivec3 coords) {\n return round("+dotify(["coords.x","coords.y","coords.z"],computeStrides(e).map(function(e){return e.toString()}).concat(["1."]))+");\n }\n "}function getReshapedInputCoords(e){return"\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+getLogicalCoordinatesFromFlatIndex(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n "}var ResizeBilinearBackpropProgram=function(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,a=n[1],o=n[2],i=e.shape,s=i[1],u=i[2],l=[r&&s>1?a-1:a,r&&u>1?o-1:o],p=[r&&s>1?s-1:s,r&&u>1?u-1:u],c=l[0]/p[0],d=l[1]/p[1],h=1/c,f=1/d,m=2*Math.ceil(h)+2,g=2*Math.ceil(f)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+c+");\n const float widthScale = float("+d+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+f+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(a-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(o-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},ResizeBilinearProgram=function(e,t,r,n){this.variableNames=["A"],this.outputShape=[];var a=e[0],o=e[1],i=e[2],s=e[3];this.outputShape=[a,t,r,s];var u=[n&&t>1?o-1:o,n&&r>1?i-1:i],l=[n&&t>1?t-1:t,n&&r>1?r-1:r];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},ResizeNearestNeigborBackpropProgram=function(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,a=n[1],o=n[2],i=e.shape,s=i[1],u=i[2],l=[r&&s>1?a-1:a,r&&u>1?o-1:o],p=[r&&s>1?s-1:s,r&&u>1?u-1:u],c=l[0]/p[0],d=l[1]/p[1],h=1/c,f=1/d,m=2*Math.ceil(h)+2,g=2*Math.ceil(f)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+c+");\n const float widthScale = float("+d+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+f+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+p[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+p[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+a+") - 1),\n "+r+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+o+") - 1),\n "+r+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},ResizeNearestNeighborProgram=function(e,t,r,n){this.variableNames=["A"],this.outputShape=[];var a=e[0],o=e[1],i=e[2],s=e[3];this.outputShape=[a,t,r,s];var u=[n&&t>1?o-1:o,n&&r>1?i-1:i],l=[n&&t>1?t-1:t,n&&r>1?r-1:r],p=n?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+o+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+p+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},ReverseProgram=function(e,t){this.variableNames=["x"];var r=e.length;if(r>4)throw new Error("WebGL backend: Reverse of rank-"+r+" tensor is not yet supported");if(this.outputShape=e,1!==r){var n=e.map(function(r,n){return function(r){return-1!==t.indexOf(r)&&1!==e[r]?e[r]+" - coords["+r+"] - 1":"coords["+r+"]"}(n)}).join(","),a=getCoordsDataType(r);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+n+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n "},ScatterProgram=function(e,t,r,n,a,o,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var s=getCoordsDataType(a.length),u=getCoordsDataType(o.length),l="";1===r?l="i":2===r&&(l="i, j");var p="getIndices("+l+")",c="";1===n?c="i":2===n&&(c="i, coords[1]");var d="getUpdates("+c+")",h=t>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+a+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+e+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+t+"; j++) {\n int index = round("+p+");\n flattenedIndex += index * "+h+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+d+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},SegmentOpProgram=function(e,t){this.variableNames=["x","segmentIds"];var r=e.windowSize,n=e.batchSize,a=e.inSize,o=e.numSegments,i=o*Math.ceil(a/r);this.outputShape=[n,i];var s=4*Math.floor(r/4),u=r%4,l="\n sumValue += dot(values, filter);\n ",p="";a%r>0&&(p="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n ");var c="";a%r>0&&(c="\n if (inIdx < 0 || inIdx >= "+a+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+p+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+c+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+o+")) * float("+r+"));\n int currentSeg = int(mod(float(outIdx), float("+o+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+l+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(2===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(3===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+l+"\n }\n setOutput(sumValue);\n }\n "},SelectProgram=function(e,t,r){var n,a;if(this.variableNames=["c","a","b"],this.outputShape=t,r>4)throw Error("Where for rank "+r+" is not yet supported");if(1===r)a="resRC",n="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n "},SliceProgram=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t=getCoordsDataType(this.rank),r=getCoords$1(this.rank);this.userCode="\n uniform "+t+" start;\n\n void main() {\n "+t+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+r+"));\n }\n "}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(r,n){if(null!=t.startLoc||(t.startLoc=r.getUniformLocationNoThrow(n,"start"),null!=t.startLoc))if(1===t.rank)r.gl.uniform1i(t.startLoc,e[0]);else if(2===t.rank)r.gl.uniform2i(t.startLoc,e[0],e[1]);else if(3===t.rank)r.gl.uniform3i(t.startLoc,e[0],e[1],e[2]);else{if(4!==t.rank)throw Error("Slicing for rank "+t.rank+" is not yet supported");r.gl.uniform4i(t.startLoc,e[0],e[1],e[2],e[3])}}},e}();function getCoords$1(e){if(1===e)return"sourceLoc";if(2===e)return"sourceLoc.x, sourceLoc.y";if(3===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+e+" is not yet supported")}var StridedSliceProgram=function(e,t,r,n){this.variableNames=["x"];var a=r.filter(function(e,t){return-1===n.indexOf(t)});this.outputShape=a;var o=r.length,i=getCoordsDataType(r.length),s=getCoordsDataType(a.length),u="";if(1===o)u="coords * strides + begin";else{var l=0;u=r.map(function(e,t){return-1===n.indexOf(t)?(l++,1===a.length?"coords * strides["+t+"] + begin["+t+"]":"coords["+(l-1)+"] * strides["+t+"] + begin["+t+"]"):"begin["+t+"]"}).join(",")}this.userCode="\n "+i+" begin = "+i+"("+e+");\n "+i+" strides = "+i+"("+t+");\n\n void main() {\n "+s+" coords = getOutputCoords();\n setOutput(getX("+u+"));\n }\n "},TextureManager=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(e,t,r){var n,a=getPhysicalFromLogicalTextureType(t,r),o=getKeyFromTextureShape(e,a,r);if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[o].shift();return this.usedTextures[o].push(i),i}return this.numUsedTextures++,this.log(),a===PhysicalTextureType.PACKED_2X2_FLOAT32?n=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===PhysicalTextureType.PACKED_2X2_FLOAT16?n=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===PhysicalTextureType.UNPACKED_FLOAT32?n=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===PhysicalTextureType.UNPACKED_FLOAT16?n=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE&&(n=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[o].push(n),n},e.prototype.releaseTexture=function(e,t,r,n){if(null!=this.freeTextures){var a=getKeyFromTextureShape(t,getPhysicalFromLogicalTextureType(r,n),n);a in this.freeTextures||(this.freeTextures[a]=[]),this.freeTextures[a].push(e),this.numFreeTextures++,this.numUsedTextures--;var o=this.usedTextures[a],i=o.indexOf(e);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(i,1),this.log()}},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var e=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});for(var t in this.usedTextures)this.usedTextures[t].forEach(function(t){e.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}();function getPhysicalFromLogicalTextureType(e,t){if(e===TextureUsage.UPLOAD)return t?PhysicalTextureType.PACKED_2X2_FLOAT32:PhysicalTextureType.UNPACKED_FLOAT32;if(e===TextureUsage.RENDER||null==e)return t?ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")?PhysicalTextureType.PACKED_2X2_FLOAT32:PhysicalTextureType.PACKED_2X2_FLOAT16:ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")?PhysicalTextureType.UNPACKED_FLOAT32:PhysicalTextureType.UNPACKED_FLOAT16;if(e===TextureUsage.DOWNLOAD||e===TextureUsage.PIXELS)return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+e)}function getKeyFromTextureShape(e,t,r){return e[0]+"_"+e[1]+"_"+t+"_"+r}var TileProgram=function(e,t){this.variableNames=["A"];for(var r=new Array(e.length),n=0;n5)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[],a=0;a6)throw Error("Transpose for rank "+t+" is not yet supported");for(var r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t),a=0;a= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";function STEP(e){return void 0===e&&(e=0),CHECK_NAN_SNIPPET$1+"\n return x > 0.0 ? 1.0 : float("+e+");\n "}var NEG="return -x;",CEIL="return ceil(x);",FLOOR="return floor(x);",SIGN="\n if (isNaN(x)) { return 0.0; }\n return sign(x);\n",ROUND="\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n",EXP="return exp(x);",EXPM1="return exp(x) - 1.0;",LOG="if (x < 0.0) return NAN;\n return log(x);",LOG1P="return log(1.0 + x);",SQRT="return sqrt(x);",RSQRT="return inversesqrt(x);",SIGMOID="return 1.0 / (1.0 + exp(-1.0 * x));",SOFTPLUS="\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n",SIN=CHECK_NAN_SNIPPET$1+"\n return sin(x);\n",COS=CHECK_NAN_SNIPPET$1+"\n return cos(x);\n",TAN="return tan(x);",ASIN="return asin(x);",ACOS="return acos(x);",ATAN=CHECK_NAN_SNIPPET$1+"\n return atan(x);\n",SINH="\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n",COSH="\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n",TANH="\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n",ASINH="return log(x + sqrt(x * x + 1.0));",ACOSH=CHECK_NAN_SNIPPET$1+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",ATANH=CHECK_NAN_SNIPPET$1+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",ERF='\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = '+ERF_P+";\n float a1 = "+ERF_A1+";\n float a2 = "+ERF_A2+";\n float a3 = "+ERF_A3+";\n float a4 = "+ERF_A4+";\n float a5 = "+ERF_A5+";\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n",SQUARE="return x * x;",RECIPROCAL="return 1.0 / x;",LOGICAL_NOT="return float(!(x >= 1.0));",TO_INT="return float(int(x));",UnpackProgram=function(e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=e;var t=e.length,r=getChannels("rc",t),n=getCoordsDataType(t),a=getSourceCoords$1(t,r),o=r.slice(-2),i=t<=1?"rc":"vec2("+o.join(",")+")";this.userCode="\n void main() {\n "+n+" rc = getOutputCoords();\n vec4 packedInput = getA("+a+");\n\n setOutput(getChannel(packedInput, "+i+"));\n }\n "};function concat1d_(e){return concat(e,0)}function concat2d_(e,t){return concat(e,t)}function concat3d_(e,t){return concat(e,t)}function concat4d_(e,t){return concat(e,t)}function concat_(e,t){void 0===t&&(t=0),assert(e.length>=1,"Pass at least one tensor to concat");var r=convertToTensorArray(e,"tensors","concat");t=parseAxisParam(t,r[0].shape)[0];var n=computeOutShape(r.map(function(e){return e.shape}),t);if(0===sizeFromShape(n))return tensor([],n);if(1===(r=r.filter(function(e){return e.size>0})).length)return r[0];var a=r.map(function(e){return e.shape});assertParamsConsistent(a,t);var o=r;return ENV.engine.runKernel(function(e){return e.concat(r,t)},o,function(e){var r=a.map(function(e){return e[t]});return split$1(e,r,t).map(function(e){return function(){return e}})})}function split_(e,t,r){void 0===r&&(r=0);var n,a=convertToTensor(e,"x","split");return r=parseAxisParam(r,a.shape)[0],"number"==typeof t?(assert(a.shape[r]%t==0,"Number of splits must evenly divide the axis."),n=Array(t).fill(a.shape[r]/t)):(assert(a.shape[r]===t.reduce(function(e,t){return e+t}),"The sum of sizes must match the size of the axis dimension."),n=t),ENV.engine.runKernel(function(e){return e.split(a,n,r)},{$x:a},function(e){return{$x:function(){return concat(e,r)}}})}var concat=op({concat_:concat_}),concat1d=op({concat1d_:concat1d_}),concat2d=op({concat2d_:concat2d_}),concat3d=op({concat3d_:concat3d_}),concat4d=op({concat4d_:concat4d_}),split$1=op({split_:split_});function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var alea=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var r=new function(e){var t,r=this,n=(t=4022871197,function(e){e=e.toString();for(var r=0;r>>0,t=(n*=t)>>>0,t+=4294967296*(n-=t)}return 2.3283064365386963e-10*(t>>>0)});r.next=function(){var e=2091639*r.s0+2.3283064365386963e-10*r.c;return r.s0=r.s1,r.s1=r.s2,r.s2=e-(r.c=0|e)},r.c=1,r.s0=n(" "),r.s1=n(" "),r.s2=n(" "),r.s0-=n(e),r.s0<0&&(r.s0+=1),r.s1-=n(e),r.s1<0&&(r.s1+=1),r.s2-=n(e),r.s2<0&&(r.s2+=1),n=null}(e),a=t&&t.state,o=r.next;return o.int32=function(){return 4294967296*r.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.alea=a}(0,e)}),xor128=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var r=new function(e){var t=this,r="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:r+=e;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xor128=a}(0,e)}),xorwow=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var r=new function(e){var t=this,r="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:r+=e;for(var n=0;n>>4),t.next()}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xorwow=a}(0,e)}),xorshift7=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var r=new function(e){var t=this;t.next=function(){var e,r,n=t.x,a=t.i;return e=n[a],r=(e^=e>>>7)^e<<24,r^=(e=n[a+1&7])^e>>>10,r^=(e=n[a+3&7])^e>>>3,r^=(e=n[a+4&7])^e<<7,e=n[a+7&7],r^=(e^=e<<13)^e<<9,n[a]=r,t.i=a+1&7,r},function(e,t){var r,n=[];if(t===(0|t))n[0]=t;else for(t=""+t,r=0;r0;--r)e.next()}(t,e)}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&(a.x&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xorshift7=a}(0,e)}),xor4096=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var r=new function(e){var t=this;t.next=function(){var e,r,n=t.w,a=t.X,o=t.i;return t.w=n=n+1640531527|0,r=a[o+34&127],e=a[o=o+1&127],r^=r<<13,e^=e<<17,r^=r>>>15,e^=e>>>12,r=a[o]=r^e,t.i=o,r+(n^n>>>16)|0},function(e,t){var r,n,a,o,i,s=[],u=128;for(t===(0|t)?(n=t,t=null):(t+="\0",n=0,u=Math.max(u,t.length)),a=0,o=-32;o>>15,n^=n<<4,n^=n>>>13,o>=0&&(i=i+1640531527|0,a=0==(r=s[127&o]^=n+i)?a+1:0);for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,o=512;o>0;--o)n=s[a+34&127],r=s[a=a+1&127],n^=n<<13,r^=r<<17,n^=n>>>15,r^=r>>>12,s[a]=n^r;e.w=i,e.X=s,e.i=a}(t,e)}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&(a.X&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xor4096=a}(0,e)}),tychei=createCommonjsModule(function(e){!function(e,t,r){function n(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var r=new function(e){var t=this,r="";t.next=function(){var e=t.b,r=t.c,n=t.d,a=t.a;return e=e<<25^e>>>7^r,r=r-n|0,n=n<<24^n>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^r,t.c=r=r-n|0,t.d=n<<16^r>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):r+=e;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.tychei=a}(0,e)}),seedrandom=createCommonjsModule(function(e){!function(t,r){var n,a=this,o=256,i=6,s="random",u=r.pow(o,i),l=r.pow(2,52),p=2*l,c=o-1;function d(e,d,g){var y=[],v=f(function e(t,r){var n,a=[],o=typeof t;if(r&&"object"==o)for(n in t)try{a.push(e(t[n],r-1))}catch(e){}return a.length?a:"string"==o?t:t+"\0"}((d=1==d?{entropy:!0}:d||{}).entropy?[e,m(t)]:null==e?function(){try{var e;return n&&(e=n.randomBytes)?e=e(o):(e=new Uint8Array(o),(a.crypto||a.msCrypto).getRandomValues(e)),m(e)}catch(e){var r=a.navigator,i=r&&r.plugins;return[+new Date,a,i,a.screen,m(t)]}}():e,3),y),x=new function(e){var t,r=e.length,n=this,a=0,i=n.i=n.j=0,s=n.S=[];for(r||(e=[r++]);a=p;)e/=2,t/=2,r>>>=1;return(e+r)/t};return b.int32=function(){return 0|x.g(4)},b.quick=function(){return x.g(4)/4294967296},b.double=b,f(m(x.S),t),(d.pass||g||function(e,t,n,a){return a&&(a.S&&h(a,x),e.state=function(){return h(x,{})}),n?(r[s]=e,t):e})(b,v,"global"in d?d.global:this==r,d.state)}function h(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function f(e,t){for(var r,n=e+"",a=0;a=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);t=this.mean+this.stdDev*a*s,r=this.mean+this.stdDev*o*s,this.truncated&&!this.isValidTruncated(t)||(n=!0)}return this.truncated&&!this.isValidTruncated(r)||(this.nextVal=this.convertValue(r)),this.convertValue(t)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}();function clone_(e){var t=convertToTensor(e,"x","clone",null);return ENV.engine.runKernel(function(e){return Tensor.make(t.shape,{dataId:t.dataId},t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})}function eye_(e,t,r,n){void 0===n&&(n="float32"),null==t&&(t=e);for(var a=buffer([e,t],n),o=e<=t?e:t,i=0;i2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);r=r||Math.random();var s=1===i?a.as2D(1,-1):a,u=ENV.engine.runKernel(function(e){return e.multinomial(s,n,t,r)},{logits2D:s});return 1===i?u.as1D():u}function oneHot_(e,t,r,n){void 0===r&&(r=1),void 0===n&&(n=0);var a=convertToTensor(e,"indices","oneHot","int32");if(t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);return ENV.engine.runKernel(function(e){return e.oneHot(a,t,r,n)},{$indices:a},function(e){return{$indices:function(){return zeros(a.shape,"float32")}}})}function fromPixels_(e,t){if(void 0===t&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return ENV.engine.fromPixels(e,t)}function toPixels(e,t){return __awaiter(this,void 0,void 0,function(){var r,n,a,o,i,s,u,l,p,c,d,h,f,m,g,y,v,x,b,w;return __generator(this,function(N){switch(N.label){case 0:if(r=convertToTensor(e,"img","toPixels"),e instanceof Tensor||(r=r.toInt()),2!==r.rank&&3!==r.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+r.rank+".");if(n=r.shape.slice(0,2),a=n[0],o=n[1],(i=2===r.rank?1:r.shape[2])>4||2===i)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+i);return s=r.min(),u=r.max(),[4,s.data()];case 1:return l=N.sent()[0],[4,u.data()];case 2:if(p=N.sent()[0],s.dispose(),u.dispose(),"float32"===r.dtype){if(l<0||p>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+l+" - "+p+"].")}else{if("int32"!==r.dtype)throw new Error("Unsupported type for toPixels: "+r.dtype+". Please use float32 or int32 tensors.");if(l<0||p>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+l+" - "+p+"].")}return[4,r.data()];case 3:for(c=N.sent(),d="float32"===r.dtype?255:1,h=new Uint8ClampedArray(o*a*4),f=0;f=1,"Pass at least one tensor to tf.stack"),1===r.length)return r[0].expandDims(t);var n=r[0].rank,a=r[0].shape,o=r[0].dtype;assert(t<=n,"Axis must be <= rank of the tensor"),r.forEach(function(e){assertShapesMatch(a,e.shape,"All tensors passed to stack must have matching shapes")}),r.forEach(function(e){assert(o===e.dtype,"All tensors passed to stack must have matching dtypes")});var i=r.map(function(e){return e.expandDims(t)});return concat(i,t)}function batchToSpaceND_(e,t,r){var n=convertToTensor(e,"x","batchToSpaceND"),a=t.reduce(function(e,t){return e*t});return assert(n.rank>=1+t.length,"input rank is "+n.rank+" but should be > than blockShape.length "+t.length),assert(r.length===t.length,"crops.length is "+r.length+" but should be equal to blockShape.length "+t.length),assert(n.shape[0]%a==0,"input tensor batch is "+n.shape[0]+" but is not divisible by the product of the elements of blockShape "+t.join(" * ")+" === "+a),ENV.engine.runKernel(function(e){return e.batchToSpaceND(n,t,r)},{$x:n},function(e){return{$x:function(){return e.spaceToBatchND(t,r)}}})}function spaceToBatchND_(e,t,r){var n=convertToTensor(e,"x","spaceToBatchND");return assert(n.rank>=1+t.length,"input rank "+n.rank+" should be > than [blockShape] "+t.length),assert(r.length===t.length,"paddings.shape[0] "+r.length+" must be equal to [blockShape] "+t.length),assert(n.shape.reduce(function(e,n,a){return a>0&&a<=t.length?e&&(n+r[a-1][0]+r[a-1][1])%t[a-1]==0:e},!0),"input spatial dimensions "+n.shape.slice(1)+" with paddings "+r.toString()+" must be divisible by blockShapes "+t.toString()),ENV.engine.runKernel(function(e){return e.spaceToBatchND(n,t,r)},{$x:n},function(e){return{$x:function(){return e.batchToSpaceND(t,r)}}})}function unstack_(e,t){void 0===t&&(t=0);for(var r,n=convertToTensor(e,"x","unstack"),a=n.shape[t],o=Array(n.rank-1).fill(0),i=0,s=0;s=0,"Negative dimension size caused by overflow when multiplying\n "+a+" and "+t+" for depthToSpace with input shape\n "+n.shape),assert(o*t>=0,"Negative dimension size caused by overflow when multiplying\n "+o+" and "+t+" for depthToSpace with input shape\n "+n.shape),assert(i%(t*t)==0,"Dimension size must be evenly divisible by "+t*t+" but is "+i+" for depthToSpace with input shape "+n.shape),ENV.engine.runKernel(function(e){return e.depthToSpace(n,t,r)},{$x:n})}function setdiff1dAsync_(e,t){return __awaiter(this,void 0,void 0,function(){var r,n,a,o,i,s,u,l,p,c;return __generator(this,function(d){switch(d.label){case 0:return r=convertToTensor(e,"x","setdiff1d"),n=convertToTensor(t,"y","setdiff1d"),assert(r.dtype===n.dtype,"x and y should have the same dtype, but got x ("+r.dtype+") and y ("+n.dtype+")."),assert(1===r.rank,"x should be 1D tensor, but got x ("+r.shape+")."),assert(1===n.rank,"y should be 1D tensor, but got y ("+n.shape+")."),[4,r.data()];case 1:return a=d.sent(),[4,n.data()];case 2:for(o=d.sent(),i=new Set(o),s=0,p=0;p0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},e.prototype.endTimer=function(e){return ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=performance.now(),e)},e.prototype.getQueryTime=function(e){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(r){return ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(t=e).endMs-t.startMs]})})},e.prototype.disposeData=function(e){if(!this.pendingDisposal.has(e))if(this.pendingRead.has(e))this.pendingDisposal.add(e);else if(this.texData.has(e)){var t=this.texData.get(e),r=t.texture,n=t.texShape,a=t.usage,o=t.complexTensors,i=t.isPacked;null!=r&&this.releaseTexture(e,r,n,a,i),null!=o&&(o.real.dispose(),o.imag.dispose()),this.texData.delete(e)}},e.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},e.prototype.getCPUBackend=function(){return ENV.get("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=ENV.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(e,t){var r=this;return void 0===t&&(t=CPU_HANDOFF_SIZE_THRESHOLD),null!=this.getCPUBackend()&&e.every(function(e){return null==r.texData.get(e.dataId).texture&&e.sizeMATMUL_SHARED_DIM_THRESHOLD){r&&(e=e.transpose([0,2,1])),n&&(t=t.transpose([0,2,1]));var u=1===o?e:e.as3D(s,i,1),l=1===o?2:1,p=1===o?t.as3D(s,1,i):t;return this.multiply(u,p).sum(l,!0)}var c=upcastType(e.dtype,t.dtype);if(1===s){var d=e.as2D(e.shape[1],e.shape[2]),h=t.as2D(t.shape[1],t.shape[2]),f=new MatMulPackedProgram(d.shape,h.shape,[a,o],r,n),m=this.makePackedTensor(f.outputShape,c),g=this.compileAndRun(f,[d,h],m);return g.reshape([1,g.shape[0],g.shape[1]])}return f=new MatMulProgram(e.shape,t.shape,r,n),m=this.makeOutputArray(f.outputShape,c),this.compileAndRun(f,[e,t],m)},e.prototype.multiply=function(e,t){if("complex64"===e.dtype){var r=this.texData.get(e.dataId),n=this.texData.get(t.dataId),a=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.REAL,e.shape,t.shape),o=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.IMAG,e.shape,t.shape),i=[this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag),this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],s=this.compileAndRun(a,i),u=this.compileAndRun(o,i),l=this.complex(s,u);return s.dispose(),u.dispose(),l}if(this.shouldExecuteOnCPU([e,t]))return this.cpuBackend.multiply(e,t);var p=new BinaryOpProgram(MUL,e.shape,t.shape),c=this.makeOutputArray(p.outputShape,e.dtype);return this.compileAndRun(p,[e,t],c)},e.prototype.batchNormalization=function(e,t,r,n,a,o){var i=[e,t,r],s=null;null!=o&&(s=o.shape,i.push(o));var u=null;if(null!=a&&(u=a.shape,i.push(a)),ENV.get("WEBGL_PACK_BATCHNORMALIZATION")){var l=new BatchNormPackedProgram(e.shape,t.shape,r.shape,s,u,n);return this.compileAndRun(l,i)}var p=new BatchNormProgram(e.shape,t.shape,r.shape,s,u,n);return this.compileAndRun(p,i)},e.prototype.localResponseNormalization4D=function(e,t,r,n,a){var o=new LRNProgram(e.shape,t,r,n,a);return this.compileAndRun(o,[e])},e.prototype.LRNGrad=function(e,t,r,n,a,o,i){var s=new LRNGradProgram(t.shape,n,a,o,i);return this.compileAndRun(s,[t,r,e])},e.prototype.tile=function(e,t){var r=new TileProgram(e.shape,t);return this.compileAndRun(r,[e])},e.prototype.pad=function(e,t,r){var n=new PadProgram(e.shape,t,r);return this.compileAndRun(n,[e])},e.prototype.transpose=function(e,t){var r=new TransposeProgram(e.shape,t);return this.compileAndRun(r,[e])},e.prototype.gather=function(e,t,r){var n=new GatherProgram(e.shape,t.size,r);return this.compileAndRun(n,[e,t])},e.prototype.batchToSpaceND=function(e,t,r){assert(e.rank<=4,"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");var n=t.reduce(function(e,t){return e*t}),a=getReshaped(e.shape,t,n),o=getPermuted(a.length,t.length),i=getReshapedPermuted(e.shape,t,n),s=getSliceBeginCoords(r,t.length),u=getSliceSize(i,r,t.length);return e.reshape(a).transpose(o).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(e,t,r){assert(e.rank<=4,"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");var n=t.reduce(function(e,t){return e*t}),a=[[0,0]];a.push.apply(a,r);for(var o=1+t.length;o1,"blockSize should be > 1 for depthToSpace, but was: "+t);var n=e.shape[0],a=("NHWC"===r?e.shape[1]:e.shape[2])*t,o=("NHWC"===r?e.shape[2]:e.shape[3])*t,i=("NHWC"===r?e.shape[3]:e.shape[1])/(t*t),s=new DepthToSpaceProgram("NHWC"===r?[n,a,o,i]:[n,i,a,o],t,r);return this.compileAndRun(s,[e])},e.prototype.split=function(e,t,r){return split(e,t,r)},e.prototype.scatterND=function(e,t,r){var n=calculateShapes(t,e,r),a=n.sliceRank,o=n.numUpdates,i=n.sliceSize,s=n.strides,u=n.outputSize,l=[u/i,i],p=e.reshape([o,a]),c=t.reshape([o,i]);if(0===u)return reshapeTensor(tensor([]),r);var d=scalar(0),h=new ScatterProgram(o,a,p.rank,c.rank,s,l);return this.compileAndRun(h,[c,p,d]).reshape(r)},e.prototype.sparseToDense=function(e,t,r,n){var a=calculateShapes(t,e,r),o=a.sliceRank,i=a.numUpdates,s=a.strides,u=a.outputSize,l=new ScatterProgram(i,o,e.rank,t.rank,s,[u,1],!1);return this.compileAndRun(l,[t,e,n]).reshape(r)},e.prototype.fft=function(e){return this.fftImpl(e,!1)},e.prototype.ifft=function(e){return this.fftImpl(e,!0)},e.prototype.fftImpl=function(e,t){var r=this.texData.get(e.dataId),n=new FFTProgram(COMPLEX_FFT.REAL,e.shape,t),a=new FFTProgram(COMPLEX_FFT.IMAG,e.shape,t),o=[this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],i=this.compileAndRun(n,o),s=this.compileAndRun(a,o),u=this.complex(i,s).as2D(e.shape[0],e.shape[1]);return i.dispose(),s.dispose(),u},e.prototype.gatherND=function(e,t){var r=t.shape,n=r[r.length-1],a=prepareAndValidate(e,t),o=a[0],i=a[1],s=a[2],u=a[3],l=t.reshape([i,n]),p=e.reshape([e.size/s,s]),c=new GatherNDProgram(n,u,[i,s]);return this.compileAndRun(c,[p,l]).reshape(o)},e.prototype.makeOutputArray=function(e,t){return Tensor.make(e,{},t)},e.prototype.makePackedTensor=function(e,t){var r=Tensor.make(e,{},t);return this.texData.get(r.dataId).isPacked=!0,r},e.prototype.unpackTensor=function(e){var t=new UnpackProgram(e.shape);return this.compileAndRun(t,[e],Tensor.make(t.outputShape,{},e.dtype))},e.prototype.getBatchDim=function(e,t){return void 0===t&&(t=2),sizeFromShape(e.slice(0,e.length-t))},e.prototype.getRowsCols=function(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]},e.prototype.packedReshape=function(e,t){var r=e.reshape([this.getBatchDim(e.shape)].concat(this.getRowsCols(e.shape))),n=[this.getBatchDim(t)].concat(this.getRowsCols(t)),a=new ReshapePackedProgram(n,r.shape);return this.compileAndRun(a,[r]).reshape(t)},e.prototype.compileAndRun=function(e,t,r,n,a){var o=this;if(void 0===a&&(a=!0),null==r&&(r=e.usesPackedTextures?this.makePackedTensor(e.outputShape,t[0].dtype):this.makeOutputArray(e.outputShape,t[0].dtype)),0===r.size)return this.texData.get(r.dataId).values=getTypedArrayFromDType(r.dtype,0),r;var i=t.map(function(t){if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var r=o.texData.get(t.dataId);if(null==r.texture){if(!e.usesPackedTextures&&sizeFromShape(t.shape)<=ENV.get("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:o.readSync(t.dataId)};e.usesPackedTextures&&(r.isPacked=!0,r.shape=t.shape)}else if(!!r.isPacked!=!!e.usesPackedTextures){var n=void 0,a=void 0;r.isPacked?(n=new UnpackProgram(t.shape),a=o.compileAndRun(n,[t],Tensor.make(n.outputShape,{},t.dtype))):(n=new PackProgram(t.shape),a=o.compileAndRun(n,[t],o.makePackedTensor(t.shape,t.dtype))),r=o.texData.get(a.dataId),t=a}else if(r.isPacked&&!isReshapeFree(r.shape,t.shape)){o.delayedStorage=!1;var i=t.dataSync();o.delayedStorage=!0,t=Tensor.make(t.shape,{values:i},t.dtype),(r=o.texData.get(t.dataId)).isPacked=!0}return o.uploadToGPU(t.dataId),{shape:t.shape,texData:r,isUniform:!1}});this.uploadToGPU(r.dataId);var s,u={shape:r.shape,texData:this.texData.get(r.dataId),isUniform:!1},l=makeShaderKey(e,i,u),p=this.getAndSaveBinary(l,function(){return compileProgram(o.gpgpu,e,i,u)}),c=null!=this.activeTimers;if(c&&(s=this.startTimer()),runProgram(p,i,u,n),ENV.get("WEBGL_PAGING_ENABLED")&&a&&this.numBytesInGPU>this.NUM_BYTES_BEFORE_PAGING)for(var d=this.numBytesInGPU-this.NUM_BYTES_BEFORE_PAGING;d>0&&this.lruDataGPU.length>0;){var h=this.lruDataGPU.shift(),f=this.texData.get(h),m=f.shape,g=f.dtype;d-=this.computeBytes(m,g),this.read(h)}return c&&(s=this.endTimer(s),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(s)})),ENV.get("WEBGL_LAZILY_UNPACK")||!this.texData.get(r.dataId).isPacked||e.isPackShader?r:this.unpackTensor(r)},e.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){if(!this.disposed){for(var e in this.binaryCache)this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram);this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixels2DContext&&this.fromPixels2DContext.canvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0}},e.prototype.floatPrecision=function(){var e=this;return tidy(function(){return e.abs(scalar(1e-8)).get()>0?32:16})},e.prototype.uploadToGPU=function(e){var t,r=this.texData.get(e),n=r.shape,a=r.values,o=r.texture,i=r.usage,s=r.isPacked;if(null==o){var u,l=null!=this.activeTimers;l&&(u=performance.now());var p=getTextureShapeFromLogicalShape(n,s);r.texShape=p;var c=this.acquireTexture(e,p,i,s);if(r.texture=c,null!=a){if(s){var d=this.getBatchDim(n),h=1,f=1;n.length&&(h=(t=this.getRowsCols(n))[0],f=t[1]),this.gpgpu.uploadMatrixToPackedTexture(c,d,h,f,p[0],p[1],typedArrayToFloat32(a))}else this.gpgpu.uploadMatrixToTexture(c,p[0],p[1],typedArrayToFloat32(a));r.values=null,l&&(this.uploadWaitMs+=performance.now()-u)}}else ENV.get("WEBGL_PAGING_ENABLED")&&this.lruDataGPU.indexOf(e)>=0&&(this.lruDataGPU.splice(this.lruDataGPU.indexOf(e),1),this.lruDataGPU.push(e))},e.prototype.convertAndCacheOnCPU=function(e,t){var r=this.delayedStorage,n=this.texData.get(e),a=n.texture,o=n.texShape,i=n.dtype,s=n.usage,u=n.isPacked;return r&&null!=a&&(this.releaseTexture(e,a,o,s,u),n.texture=null,n.texShape=null),n.usage=TextureUsage.UPLOAD,null!=t&&(n.values=float32ToTypedArray(t,i)),n.values},e.prototype.releaseTexture=function(e,t,r,n,a){var o=this.texData.get(e),i=o.shape,s=o.dtype;if(ENV.get("WEBGL_PAGING_ENABLED")){var u=this.lruDataGPU.indexOf(e);u>=0&&this.lruDataGPU.splice(u,1)}this.numBytesInGPU-=this.computeBytes(i,s),this.textureManager.releaseTexture(t,r,n,a)},e.prototype.acquireTexture=function(e,t,r,n){var a=this.texData.get(e),o=a.shape,i=a.dtype;return ENV.get("WEBGL_PAGING_ENABLED")&&this.lruDataGPU.push(e),this.numBytesInGPU+=this.computeBytes(o,i),this.textureManager.acquireTexture(t,r,n)},e.prototype.computeBytes=function(e,t){return sizeFromShape(e)*bytesPerElement(t)},e}();function float32ToTypedArray(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){for(var r="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),n=0;n=2&&i.rank>=2&&o.rank===i.rank,"Error in matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+i.rank+"."),assert(arraysEqual(c,d),"Error in matMul: outer dimensions ("+c+") and ("+d+") of Tensors with shapes "+o.shape+" and "+i.shape+" must match."),assert(s===u,"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+o.shape+" and "+i.shape+" and transposeA="+r+" and transposeB="+n+" must match.");var m=o.shape.slice(0,-2).concat([l,p]),g=r?o.as3D(h,s,l):o.as3D(h,l,s),y=n?i.as3D(f,p,u):i.as3D(f,u,p);return ENV.engine.runKernel(function(e){return e.batchMatMul(g,y,r,n)},{$a:g,$b:y},function(e){return r||n?!r&&n?{$a:function(){return e.matMul(y,!1,!1)},$b:function(){return e.matMul(g,!0,!1)}}:r&&!n?{$a:function(){return y.matMul(e,!1,!0)},$b:function(){return g.matMul(e,!1,!1)}}:{$a:function(){return y.matMul(e,!0,!0)},$b:function(){return e.matMul(g,!0,!0)}}:{$a:function(){return e.matMul(y,!1,!0)},$b:function(){return g.matMul(e,!0,!1)}}}).reshape(m)}function outerProduct_(e,t){var r=convertToTensor(e,"v1","outerProduct"),n=convertToTensor(t,"v2","outerProduct");return assert(1===r.rank&&1===n.rank,"Error in outerProduct: inputs must be rank 1, but got ranks "+r.rank+" and "+n.rank+"."),r.as2D(-1,1).matMul(n.as2D(1,-1))}function dot_(e,t){var r=convertToTensor(e,"t1","dot"),n=convertToTensor(t,"t2","dot");assert(!(1!==r.rank&&2!==r.rank||1!==n.rank&&2!==n.rank),"Error in dot: inputs must all be rank 1 or 2, but got ranks "+r.rank+" and "+n.rank+".");var a=1===r.rank?r.size:r.shape[1],o=1===n.rank?n.size:n.shape[0];return assert(a===o,"Error in dot: inner dimensions of inputs must match, but got "+a+" and "+o+"."),1===r.rank&&1===n.rank?r.as2D(1,-1).matMul(n.as2D(-1,1)).asScalar():1===r.rank&&2===n.rank?r.as2D(1,-1).matMul(n.as2D(n.shape[0],n.shape[1])).as1D():2===r.rank&&1===n.rank?r.matMul(n.as2D(-1,1)).as1D():r.matMul(n.as2D(n.shape[0],n.shape[1]))}var matMul=op({matMul_:matMul_}),dot=op({dot_:dot_}),outerProduct=op({outerProduct_:outerProduct_});function conv1d_(e,t,r,n,a,o,i){void 0===a&&(a="NWC"),void 0===o&&(o=1);var s=convertToTensor(e,"x","conv1d"),u=convertToTensor(t,"filter","conv1d"),l=s,p=!1;2===s.rank&&(p=!0,l=s.as3D(1,s.shape[0],s.shape[1])),assert(3===l.rank,"Error in conv1d: input must be rank 3, but got rank "+l.rank+"."),assert(3===u.rank,"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."),null!=i&&assert(isInt(n),"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+n+"."),assert(l.shape[2]===u.shape[1],"Error in conv1d: depth of input ("+l.shape[2]+") must match input depth for filter "+u.shape[1]+"."),assert(eitherStridesOrDilationsAreOne(r,o),"Error in conv1D: Either stride or dilation must be 1. Got stride "+r+" and dilation '"+o+"'"),assert("NWC"===a,"Error in conv1d: got dataFormat of "+a+" but only NWC is currently supported.");var c=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),d=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),h=conv2d(d,c,[1,r],n,"NHWC",[1,o],i);return p?h.as2D(h.shape[2],h.shape[3]):h.as3D(h.shape[0],h.shape[2],h.shape[3])}function conv2d_(e,t,r,n,a,o,i){void 0===a&&(a="NHWC"),void 0===o&&(o=[1,1]);var s=convertToTensor(e,"x","conv2d"),u=convertToTensor(t,"filter","conv2d"),l=s,p=!1;3===s.rank&&(p=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),assert(4===l.rank,"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."),assert(4===u.rank,"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."),null!=i&&assert(isInt(n),"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+n+"."),assert(l.shape[3]===u.shape[2],"Error in conv2d: depth of input ("+l.shape[3]+") must match input depth for filter "+u.shape[2]+"."),assert(eitherStridesOrDilationsAreOne(r,o),"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"),assert("NHWC"===a,"Error in conv2d: got dataFormat of "+a+" but only NHWC is currently supported.");var c,d=computeConv2DInfo(l.shape,u.shape,r,o,n,i);if(1!==d.filterHeight||1!==d.filterWidth||1!==d.dilationHeight||1!==d.dilationWidth||1!==d.strideHeight||1!==d.strideWidth||"SAME"!==d.padInfo.type&&"VALID"!==d.padInfo.type)c=ENV.engine.runKernel(function(e){return e.conv2d(l,u,d)},{x:l,$filter:u},function(e){return assert(tupleValuesAreOne(o),"Error in gradient of conv2D: dilation rates greater than 1 are notyet supported in gradients. Got dilations '"+o+"'"),{x:function(){return conv2dDerInput_(l.shape,e,u,r,n)},$filter:function(){return conv2dDerFilter_(l,e,u.shape,r,n)}}});else{var h=l.reshape([-1,d.inChannels]),f=u.reshape([d.inChannels,d.outChannels]);c=matMul(h,f).reshape(d.outShape)}return p?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function conv2dDerInput_(e,t,r,n,a,o){assert(e.length===t.rank,"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match");var i=e,s=t,u=!1;3===t.rank&&(u=!0,s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),i=[1,e[0],e[1],e[2]]);var l=i[3],p=s.shape[3];assert(4===i.length,"Error in conv2dDerInput: inShape must be length 4, but got length "+i.length+"."),assert(4===s.rank,"Error in conv2dDerInput: dy must be rank 4, but got rank "+s.rank),assert(4===r.rank,"Error in conv2dDerInput: filter must be rank 4, but got rank "+r.rank),assert(l===r.shape[2],"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+r.shape[2]+"."),assert(p===r.shape[3],"Error in conv2dDerInput: depth of output ("+p+") must match output depth for filter "+r.shape[3]+"."),null!=o&&assert(isInt(a),"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+".");var c=computeConv2DInfo(i,r.shape,n,1,a,o),d=ENV.engine.runKernel(function(e){return e.conv2dDerInput(s,r,c)},{dy4D:s,filter:r},function(e){return{dy4D:function(){return conv2d(e,r,n,a,"NHWC",1,o)},filter:function(){return conv2dDerFilter(e,s,r.shape,n,a,o)}}});return u?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function conv2dDerFilter_(e,t,r,n,a,o){var i=e;3===e.rank&&(i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var s=t;3===s.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),assert(4===i.rank,"Error in conv2dDerFilter: input must be rank 4, but got shape "+i.shape+"."),assert(4===s.rank,"Error in conv2dDerFilter: dy must be rank 4, but got shape "+s.shape+"."),assert(4===r.length,"Error in conv2dDerFilter: filterShape must be length 4, but got "+r+"."),assert(i.shape[3]===r[2],"Error in conv2dDerFilter: depth of input "+i.shape[3]+") must match input depth in filter ("+r[2]+"."),assert(s.shape[3]===r[3],"Error in conv2dDerFilter: depth of dy ("+s.shape[3]+") must match output depth for filter ("+r[3]+")."),null!=o&&assert(isInt(a),"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+".");var u=computeConv2DInfo(i.shape,r,n,1,a,o);return ENV.engine.runKernel(function(e){return e.conv2dDerFilter(i,s,u)},{x4D:i,dy4D:s})}function conv2dTranspose_(e,t,r,n,a,o){return conv2dDerInput_(r,convertToTensor(e,"x","conv2dTranspose"),convertToTensor(t,"filter","conv2dTranspose"),n,a,o)}function depthwiseConv2d_(e,t,r,n,a,o,i){void 0===a&&(a="NHWC"),void 0===o&&(o=[1,1]);var s=convertToTensor(e,"x","depthwiseConv2d"),u=convertToTensor(t,"filter","depthwiseConv2d"),l=s,p=!1;3===s.rank&&(p=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),assert(4===l.rank,"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."),assert(4===u.rank,"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."),assert(l.shape[3]===u.shape[2],"Error in depthwiseConv2d: number of input channels ("+l.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."),null==o&&(o=[1,1]),assert(eitherStridesOrDilationsAreOne(r,o),"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"),null!=i&&assert(isInt(n),"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+n+".");var c=computeConv2DInfo(l.shape,u.shape,r,o,n,i,!0),d=ENV.engine.runKernel(function(e){return e.depthwiseConv2D(l,u,c)},{x:l,$filter:u},function(e){return assert(tupleValuesAreOne(o),"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+o+"'"),{x:function(){return depthwiseConv2dDerInput(l.shape,e,u,c)},$filter:function(){return depthwiseConv2dDerFilter(l,e,u.shape,c)}}});return p?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function separableConv2d_(e,t,r,n,a,o,i){void 0===o&&(o=[1,1]),void 0===i&&(i="NHWC");var s=convertToTensor(e,"x","separableConv2d"),u=convertToTensor(t,"depthwiseFilter","separableConv2d"),l=convertToTensor(r,"pointwiseFilter","separableConv2d"),p=s,c=!1;if(3===s.rank&&(c=!0,p=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");assert(4===p.rank,"Error in separableConv2d: input must be rank 4, but got rank "+p.rank+"."),assert(4===u.rank,"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."),assert(4===l.rank,"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."),assert(1===l.shape[0],"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+l.shape[0]+"."),assert(1===l.shape[1],"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+".");var d=u.shape[2],h=u.shape[3];assert(l.shape[2]===d*h,"Error in separableConv2d: the third dimension of pointwise filter must be "+d*h+", but got "+l.shape[2]+".");var f=depthwiseConv2d(p,u,n,a,i,o),m=conv2d(f,l,1,"valid",i);return c?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}function parseTupleParam$1(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function tupleValuesAreOne$1(e){var t=parseTupleParam$1(e),r=t[0],n=t[1],a=t[2];return 1===r&&1===n&&1===a}function eitherStridesOrDilationsAreOne$1(e,t){return tupleValuesAreOne$1(e)||tupleValuesAreOne$1(t)}function depthwiseConv2dDerInput(e,t,r,n){var a=t,o=!1;3===t.rank&&(o=!0,a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var i=ENV.engine.runKernel(function(e){return e.depthwiseConv2DDerInput(a,r,n)},{dy4D:a});return o?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}function depthwiseConv2dDerFilter(e,t,r,n){var a=e;3===e.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var o=t;return 3===o.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),ENV.engine.runKernel(function(e){return e.depthwiseConv2DDerFilter(a,o,n)},{x4D:a,dy4D:o})}function conv3d_(e,t,r,n,a,o){void 0===a&&(a="NHWC"),void 0===o&&(o=[1,1,1]);var i=convertToTensor(e,"x","conv3d"),s=convertToTensor(t,"filter","conv3d"),u=i,l=!1;4===i.rank&&(l=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),assert(5===u.rank,"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."),assert(5===s.rank,"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."),assert(u.shape[4]===s.shape[3],"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+"."),assert(eitherStridesOrDilationsAreOne$1(r,o),"Error in conv3D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"),assert("NHWC"===a,"Error in conv3d: got dataFormat of "+a+" but only NHWC is currently supported.");var p=computeConv3DInfo(u.shape,s.shape,r,o,n),c=ENV.engine.runKernel(function(e){return e.conv3d(u,s,p)},{x:u,$filter:s},function(e){return assert(tupleValuesAreOne$1(o),"Error in gradient of conv3D: dilation rates greater than 1 are notyet supported in gradients. Got dilations '"+o+"'"),{x:function(){return conv3dDerInput_(u.shape,e,s,r,n)},$filter:function(){return conv3dDerFilter_(u,e,s.shape,r,n)}}});return l?c.as4D(c.shape[1],c.shape[2],c.shape[3],c.shape[4]):c}function conv3dDerInput_(e,t,r,n,a){assert(e.length===t.rank,"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match");var o=e,i=t,s=!1;4===t.rank&&(s=!0,i=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]),o=[1,e[0],e[1],e[2],e[3]]);var u=o[4],l=i.shape[4];assert(5===o.length,"Error in conv3dDerInput: inShape must be length 5, but got length "+o.length+"."),assert(5===i.rank,"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank),assert(5===r.rank,"Error in conv3dDerInput: filter must be rank 5, but got rank "+r.rank),assert(u===r.shape[3],"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+r.shape[3]+"."),assert(l===r.shape[4],"Error in conv3dDerInput: depth of output ("+l+") must match output depth for filter "+r.shape[4]+".");var p=computeConv3DInfo(o,r.shape,n,1,a),c=ENV.engine.runKernel(function(e){return e.conv3dDerInput(i,r,p)},{dy5D:i});return s?c.as4D(c.shape[1],c.shape[2],c.shape[3],c.shape[4]):c}function conv3dDerFilter_(e,t,r,n,a){var o=e;4===e.rank&&(o=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]));var i=t;4===i.rank&&(i=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3])),assert(5===o.rank,"Error in conv3dDerFilter: input must be rank 5, but got shape "+o.shape+"."),assert(5===i.rank,"Error in conv3dDerFilter: dy must be rank 5, but got shape "+i.shape+"."),assert(5===r.length,"Error in conv3dDerFilter: filterShape must be length 5, but got "+r+"."),assert(o.shape[4]===r[3],"Error in conv3dDerFilter: depth of input "+o.shape[4]+") must match input depth in filter ("+r[3]+"."),assert(i.shape[4]===r[4],"Error in conv3dDerFilter: depth of dy ("+i.shape[4]+") must match output depth for filter ("+r[4]+").");var s=computeConv3DInfo(o.shape,r,n,1,a);return ENV.engine.runKernel(function(e){return e.conv3dDerFilter(o,i,s)},{x5D:o,dy5D:i})}var conv1d=op({conv1d_:conv1d_}),conv2d=op({conv2d_:conv2d_}),conv3d=op({conv3d_:conv3d_}),conv2dDerFilter=op({conv2dDerFilter_:conv2dDerFilter_}),depthwiseConv2d=op({depthwiseConv2d_:depthwiseConv2d_}),separableConv2d=op({separableConv2d_:separableConv2d_}),conv2dTranspose=op({conv2dTranspose_:conv2dTranspose_});function reverse1d_(e){var t=convertToTensor(e,"x","reverse");return assert(1===t.rank,"Error in reverse1D: x must be rank 1 but got\n rank "+t.rank+"."),reverse(t,0)}function reverse2d_(e,t){var r=convertToTensor(e,"x","reverse");return assert(2===r.rank,"Error in reverse2D: x must be rank 2 but got\n rank "+r.rank+"."),reverse(r,t)}function reverse3d_(e,t){var r=convertToTensor(e,"x","reverse");return assert(3===r.rank,"Error in reverse3D: x must be rank 3 but got\n rank "+r.rank+"."),reverse(r,t)}function reverse4d_(e,t){var r=convertToTensor(e,"x","reverse");return assert(4===r.rank,"Error in reverse4D: x must be rank 4 but got\n rank "+r.rank+"."),reverse(r,t)}function reverse_(e,t){var r=convertToTensor(e,"x","reverse");if(0===r.rank)return r.clone();var n=parseAxisParam(t,r.shape);return ENV.engine.runKernel(function(e){return e.reverse(r,n)},{$x:r},function(e){return{$x:function(){return e.reverse(n)}}}).reshapeAs(r)}var reverse=op({reverse_:reverse_}),reverse1d=op({reverse1d_:reverse1d_}),reverse2d=op({reverse2d_:reverse2d_}),reverse3d=op({reverse3d_:reverse3d_}),reverse4d=op({reverse4d_:reverse4d_});function maxPoolImpl_(e,t,r,n,a,o){var i=convertToTensor(e,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==n&&(n=[1,1]),assert(4===s.rank,"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."),assert(eitherStridesOrDilationsAreOne(r,n),"Error in maxPool: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+n+"'"),null!=o&&assert(isInt(a),"Error in maxPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+".");var l=computePool2DInfo(s.shape,t,r,n,a,o),p=ENV.engine.runKernel(function(e,t){return t(e.maxPool(s,l))},{x:s},function(e,o){var i=o[0];return{x:function(){return maxPoolBackprop(e,s,i,t,r,n,a)}}});return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function maxPool_(e,t,r,n,a){return maxPoolImpl_(e,t,r,1,n,a)}function avgPoolImpl_(e,t,r,n,a,o){var i=convertToTensor(e,"x","avgPool","float32");null==n&&(n=[1,1]),assert(eitherStridesOrDilationsAreOne(r,n),"Error in avgPool: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+n+"'");var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),assert(4===s.rank,"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."),null!=o&&assert(isInt(a),"Error in avgPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+".");var l=computePool2DInfo(s.shape,t,r,n,a),p=ENV.engine.runKernel(function(e){return e.avgPool(s,l)},{x:s},function(e){return{x:function(){return avgPoolBackprop(e,s,t,r,n,a)}}});return p=p.cast(i.dtype),u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function avgPool_(e,t,r,n,a){return avgPoolImpl_(e,t,r,1,n,a)}function pool_(e,t,r,n,a,o){null==a&&(a=[1,1]),null==o&&(o=1),0===n&&(n="valid");var i=convertToTensor(e,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),assert(eitherStridesOrDilationsAreOne(o,a),"Error in pool: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'");var l,p=computePool2DInfo(s.shape,t,o,a,n),c=[p.dilationHeight,p.dilationWidth];l="same"===n?withSpaceToBatchBasePaddings([p.filterHeight,p.filterWidth],c):[[0,0],[0,0]];var d=1===c[0]&&1===c[1],h=requiredSpaceToBatchPaddings([p.inHeight,p.inWidth],c,l),f=h[0],m=h[1],g=d?n:"valid",y=d?s:spaceToBatchND(s,c,f),v=("avg"===r?function(){return avgPoolImpl_(y,t,o,1,g)}:function(){return maxPoolImpl_(y,t,o,1,g)})(),x=d?v:batchToSpaceND(v,c,m);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}function maxPoolBackprop(e,t,r,n,a,o,i,s){var u=convertToTensor(e,"dy","maxPoolBackprop"),l=convertToTensor(t,"input","maxPoolBackprop"),p=convertToTensor(r,"output","maxPoolBackprop");assert(l.rank===u.rank,"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"),null==o&&(o=[1,1]),assert(eitherStridesOrDilationsAreOne(a,o),"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"),assert(4===u.rank,"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."),assert(4===l.rank,"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."),null!=s&&assert(isInt(i),"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+".");var c=computePool2DInfo(l.shape,n,a,o,i,s);return ENV.engine.runKernel(function(e){return e.maxPoolBackprop(u,l,p,c)},{$dy:u,$input:l})}function avgPoolBackprop(e,t,r,n,a,o){var i=convertToTensor(e,"dy","avgPoolBackprop"),s=convertToTensor(t,"input","avgPoolBackprop");assert(s.rank===i.rank,"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"),null==a&&(a=[1,1]),assert(eitherStridesOrDilationsAreOne(n,a),"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'");var u=s,l=i,p=!1;3===s.rank&&(p=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),assert(4===l.rank,"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."),assert(4===u.rank,"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+".");var c=computePool2DInfo(u.shape,r,n,a,o),d=ENV.engine.runKernel(function(e){return e.avgPoolBackprop(l,u,c)},{dy4D:l,input4D:u});return p?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function requiredSpaceToBatchPaddings(e,t,r){var n=r.map(function(e){return e[0]}),a=r.map(function(e){return e[1]}),o=e.concat(n,a),i=t.map(function(e,t){return(e-o[t]%e)%e}),s=a.map(function(e,t){return e+i[t]});return[t.map(function(e,t){return[n[t],s[t]]}),t.map(function(e,t){return[0,i[t]]})]}function withSpaceToBatchBasePaddings(e,t){var r=e.map(function(e,r){return e+(e-1)*(t[r]-1)}).map(function(e){return e-1}),n=r.map(function(e){return Math.floor(e/2)}),a=r.map(function(e,t){return e-n[t]});return r.map(function(e,t){return[n[t],a[t]]})}var maxPool=op({maxPool_:maxPool_}),avgPool=op({avgPool_:avgPool_}),pool=op({pool_:pool_});function slice1d_(e,t,r){var n=convertToTensor(e,"x","slice1d");return assert(1===n.rank,"slice1d expects a rank-1 tensor, but got a rank-"+n.rank+" tensor"),slice(n,[t],[r])}function slice2d_(e,t,r){var n=convertToTensor(e,"x","slice2d");return assert(2===n.rank,"slice2d expects a rank-2 tensor, but got a rank-"+n.rank+" tensor"),slice(n,t,r)}function slice3d_(e,t,r){var n=convertToTensor(e,"x","slice3d");return assert(3===n.rank,"slice3d expects a rank-3 tensor, but got a rank-"+n.rank+" tensor"),slice(n,t,r)}function slice4d_(e,t,r){var n=convertToTensor(e,"x","slice4d");return assert(4===n.rank,"slice4d expects a rank-4 tensor, but got a rank-"+n.rank+" tensor"),slice(n,t,r)}function slice_(e,t,r){var n,a,o=convertToTensor(e,"x","slice");if(0===o.rank)throw new Error("Slicing scalar is not possible");n="number"==typeof t?[t].concat(new Array(o.rank-1).fill(0)):t.length=0?e:(assert(-1===e,"Bad value in size"),o.shape[t]-n[t])}),assertParamsValid(o,n,a);var i=o.shape;return ENV.engine.runKernel(function(e){return e.slice(o,n,a)},{$x:o},function(e){for(var t=[],r=0;r0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,r=getReductionAxes(a.shape,o);return r.length>0&&(t=t.sum(r)),t.reshape(a.shape)}}})}function addN_(e){assert(Array.isArray(e),function(){return"The argument passed to tf.addN() must be a list of tensors"}),assert(e.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+e.length});var t=e.map(function(e,t){return convertToTensor(e,"tensors"+t,"addN")}),r=t[0];t.forEach(function(e){if(e.dtype!==r.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(e){if(!arraysEqual(e.shape,r.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var n=t;return ENV.engine.runKernel(function(e){return e.addN(t)},n,function(e){var r={};return t.forEach(function(t,n){r[n]=function(){return e.clone()}}),r})}function addStrict_(e,t){var r=convertToTensor(e,"a","addStrict"),n=convertToTensor(t,"b","addStrict");return assertShapesMatch(r.shape,n.shape,"Error in addStrict: "),r.add(n)}function sub_(e,t){var r,n=convertToTensor(e,"a","sub"),a=convertToTensor(t,"b","sub");r=makeTypesMatch(n,a),n=r[0],a=r[1];var o=assertAndGetBroadcastShape(n.shape,a.shape);return ENV.engine.runKernel(function(e){return e.subtract(n,a)},{$a:n,$b:a},function(e){return{$a:function(){var t=e,r=getReductionAxes(n.shape,o);return r.length>0&&(t=t.sum(r)),t.reshape(n.shape)},$b:function(){var t=e,r=getReductionAxes(a.shape,o);return r.length>0&&(t=t.sum(r)),t.neg().reshape(a.shape)}}})}function subStrict_(e,t){var r=convertToTensor(e,"a","subStrict"),n=convertToTensor(t,"b","subStrict");return assertShapesMatch(r.shape,n.shape,"Error in subStrict: "),r.sub(n)}function pow_(e,t){var r=convertToTensor(e,"base","pow"),n=convertToTensor(t,"exp","pow"),a=assertAndGetBroadcastShape(r.shape,n.shape);return e=r.cast(upcastType(r.dtype,n.dtype)),t=n.cast(upcastType(r.dtype,n.dtype)),ENV.engine.runKernel(function(e,t){return t(e.pow(r,n))},{$base:r,$exp:n},function(e,t){var o=t[0];return{$base:function(){var t=n.toFloat(),o=e.mul(t.mul(r.pow(t.sub(scalar(1))))),i=getReductionAxes(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)},$exp:function(){var t=e.mul(o.mul(r.log()).toFloat()),i=getReductionAxes(n.shape,a);return i.length>0&&(t=t.sum(i)),t.reshape(n.shape)}}})}function powStrict_(e,t){return assertShapesMatch(e.shape,t.shape,"Error in powStrict: "),e.pow(t)}function mul_(e,t){var r,n=convertToTensor(e,"a","mul"),a=convertToTensor(t,"b","mul");r=makeTypesMatch(n,a),n=r[0],a=r[1];var o=assertAndGetBroadcastShape(n.shape,a.shape);return ENV.engine.runKernel(function(e){return e.multiply(n,a)},{$a:n,$b:a},function(e){return{$a:function(){var t=e.mul(a.toFloat()),r=getReductionAxes(n.shape,o);return r.length>0?t.sum(r).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),r=getReductionAxes(a.shape,o);return r.length>0?t.sum(r).reshape(a.shape):t}}})}function mulStrict_(e,t){var r=convertToTensor(e,"a","mul"),n=convertToTensor(t,"b","mul");return assertShapesMatch(r.shape,n.shape,"Error in multiplyStrict: "),r.mul(n)}function div_(e,t){var r,n,a=convertToTensor(e,"a","div"),o=convertToTensor(t,"b","div");if(r=makeTypesMatch(a,o),a=r[0],o=r[1],"int32"===a.dtype&&"int32"===o.dtype)return floorDiv(a,o);n=function(e){return e.realDivide(a,o)};var i=assertAndGetBroadcastShape(a.shape,o.shape);return ENV.engine.runKernel(n,{$a:a,$b:o},function(e){return{$a:function(){var t=e.div(o.toFloat()),r=getReductionAxes(a.shape,i);return r.length>0?t.sum(r).reshape(a.shape):t},$b:function(){var t=e.mul(a.toFloat()),r=getReductionAxes(o.shape,i);r.length>0&&(t=t.sum(r).reshape(o.shape));var n=o.square();return t.div(n.toFloat()).neg()}}})}function floorDiv_(e,t){var r,n=convertToTensor(e,"a","floorDiv"),a=convertToTensor(t,"b","floorDiv");r=makeTypesMatch(n,a),n=r[0],a=r[1];var o=assertAndGetBroadcastShape(n.shape,a.shape);return ENV.engine.runKernel(function(e){return e.floorDiv(n,a)},{$a:n,$b:a},function(e){return{$a:function(){var t=e.div(a.toFloat()),r=getReductionAxes(n.shape,o);return r.length>0?t.sum(r).reshape(n.shape):t},$b:function(){var t=e.mul(n.toFloat()),r=getReductionAxes(a.shape,o);r.length>0&&(t=t.sum(r).reshape(a.shape));var i=a.square();return t.div(i.toFloat()).neg()}}})}function divStrict_(e,t){var r=convertToTensor(e,"a","div"),n=convertToTensor(t,"b","div");return assertShapesMatch(r.shape,n.shape,"Error in divideStrict: "),r.div(n)}function mod_(e,t){var r,n=convertToTensor(e,"a","mod"),a=convertToTensor(t,"b","mod");r=makeTypesMatch(n,a),n=r[0],a=r[1];var o=assertAndGetBroadcastShape(n.shape,a.shape);return ENV.engine.runKernel(function(e){return e.mod(n,a)},{$a:n,$b:a},function(e){return{$a:function(){var t=getReductionAxes(n.shape,o);return t.length>0?e.sum(t).reshape(n.shape):e},$b:function(){var t=e.mul(n.div(a).floor().neg()),r=getReductionAxes(a.shape,o);return r.length>0?t.sum(r).reshape(a.shape):t}}})}function modStrict_(e,t){var r=convertToTensor(e,"a","modStrict"),n=convertToTensor(t,"b","modStrict");return assertShapesMatch(r.shape,n.shape,"Error in modStrict: "),r.mod(n)}function minimum_(e,t){var r,n=convertToTensor(e,"a","minimum"),a=convertToTensor(t,"b","minimum");return r=makeTypesMatch(n,a),n=r[0],a=r[1],"bool"===n.dtype&&(n=n.toInt(),a=a.toInt()),assertAndGetBroadcastShape(n.shape,a.shape),ENV.engine.runKernel(function(e){return e.minimum(n,a)},{$a:n,$b:a},function(e){return{$a:function(){return e.mul(n.lessEqual(a).toFloat())},$b:function(){return e.mul(n.greater(a).toFloat())}}})}function minimumStrict_(e,t){var r=convertToTensor(e,"a","minimumStrict"),n=convertToTensor(t,"b","minimumStrict");return assertShapesMatch(r.shape,n.shape,"Error in minimumStrict: "),r.minimum(n)}function maximum_(e,t){var r,n=convertToTensor(e,"a","maximum"),a=convertToTensor(t,"b","maximum");return r=makeTypesMatch(n,a),n=r[0],a=r[1],"bool"===n.dtype&&(n=n.toInt(),a=a.toInt()),assertAndGetBroadcastShape(n.shape,a.shape),ENV.engine.runKernel(function(e){return e.maximum(n,a)},{$a:n,$b:a},function(e){return{$a:function(){return e.mul(n.greaterEqual(a).toFloat())},$b:function(){return e.mul(n.less(a).toFloat())}}})}function maximumStrict_(e,t){var r=convertToTensor(e,"a","maximumStrict"),n=convertToTensor(t,"b","maximumStrict");return assertShapesMatch(r.shape,n.shape,"Error in maximumStrict: "),r.maximum(n)}function squaredDifference_(e,t){var r,n=convertToTensor(e,"a","squaredDifference"),a=convertToTensor(t,"b","squaredDifference");return r=makeTypesMatch(n,a),n=r[0],a=r[1],assertAndGetBroadcastShape(n.shape,a.shape),ENV.engine.runKernel(function(e){return e.squaredDifference(n,a)},{$a:n,$b:a},function(e){var t=scalar(2);return{$a:function(){return e.mul(n.sub(a).mul(t))},$b:function(){return e.mul(a.sub(n).mul(t))}}})}function squaredDifferenceStrict_(e,t){var r=convertToTensor(e,"a","squaredDifferenceStrict"),n=convertToTensor(t,"b","squaredDifferenceStrict");return assertShapesMatch(r.shape,n.shape,"Error in squaredDifferenceStrict: "),r.squaredDifference(n)}function atan2_(e,t){var r,n=convertToTensor(e,"a","atan2"),a=convertToTensor(t,"b","atan2");r=makeTypesMatch(n,a),n=r[0],a=r[1];var o=assertAndGetBroadcastShape(n.shape,a.shape);return ENV.engine.runKernel(function(e){return e.atan2(n,a)},{$a:n,$b:a},function(e){return{$a:function(){var t=add(n.square(),a.square()),r=e.mul(a.div(t)),i=getReductionAxes(n.shape,o);return i.length>0&&(r=r.sum(i)),r.reshape(n.shape)},$b:function(){var t=add(n.square(),a.square()),r=neg(e.mul(n.div(t))),i=getReductionAxes(a.shape,o);return i.length>0&&(r=r.sum(i)),r.reshape(a.shape)}}})}var add=op({add_:add_}),addN=op({addN_:addN_}),addStrict=op({addStrict_:addStrict_}),atan2=op({atan2_:atan2_}),div=op({div_:div_}),divStrict=op({divStrict_:divStrict_}),floorDiv=op({floorDiv_:floorDiv_}),maximum=op({maximum_:maximum_}),maximumStrict=op({maximumStrict_:maximumStrict_}),minimum=op({minimum_:minimum_}),minimumStrict=op({minimumStrict_:minimumStrict_}),mod=op({mod_:mod_}),modStrict=op({modStrict_:modStrict_}),mul=op({mul_:mul_}),mulStrict=op({mulStrict_:mulStrict_}),pow=op({pow_:pow_}),powStrict=op({powStrict_:powStrict_}),squaredDifference=op({squaredDifference_:squaredDifference_}),squaredDifferenceStrict=op({squaredDifferenceStrict_:squaredDifferenceStrict_}),sub=op({sub_:sub_}),subStrict=op({subStrict_:subStrict_});function logicalNot_(e){var t=convertToTensor(e,"x","logicalNot","bool");return ENV.engine.runKernel(function(e){return e.logicalNot(t)},{$x:t})}function logicalAnd_(e,t){var r=convertToTensor(e,"a","logicalAnd","bool"),n=convertToTensor(t,"b","logicalAnd","bool");return assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.logicalAnd(r,n)},{$a:r,$b:n})}function logicalOr_(e,t){var r=convertToTensor(e,"a","logicalOr","bool"),n=convertToTensor(t,"b","logicalOr","bool");return assertAndGetBroadcastShape(r.shape,n.shape),ENV.engine.runKernel(function(e){return e.logicalOr(r,n)},{$a:r,$b:n})}function logicalXor_(e,t){var r=convertToTensor(e,"a","logicalXor","bool"),n=convertToTensor(t,"b","logicalXor","bool");return assertAndGetBroadcastShape(r.shape,n.shape),logicalOr(e,t).logicalAnd(logicalAnd(e,t).logicalNot())}function where_(e,t,r){var n=convertToTensor(t,"a","where"),a=convertToTensor(r,"b","where"),o=convertToTensor(e,"condition","where","bool");return assertShapesMatch(n.shape,a.shape,"Error in where: "),1===o.rank?assert(o.shape[0]===n.shape[0],"The first dimension of `a` must match the size of `condition`."):assertShapesMatch(o.shape,a.shape,"Error in where: "),ENV.engine.runKernel(function(e){return e.select(o,n,a)},{$condition:o,$a:n,$b:a},function(e){return{$condition:function(){return zerosLike(o).toFloat()},$a:function(){return e.mul(o.cast(e.dtype))},$b:function(){return e.mul(o.logicalNot().cast(e.dtype))}}})}function whereAsync_(e){return __awaiter(this,void 0,void 0,function(){var t,r,n;return __generator(this,function(a){switch(a.label){case 0:return[4,(t=convertToTensor(e,"condition","whereAsync","bool")).data()];case 1:return r=a.sent(),n=whereImpl(t.shape,r),e!==t&&t.dispose(),[2,n]}})})}var logicalAnd=op({logicalAnd_:logicalAnd_}),logicalNot=op({logicalNot_:logicalNot_}),logicalOr=op({logicalOr_:logicalOr_}),logicalXor=op({logicalXor_:logicalXor_}),where=op({where_:where_}),whereAsync=whereAsync_;function relu_(e){var t=convertToTensor(e,"x","relu");return"bool"===t.dtype?t.toInt():ENV.engine.runKernel(function(e){return e.relu(t)},{$x:t},function(e){var r=t.step();return{$x:function(){return e.mulStrict(r.toFloat())}}})}function elu_(e){var t=convertToTensor(e,"x","elu");return ENV.engine.runKernel(function(e,r){return r(e.elu(t))},{$x:t},function(e,t){var r=t[0];return{$x:function(){return ENV.engine.runKernel(function(t){return t.eluDer(e,r)},{dy:e,y:r})}}})}function selu_(e){var t=convertToTensor(e,"x","selu");return ENV.engine.runKernel(function(e){return e.selu(t)},{$x:t},function(e){return{$x:function(){var r=t.greater(scalar(0)),n=scalar(SELU_SCALEALPHA),a=scalar(SELU_SCALE),o=e.mul(a),i=e.mul(n).mul(t.toFloat().exp());return where(r,o,i)}}})}function leakyRelu_(e,t){void 0===t&&(t=.2);var r=convertToTensor(e,"x","leakyRelu");return maximum(scalar(t).mul(r),r)}function prelu_(e,t){var r=convertToTensor(e,"x","prelu"),n=convertToTensor(t,"alpha","prelu"),a=scalar(0);return maximum(a,r).add(n.mul(minimum(a,r)))}var elu=op({elu_:elu_}),leakyRelu=op({leakyRelu_:leakyRelu_}),prelu=op({prelu_:prelu_}),relu=op({relu_:relu_}),selu=op({selu_:selu_});function transpose_(e,t){var r=convertToTensor(e,"x","transpose");return null==t&&(t=r.shape.map(function(e,t){return t}).reverse()),assert(r.rank===t.length,"Error in transpose: rank of input "+r.rank+" must match length of perm "+t+"."),t.forEach(function(e){assert(e>=0&&ea)throw new Error("'k' passed to topk() must be <= the last dimension ("+a+") but got "+t);var o=ENV.engine.runKernel(function(e){return e.topk(n,t,r)},{$x:n});return{values:o[0],indices:o[1]}}var topk=op({topk_:topk_});function scatterND_(e,t,r){var n=convertToTensor(e,"indices","scatterND","int32"),a=convertToTensor(t,"updates","scatterND");return validateInput(a,n,r),ENV.engine.runKernel(function(e){return e.scatterND(n,a,r)},{$indices:n,$updates:a})}var scatterND=op({scatterND_:scatterND_});function fft_(e){assert("complex64"===e.dtype,"The dtype for tf.spectral.fft() must be complex64 but got "+e.dtype+".");var t=e.shape[e.shape.length-1],r=e.size/t,n=e.as2D(r,t);return ENV.engine.runKernel(function(e){return e.fft(n)},{input:e}).reshape(e.shape)}function ifft_(e){assert("complex64"===e.dtype,"The dtype for tf.spectral.ifft() must be complex64 but got "+e.dtype+".");var t=e.shape[e.shape.length-1],r=e.size/t,n=e.as2D(r,t);return ENV.engine.runKernel(function(e){return e.ifft(n)},{input:e}).reshape(e.shape)}function rfft_(e){assert("float32"===e.dtype,"The dtype for rfft() must be real value but\n got "+e.dtype);var t=e.shape[e.shape.length-1],r=e.size/t,n=e.zerosLike(),a=complex(e,n).as2D(r,t),o=fft(a),i=Math.floor(t/2)+1,s=real(o),u=imag(o),l=s.split([i,t-i],s.shape.length-1),p=u.split([i,t-i],u.shape.length-1),c=e.shape.slice();return c[e.shape.length-1]=i,complex(l[0],p[0]).reshape(c)}function irfft_(e){var t=e.shape[e.shape.length-1],r=e.size/t;if(t<=2){var n=e.as2D(r,t),a=ifft(n);return real(a)}var o=[r,2*(t-1)],i=real(e).as2D(r,t),s=imag(e).as2D(r,t),u=i.slice([0,1],[r,t-2]).reverse(1),l=s.slice([0,1],[r,t-2]).reverse(1).mul(scalar(-1)),p=i.concat(u,1),c=s.concat(l,1);return n=complex(p,c).as2D(o[0],o[1]),a=ifft(n),real(a)}var fft=op({fft_:fft_}),ifft=op({ifft_:ifft_}),rfft=op({rfft_:rfft_}),irfft=op({irfft_:irfft_}),spectral_ops=Object.freeze({fft:fft,ifft:ifft,rfft:rfft,irfft:irfft});function validateInput$1(e,t,r,n){if("int32"!==e.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+e.shape+".");var a=e.rank>0?e.shape[0]:1,o=e.rank>1?e.shape[1]:1;if(r.length!==o)throw new Error("outputShape has incorrect number of elements:, "+r.length+", should be: "+o+".");var i=t.size;if(0!==t.rank&&(1!==t.rank||i!==a))throw new Error("sparseValues has incorrect shape "+t.shape+", should be [] or ["+a+"]");if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function sparseToDense_(e,t,r,n){var a=convertToTensor(e,"sparseIndices","sparseToDense","int32"),o=convertToTensor(t,"sparseValues","sparseToDense"),i=convertToTensor(n,"defaultValue","sparseToDense",o.dtype);return validateInput$1(a,o,r,i),ENV.engine.runKernel(function(e){return e.sparseToDense(a,o,r,i)},{$sparseIndices:a,$sparseValues:o,$defaultValue:i})}var sparseToDense=op({sparseToDense_:sparseToDense_});function gatherND_(e,t){var r=convertToTensor(t,"indices","gatherND","int32"),n=convertToTensor(e,"x","gatherND");return ENV.engine.runKernel(function(e){return e.gatherND(n,r)},{$x:n,$indices:r})}var gatherND=op({gatherND_:gatherND_});function computeWeightedLoss_(e,t,r){void 0===r&&(r=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var n=convertToTensor(e,"losses","computeWeightedLoss"),a=null;null!=t&&(a=convertToTensor(t,"weights","computeWeightedLoss"));var o=null==a?n:n.mul(a);if(r===exports.Reduction.NONE)return o;if(r===exports.Reduction.SUM)return o.sum();if(r===exports.Reduction.MEAN){if(null==a)return o.mean();var i=sizeFromShape(n.shape)/sizeFromShape(a.shape),s=o.sum().div(a.sum());return i>1?s.div(scalar(i)):s}if(r===exports.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return o.sum().div(scalar(n.size));var u=a.mul(ones$1(n.shape)).notEqual(scalar(0)).sum().toFloat();return o.sum().div(u)}throw Error("Unknown reduction: "+r)}function absoluteDifference_(e,t,r,n){void 0===n&&(n=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=convertToTensor(e,"labels","absoluteDifference"),o=convertToTensor(t,"predictions","absoluteDifference"),i=null;null!=r&&(i=convertToTensor(r,"weights","absoluteDifference")),assertShapesMatch(a.shape,o.shape,"Error in absoluteDifference: ");var s=a.sub(o).abs();return computeWeightedLoss(s,i,n)}function meanSquaredError_(e,t,r,n){void 0===n&&(n=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=convertToTensor(e,"labels","meanSquaredError"),o=convertToTensor(t,"predictions","meanSquaredError"),i=null;null!=r&&(i=convertToTensor(r,"weights","meanSquaredError")),assertShapesMatch(a.shape,o.shape,"Error in meanSquaredError: ");var s=a.squaredDifference(o);return computeWeightedLoss(s,i,n)}function cosineDistance_(e,t,r,n,a){void 0===a&&(a=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=convertToTensor(e,"labels","cosineDistance"),i=convertToTensor(t,"predictions","cosineDistance"),s=null;null!=n&&(s=convertToTensor(n,"weights","cosineDistance")),assertShapesMatch(o.shape,i.shape,"Error in cosineDistance: ");var u=scalar(1).sub(o.mul(i).sum(r,!0));return computeWeightedLoss(u,s,a)}function hingeLoss_(e,t,r,n){void 0===n&&(n=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=convertToTensor(e,"labels","hingeLoss"),o=convertToTensor(t,"predictions","hingeLoss"),i=null;null!=r&&(i=convertToTensor(r,"weights","hingeLoss")),assertShapesMatch(a.shape,o.shape,"Error in hingeLoss: ");var s=scalar(1);a=scalar(2).mul(a).sub(s);var u=s.sub(a.mul(o)).relu();return computeWeightedLoss(u,i,n)}function logLoss_(e,t,r,n,a){void 0===n&&(n=1e-7),void 0===a&&(a=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=convertToTensor(e,"labels","logLoss"),i=convertToTensor(t,"predictions","logLoss"),s=null;null!=r&&(s=convertToTensor(r,"weights","logLoss")),assertShapesMatch(o.shape,i.shape,"Error in logLoss: ");var u=scalar(1),l=scalar(n),p=o.mul(i.add(l).log()).neg().sub(u.sub(o).mul(u.sub(i).add(l).log()));return computeWeightedLoss(p,s,a)}function sigmoidCrossEntropyWithLogits_(e,t){var r=convertToTensor(e,"labels","sigmoidCrossEntropyWithLogits"),n=convertToTensor(t,"logits","sigmoidCrossEntropyWithLogits");assertShapesMatch(r.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");var a=n.relu(),o=n.mul(r),i=n.abs().neg().exp().log1p();return a.sub(o).add(i)}function sigmoidCrossEntropy_(e,t,r,n,a){void 0===n&&(n=0),void 0===a&&(a=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=convertToTensor(e,"multiClassLabels","sigmoidCrossEntropy"),i=convertToTensor(t,"logits","sigmoidCrossEntropy"),s=null;if(null!=r&&(s=convertToTensor(r,"weights","sigmoidCrossEntropy")),assertShapesMatch(o.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){var u=scalar(n),l=scalar(1),p=scalar(.5);o=o.mul(l.sub(u)).add(p.mul(u))}var c=sigmoidCrossEntropyWithLogits_(o,i);return computeWeightedLoss(c,s,a)}function huberLoss_(e,t,r,n,a){void 0===n&&(n=1),void 0===a&&(a=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=convertToTensor(e,"labels","huberLoss"),i=convertToTensor(t,"predictions","huberLoss"),s=null;null!=r&&(s=convertToTensor(r,"weights","huberLoss")),assertShapesMatch(o.shape,i.shape,"Error in huberLoss: ");var u=scalar(n),l=i.sub(o).abs(),p=minimum(l,u),c=l.sub(p),d=scalar(.5).mul(p.square()).add(u.mul(c));return computeWeightedLoss(d,s,a)}function softmaxCrossEntropyWithLogits_(e,t,r){if(void 0===r&&(r=-1),-1===r&&(r=t.rank-1),r!==t.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+t.rank+" and dim was "+r);return customGrad(function(e,t){var n=t.logSumExp([r],!0),a=t.toFloat().sub(n);return{value:a.mul(e).neg().sum([r]),gradFunc:function(t){var n=expandShapeToKeepDim(t.shape,[r]);return[t.reshape(n).mul(e.toFloat().sub(a.exp())),t.reshape(n).mul(a.exp().sub(e.toFloat()))]}}})(e,t)}function softmaxCrossEntropy_(e,t,r,n,a){void 0===n&&(n=0),void 0===a&&(a=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=convertToTensor(e,"onehotLabels","softmaxCrossEntropy"),i=convertToTensor(t,"logits","softmaxCrossEntropy"),s=null;if(null!=r&&(s=convertToTensor(r,"weights","softmaxCrossEntropy")),assertShapesMatch(o.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){var u=scalar(n),l=scalar(1),p=scalar(o.shape[1]);o=o.mul(l.sub(u)).add(u.div(p))}var c=softmaxCrossEntropyWithLogits_(o,i);return computeWeightedLoss(c,s,a)}!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(exports.Reduction||(exports.Reduction={}));var absoluteDifference=op({absoluteDifference_:absoluteDifference_}),computeWeightedLoss=op({computeWeightedLoss_:computeWeightedLoss_}),cosineDistance=op({cosineDistance_:cosineDistance_}),hingeLoss=op({hingeLoss_:hingeLoss_}),huberLoss=op({huberLoss_:huberLoss_}),logLoss=op({logLoss_:logLoss_}),meanSquaredError=op({meanSquaredError_:meanSquaredError_}),sigmoidCrossEntropy=op({sigmoidCrossEntropy_:sigmoidCrossEntropy_}),softmaxCrossEntropy=op({softmaxCrossEntropy_:softmaxCrossEntropy_}),loss_ops=Object.freeze({get Reduction(){return exports.Reduction},absoluteDifference:absoluteDifference,computeWeightedLoss:computeWeightedLoss,cosineDistance:cosineDistance,hingeLoss:hingeLoss,huberLoss:huberLoss,logLoss:logLoss,meanSquaredError:meanSquaredError,sigmoidCrossEntropy:sigmoidCrossEntropy,softmaxCrossEntropy:softmaxCrossEntropy});function gramSchmidt_(e){var t;if(Array.isArray(e)){t=!1,assert(null!=e&&e.length>0,"Gram-Schmidt process: input must not be null, undefined, or empty");for(var r=e[0].shape[0],n=1;n0)for(var r=0;r= 2, but got rank "+e.rank);if(2===e.rank)return qr2d(e,t);var r=e.shape.slice(0,e.shape.length-2).reduce(function(e,t){return e*t}),n=[],a=[];return unstack(e.reshape([r,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0).forEach(function(e){var r=qr2d(e,t),o=r[0],i=r[1];n.push(o),a.push(i)}),[stack(n,0).reshape(e.shape),stack(a,0).reshape(e.shape)]}function qr2d(e,t){return void 0===t&&(t=!1),ENV.engine.tidy(function(){if(2!==e.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+e.shape.length+"D Tensor.");for(var r=e.shape[0],n=e.shape[1],a=eye(r),o=e.clone(),i=tensor2d([[1]],[1,1]),s=i.clone(),u=r>=n?n:r,l=function(e){var t,u=o,l=s,p=a;t=ENV.engine.tidy(function(){var t=o.slice([e,e],[r-e,1]),u=t.norm(),l=o.slice([e,e],[1,1]),p=l.sign().neg(),c=l.sub(p.mul(u)),d=t.div(c);s=1===d.shape[0]?i.clone():i.concat(d.slice([1,0],[d.shape[0]-1,d.shape[1]]),0);var h=p.matMul(c).div(u).neg(),f=o.slice([e,0],[r-e,n]),m=h.mul(s);o=0===e?f.sub(m.matMul(s.transpose().matMul(f))):o.slice([0,0],[e,n]).concat(f.sub(m.matMul(s.transpose().matMul(f))),0);var g=a.slice([0,e],[r,a.shape[1]-e]);return a=0===e?g.sub(g.matMul(s).matMul(m.transpose())):a.slice([0,0],[r,e]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,o,a]}),s=t[0],o=t[1],a=t[2],dispose([u,l,p])},p=0;pn&&(a=a.slice([0,0],[r,n]),o=o.slice([0,0],[n,n])),[a,o]})}var gramSchmidt=op({gramSchmidt_:gramSchmidt_}),qr=op({qr_:qr_}),linalg_ops=Object.freeze({gramSchmidt:gramSchmidt,qr:qr});function resizeBilinear_(e,t,r){void 0===r&&(r=!1);var n=convertToTensor(e,"images","resizeBilinear");assert(3===n.rank||4===n.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+n.rank+"."),assert(2===t.length,"Error in resizeBilinear: new shape must 2D, but got shape "+t+".");var a=n,o=!1;3===n.rank&&(o=!0,a=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],u=ENV.engine.runKernel(function(e,t){return e.resizeBilinear(a,i,s,r)},{batchImages:a},function(e,t){return{batchImages:function(){return ENV.engine.runKernel(function(t){return t.resizeBilinearBackprop(e,a,r)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}function resizeNearestNeighbor_(e,t,r){void 0===r&&(r=!1);var n=convertToTensor(e,"images","resizeNearestNeighbor");assert(3===n.rank||4===n.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+n.rank+"."),assert(2===t.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."),assert("float32"===n.dtype||"int32"===n.dtype,"`images` must have `int32` or `float32` as dtype");var a=n,o=!1;3===n.rank&&(o=!0,a=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]));var i=t[0],s=t[1],u=ENV.engine.runKernel(function(e,t){return e.resizeNearestNeighbor(a,i,s,r)},{batchImages:a},function(e,t){return{batchImages:function(){return ENV.engine.runKernel(function(t){return t.resizeNearestNeighborBackprop(e,a,r)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}function nonMaxSuppression_(e,t,r,n,a){void 0===n&&(n=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY);var o=convertToTensor(e,"boxes","nonMaxSuppression"),i=convertToTensor(t,"scores","nonMaxSuppression"),s=nonMaxSuppSanityCheck(o,i,r,n,a);return r=s.maxOutputSize,n=s.iouThreshold,a=s.scoreThreshold,ENV.engine.runKernel(function(e){return e.nonMaxSuppression(o,i,r,n,a)},{$boxes:o})}function nonMaxSuppressionAsync_(e,t,r,n,a){return void 0===n&&(n=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),__awaiter(this,void 0,void 0,function(){var o,i,s,u,l,p;return __generator(this,function(c){switch(c.label){case 0:return o=convertToTensor(e,"boxes","nonMaxSuppressionAsync"),i=convertToTensor(t,"scores","nonMaxSuppressionAsync"),s=nonMaxSuppSanityCheck(o,i,r,n,a),r=s.maxOutputSize,n=s.iouThreshold,a=s.scoreThreshold,[4,o.data()];case 1:return u=c.sent(),[4,i.data()];case 2:return l=c.sent(),p=nonMaxSuppressionImpl(u,l,r,n,a),o!==e&&o.dispose(),i!==t&&i.dispose(),[2,p]}})})}function nonMaxSuppSanityCheck(e,t,r,n,a){null==n&&(n=.5),null==a&&(a=Number.NEGATIVE_INFINITY);var o=e.shape[0];return r=Math.min(r,o),assert(0<=n&&n<=1,"iouThreshold must be in [0, 1], but was '"+n+"'"),assert(2===e.rank,"boxes must be a 2D tensor, but was of rank '"+e.rank+"'"),assert(4===e.shape[1],"boxes must have 4 columns, but 2nd dimension was "+e.shape[1]),assert(1===t.rank,"scores must be a 1D tensor"),assert(t.shape[0]===o,"scores has incompatible shape with boxes. Expected "+o+", but was "+t.shape[0]),{maxOutputSize:r,iouThreshold:n,scoreThreshold:a}}function cropAndResize_(e,t,r,n,a,o){var i=convertToTensor(e,"image","cropAndResize","float32"),s=convertToTensor(t,"boxes","cropAndResize","float32"),u=convertToTensor(r,"boxInd","cropAndResize","int32");a=a||"bilinear",o=o||0;var l=s.shape[0];return assert(4===i.rank,"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."),assert(2===s.rank&&4===s.shape[1],"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."),assert(1===u.rank&&u.shape[0]===l,"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."),assert(2===n.length,"Error in cropAndResize: cropSize must be of length 2, but got length "+n.length+"."),assert(n[0]>=1&&n[1]>=1,"cropSize must be atleast [1,1], but was "+n),assert("bilinear"===a||"nearest"===a,"method must be bilinear or nearest, but was "+a),ENV.engine.runKernel(function(e,t){return e.cropAndResize(i,s,u,n,a,o)},{$image:i,$boxes:s})}var resizeBilinear=op({resizeBilinear_:resizeBilinear_}),resizeNearestNeighbor=op({resizeNearestNeighbor_:resizeNearestNeighbor_}),nonMaxSuppression=op({nonMaxSuppression_:nonMaxSuppression_}),nonMaxSuppressionAsync=nonMaxSuppressionAsync_,cropAndResize=cropAndResize_,image_ops=Object.freeze({resizeBilinear:resizeBilinear,resizeNearestNeighbor:resizeNearestNeighbor,nonMaxSuppression:nonMaxSuppression,nonMaxSuppressionAsync:nonMaxSuppressionAsync,cropAndResize:cropAndResize}),ops=Object.freeze({image:image_ops,linalg:linalg_ops,losses:loss_ops,spectral:spectral_ops,op:op,batchNormalization2d:batchNormalization2d,batchNormalization3d:batchNormalization3d,batchNormalization4d:batchNormalization4d,batchNormalization:batchNormalization,complex:complex,real:real,imag:imag,concat:concat,concat1d:concat1d,concat2d:concat2d,concat3d:concat3d,concat4d:concat4d,split:split$1,conv1d:conv1d,conv2d:conv2d,conv3d:conv3d,conv2dDerFilter:conv2dDerFilter,depthwiseConv2d:depthwiseConv2d,separableConv2d:separableConv2d,conv2dTranspose:conv2dTranspose,matMul:matMul,dot:dot,outerProduct:outerProduct,reverse:reverse,reverse1d:reverse1d,reverse2d:reverse2d,reverse3d:reverse3d,reverse4d:reverse4d,maxPool:maxPool,avgPool:avgPool,pool:pool,slice:slice,slice1d:slice1d,slice2d:slice2d,slice3d:slice3d,slice4d:slice4d,abs:abs,acos:acos,acosh:acosh,asin:asin,asinh:asinh,atan:atan,atanh:atanh,ceil:ceil,clipByValue:clipByValue,cos:cos,cosh:cosh,erf:erf,exp:exp,expm1:expm1,floor:floor,log:log$1,log1p:log1p,logSigmoid:logSigmoid,neg:neg,reciprocal:reciprocal,round:round,rsqrt:rsqrt,sigmoid:sigmoid,sign:sign,sin:sin,sinh:sinh,softplus:softplus,sqrt:sqrt,square:square,step:step,tan:tan,tanh:tanh$1,all:all,any:any,argMax:argMax,argMin:argMin,logSumExp:logSumExp,max:max,mean:mean,min:min,moments:moments,sum:sum$1,prod:prod,equal:equal,equalStrict:equalStrict,greater:greater,greaterEqual:greaterEqual,greaterEqualStrict:greaterEqualStrict,greaterStrict:greaterStrict,less:less,lessEqual:lessEqual,lessEqualStrict:lessEqualStrict,lessStrict:lessStrict,notEqual:notEqual,notEqualStrict:notEqualStrict,add:add,addN:addN,addStrict:addStrict,atan2:atan2,div:div,divStrict:divStrict,floorDiv:floorDiv,maximum:maximum,maximumStrict:maximumStrict,minimum:minimum,minimumStrict:minimumStrict,mod:mod,modStrict:modStrict,mul:mul,mulStrict:mulStrict,pow:pow,powStrict:powStrict,squaredDifference:squaredDifference,squaredDifferenceStrict:squaredDifferenceStrict,sub:sub,subStrict:subStrict,elu:elu,leakyRelu:leakyRelu,prelu:prelu,relu:relu,selu:selu,logicalAnd:logicalAnd,logicalNot:logicalNot,logicalOr:logicalOr,logicalXor:logicalXor,where:where,whereAsync:whereAsync,buffer:buffer,toPixels:toPixels,print:print,batchToSpaceND:batchToSpaceND,cast:cast,clone:clone,cumsum:cumsum,depthToSpace:depthToSpace,expandDims:expandDims,eye:eye,fromPixels:fromPixels,multinomial:multinomial,oneHot:oneHot,pad:pad,pad1d:pad1d,pad2d:pad2d,pad3d:pad3d,pad4d:pad4d,rand:rand,randomNormal:randomNormal,randomUniform:randomUniform,reshape:reshape,spaceToBatchND:spaceToBatchND,squeeze:squeeze,stack:stack,tile:tile,truncatedNormal:truncatedNormal,unstack:unstack,setdiff1dAsync:setdiff1dAsync,fill:fill,linspace:linspace,ones:ones$1,range:range,scalar:scalar,tensor:tensor,tensor1d:tensor1d,tensor2d:tensor2d,tensor3d:tensor3d,tensor4d:tensor4d,tensor5d:tensor5d,tensor6d:tensor6d,zeros:zeros,onesLike:onesLike,zerosLike:zerosLike,transpose:transpose,softmax:softmax,logSoftmax:logSoftmax,localResponseNormalization:localResponseNormalization,norm:norm,gather:gather,unsortedSegmentSum:unsortedSegmentSum,basicLSTMCell:basicLSTMCell,multiRNNCell:multiRNNCell,movingAverage:movingAverage,stridedSlice:stridedSlice,topk:topk,scatterND:scatterND,fft:fft,ifft:ifft,rfft:rfft,irfft:irfft,sparseToDense:sparseToDense,gatherND:gatherND}),MathBackendCPU=function(){function e(){this.blockSize=48,this.firstUse=!0,ENV.get("IS_BROWSER")&&(this.fromPixels2DContext=document.createElement("canvas").getContext("2d"))}return e.prototype.setDataMover=function(e){this.data=new DataStorage(e)},e.prototype.register=function(e,t,r){if(this.firstUse&&(this.firstUse=!1,ENV.get("IS_NODE")&&warn("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,{dtype:r})},e.prototype.write=function(e,t){if(null==t)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(e).values=t},e.prototype.fromPixels=function(e,t){if(null==e)throw new Error("pixels passed to tf.fromPixels() can not be null");var r,n;if(ENV.get("IS_NODE")&&null==e.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=e.getContext)r=e.getContext("2d").getImageData(0,0,e.width,e.height).data;else if(e instanceof ImageData)r=e.data;else{if(!(e instanceof HTMLImageElement||e instanceof HTMLVideoElement))throw new Error("pixels passed to tf.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+e.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=e.width,this.fromPixels2DContext.canvas.height=e.height,this.fromPixels2DContext.drawImage(e,0,0,e.width,e.height),r=this.fromPixels2DContext.getImageData(0,0,e.width,e.height).data}if(4===t)n=new Int32Array(r);else{var a=e.width*e.height;n=new Int32Array(a*t);for(var o=0;od&&(d=m,h=f)}u[p]=h}return i},e.prototype.cumsum=function(e,t,r,n){if(this.assertNotComplex(e,"cumsum"),t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var a=upcastType(e.dtype,"int32"),o=zeros(e.shape,a),i=o.dataSync(),s=e.dataSync(),u=e.shape[e.rank-1],l=n?function(e,t){return e+u-t-1}:function(e,t){return e+t},p=0;pt?1:0})},e.prototype.greaterEqual=function(e,t){return this.assertNotComplex([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e>=t?1:0})},e.prototype.logicalNot=function(e){this.assertNotComplex(e,"logicalNot");for(var t=e.dataSync(),r=new Uint8Array(t.length),n=0;n1||1===t.rank?1:t.shape[1],p=0;p=0&&t>=0?r:(r+t)%t})},e.prototype.max=function(e,t){this.assertNotComplex(e,"max"),assertAxesAreInnerMostDims("max",t,e.rank);for(var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=r[1],o=zeros(n,e.dtype),i=sizeFromShape(a),s=o.dataSync(),u=e.dataSync(),l=0;lc&&(c=h)}s[l]=c}return o},e.prototype.maximum=function(e,t){return this.assertNotComplex([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.max(e,t)})},e.prototype.all=function(e,t){this.assertNotComplex(e,"all"),assertAxesAreInnerMostDims("all",t,e.rank);for(var r=computeOutAndReduceShapes(e.shape,t),n=r[0],a=r[1],o=zeros(n,e.dtype),i=sizeFromShape(a),s=o.dataSync(),u=e.dataSync(),l=0;l0?r[n]=1:r[n]=0;return Tensor.make(e.shape,{values:r})},e.prototype.round=function(e){this.assertNotComplex(e,"round");for(var t=e.dataSync(),r=new Float32Array(t.length),n=0;n.5?r[n]=Math.ceil(t[n]):r[n]=a%2==0?a:a+1}return Tensor.make(e.shape,{values:r})},e.prototype.exp=function(e){this.assertNotComplex(e,"exp");for(var t=e.dataSync(),r=new Float32Array(t.length),n=0;n=0?a:Math.exp(a)-1}return Tensor.make(e.shape,{values:t})},e.prototype.eluDer=function(e,t){this.assertNotComplex([e,t],"eluDer");for(var r=new Float32Array(t.size),n=t.dataSync(),a=e.dataSync(),o=0;o=1?a[o]:a[o]*(i+1)}return Tensor.make(t.shape,{values:r})},e.prototype.selu=function(e){this.assertNotComplex(e,"selu");for(var t=SELU_SCALEALPHA,r=SELU_SCALE,n=new Float32Array(e.size),a=e.dataSync(),o=0;o=0?r*i:t*(Math.exp(i)-1)}return Tensor.make(e.shape,{values:n})},e.prototype.clip=function(e,t,r){this.assertNotComplex(e,"clip");for(var n=new Float32Array(e.size),a=e.dataSync(),o=0;or?r:i-t,s=n[a]0?1:t}return Tensor.make(e.shape,{values:r})},e.prototype.conv2d=function(e,t,r){this.assertNotComplex([e,t],"conv2d");for(var n=r.filterHeight,a=r.filterWidth,o=r.dilationHeight,i=r.dilationWidth,s=r.padInfo.left,u=r.padInfo.top,l=buffer(r.outShape,e.dtype),p=e.dataSync(),c=t.dataSync(),d=l.values,h=0;h=r.inHeight))for(var w=x*t.strides[0],N=f+b*e.strides[1],S=0;S=r.inWidth))for(var C=w+I*t.strides[1],A=N+_*r.inChannels,P=C,k=0;k=r.inDepth))for(var T=N*t.strides[0],E=y+S*e.strides[1],I=0;I=r.inHeight))for(var k=T+A*t.strides[1],D=E+P*e.strides[2],R=0;R=r.inWidth))for(var F=k+z*t.strides[2],V=D+L*r.inChannels,B=F,$=0;$=r.inHeight))for(var N=b*t.strides[0],S=m+w*e.strides[1],T=0;T=r.inWidth))for(var A=N+_*t.strides[1],P=S+C*r.inChannels,k=E,D=A,R=0;Rk?k=L:"avg"===r&&(D+=L,R++)}if(isNaN(k))break}f[I+_*y+w]="avg"===r?D/R:k}return h.toTensor()},e.prototype.maxPool=function(e,t){return this.pool(e,t,"max")},e.prototype.maxPoolPositions=function(e,t){for(var r=buffer(t.outShape,"int32"),n=t.strideHeight,a=t.strideWidth,o=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=t.padInfo.top,p=t.padInfo.left,c=0;cw&&(w=_,N=T*u+I)}r.set(N,c,h,y,d)}}return r.toTensor()},e.prototype.maxPoolBackprop=function(e,t,r,n){this.assertNotComplex([t,r],"maxPoolBackprop");for(var a=this.maxPoolPositions(t,n),o=n.strideHeight,i=n.strideWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,p=n.effectiveFilterWidth,c=p-1-n.padInfo.left,d=l-1-n.padInfo.top,h=buffer(t.shape,"float32"),f=0;f=n.outHeight||Math.floor(N)!==N))for(var S=0;S=n.outWidth||Math.floor(T)!==T)){var E=l*p-1-a.get(f,N,T,m)===w*p+S?1:0;0!==E&&(b+=e.get(f,N,T,m)*E)}}}h.set(b,f,g,y,m)}return h.toTensor()},e.prototype.avgPoolBackprop=function(e,t,r){this.assertNotComplex([e,t],"avgPoolBackprop");for(var n=r.strideHeight,a=r.strideWidth,o=r.filterHeight,i=r.filterWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,p=r.effectiveFilterWidth,c=p-1-r.padInfo.left,d=l-1-r.padInfo.top,h=buffer(t.shape,"float32"),f=1/(o*i),m=0;m=r.outHeight||Math.floor(S)!==S))for(var T=0;T=r.outWidth||Math.floor(E)!==E||(w+=e.get(m,S,E,g))}}h.set(w*f,m,y,v,g)}return h.toTensor()},e.prototype.cast=function(e,t){return castTensor(e,t,this)},e.prototype.reshape=function(e,t){return reshapeTensor(e,t)},e.prototype.avgPool=function(e,t){return this.assertNotComplex(e,"avgPool"),this.pool(e,t,"avg").toFloat()},e.prototype.resizeBilinear=function(e,t,r,n){this.assertNotComplex(e,"resizeBilinear");for(var a=e.shape,o=a[0],i=a[1],s=a[2],u=a[3],l=e.dataSync(),p=new Float32Array(sizeFromShape([o,t,r,u])),c=[n&&t>1?i-1:i,n&&r>1?s-1:s],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h=0,f=c[0]/d[0],m=c[1]/d[1],g=0;g1?o-1:o,r&&p>1?i-1:i],h=[r&&l>1?l-1:l,r&&p>1?p-1:p],f=d[0]/h[0],m=d[1]/h[1],g=e.dataSync(),y=0,v=0;v1?i-1:i,n&&r>1?s-1:s],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h=c[0]/d[0],f=c[1]/d[1],m=0,g=0;g1?o-1:o,r&&p>1?i-1:i],f=[r&&l>1?l-1:l,r&&p>1?p-1:p],m=h[0]/f[0],g=h[1]/f[1],y=1/m,v=1/g,x=2*Math.ceil(y)+2,b=2*Math.ceil(v)+2,w=0;w=l)){var M=N+O*e.strides[1],z=O*m;if(S===Math.min(o-1,r?Math.round(z):Math.floor(z)))for(var L=0;L=p)){var V=M+F*e.strides[2],B=F*g;_===Math.min(i-1,r?Math.round(B):Math.floor(B))&&(D+=d[V+k])}}}}c[C+k]=D}return tensor4d(c,t.shape,t.dtype)},e.prototype.batchNormalization=function(e,t,r,n,a,o){this.assertNotComplex([e,t,r,a,o],"batchNormalization");for(var i=e.dataSync(),s=t.dataSync(),u=r.dataSync(),l=a?a.dataSync():new Float32Array([1]),p=o?o.dataSync():new Float32Array([0]),c=new Float32Array(i.length),d=p.length,h=l.length,f=u.length,m=s.length,g=0,y=0,v=0,x=0,b=0;b=d&&(g=0),y>=m&&(y=0),v>=h&&(v=0),x>=f&&(x=0);return tensor4d(c,e.shape)},e.prototype.localResponseNormalization4D=function(e,t,r,n,a){this.assertNotComplex(e,"localResponseNormalization4D");var o=e.shape[3],i=o-1,s=e.dataSync(),u=sizeFromShape(e.shape),l=new Float32Array(u);function p(e){for(var r=e%o,n=e-r+Math.max(0,r-t),a=e-r+Math.min(r+t,i),u=0;n<=a;n++){var l=s[n];u+=l*l}return u}for(var c=0;c=0&&e.get(o)1,"blockSize should be > 1 for depthToSpace, but was: "+t);for(var n=e.shape[0],a=e.shape[1],o=e.shape[2],i=e.shape[3],s=a*t,u=o*t,l=i/(t*t),p=e.dataSync(),c=new Float32Array(n*s*u*l),d=0,h=0;h=s))for(var _=d>1?(T-N)*(u-1)/(d-1):0,C=h>1?(E-S)*(l-1)/(h-1):0,A=0;A1?N*(u-1)+A*_:.5*(N+T)*(u-1);if(P<0||P>u-1)for(var k=0;k1?S*(l-1)+k*C:.5*(S+E)*(l-1))<0||H>l-1)for(D=0;D1?S*(l-1)+k*C:.5*(S+E)*(l-1))<0||H>l-1)for(D=0;D=e.size/s)throw new Error("Invalid indices: "+h+" does not index into "+e.shape);for(var y=0;y=n/a)throw new Error("Invalid indices: "+m+" does not index into "+r);for(var x=0;x0,"scheme must not be an empty string.");var n=e.getInstance();assert(null==n.managers[t],"A model store manager is already registered for scheme '"+t+"'."),n.managers[t]=r},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t},e.getSchemes=function(){return Object.keys(this.getInstance().managers)},e}();function parseURL(e){if(-1===e.indexOf(URL_SCHEME_SUFFIX))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+ModelStoreManagerRegistry.getSchemes().join(","));return{scheme:e.split(URL_SCHEME_SUFFIX)[0],path:e.split(URL_SCHEME_SUFFIX)[1]}}function cloneModelInternal(e,t,r){return void 0===r&&(r=!1),__awaiter(this,void 0,void 0,function(){var n,a,o,i,s,u,l,p,c;return __generator(this,function(d){switch(d.label){case 0:return assert(e!==t,"Old path and new path are the same: '"+e+"'"),assert((n=IORouterRegistry.getLoadHandlers(e)).length>0,"Copying failed because no load handler is found for source URL "+e+"."),assert(n.length<2,"Copying failed because more than one ("+n.length+") load handlers for source URL "+e+"."),a=n[0],assert((o=IORouterRegistry.getSaveHandlers(t)).length>0,"Copying failed because no save handler is found for destination URL "+t+"."),assert(o.length<2,"Copying failed because more than one ("+n.length+") save handlers for destination URL "+t+"."),i=o[0],s=parseURL(e).scheme,u=parseURL(e).path,l=s===parseURL(e).scheme,[4,a.load()];case 1:return p=d.sent(),r&&l?[4,ModelStoreManagerRegistry.getManager(s).removeModel(u)]:[3,3];case 2:d.sent(),d.label=3;case 3:return[4,i.save(p)];case 4:return c=d.sent(),!r||l?[3,6]:[4,ModelStoreManagerRegistry.getManager(s).removeModel(u)];case 5:d.sent(),d.label=6;case 6:return[2,c.modelArtifactsInfo]}})})}function listModels(){return __awaiter(this,void 0,void 0,function(){var e,t,r,n,a,o,i;return __generator(this,function(s){switch(s.label){case 0:e=ModelStoreManagerRegistry.getSchemes(),t={},r=0,n=e,s.label=1;case 1:return r0,"URL path for browserHTTPRequest must not be null, undefined or empty."),Array.isArray(e)&&assert(2===e.length,"URL paths for browserHTTPRequest must have a length of 2, (actual length is "+e.length+")."),this.path=e,null!=t&&null!=t.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t||{}}return e.prototype.save=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n,a;return __generator(this,function(o){switch(o.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,r=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,weightsManifest:r},t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.getFetchFunc()(this.path,t)];case 1:if((a=o.sent()).ok)return[2,{modelArtifactsInfo:getModelArtifactsInfoForJSON(e),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,Array.isArray(this.path)?this.loadBinaryModel():this.loadJSONModel()]})})},e.prototype.loadBinaryTopology=function(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(r){switch(r.label){case 0:return r.trys.push([0,3,,4]),[4,this.getFetchFunc()(this.path[0],this.requestInit)];case 1:if(!(e=r.sent()).ok)throw new Error("BrowserHTTPRequest.load() failed due to HTTP response: "+e.statusText);return[4,e.arrayBuffer()];case 2:return[2,r.sent()];case 3:throw t=r.sent(),new Error(this.path[0]+" not found. "+t);case 4:return[2]}})})},e.prototype.loadBinaryModel=function(){return __awaiter(this,void 0,void 0,function(){var e,t,r,n,a,o,i,s;return __generator(this,function(u){switch(u.label){case 0:return e=this.loadBinaryTopology(),[4,this.getFetchFunc()(this.path[1],this.requestInit)];case 1:if(!(t=u.sent()).ok)throw new Error("BrowserHTTPRequest.load() failed due to HTTP response: "+t.statusText);return[4,Promise.all([e,t])];case 2:return r=u.sent(),n=r[0],[4,r[1].json()];case 3:return null==(a=u.sent())?[3,5]:[4,this.loadWeights(a)];case 4:s=u.sent(),o=s[0],i=s[1],u.label=5;case 5:return[2,{modelTopology:n,weightSpecs:o,weightData:i}]}})})},e.prototype.loadJSONModel=function(){return __awaiter(this,void 0,void 0,function(){var e,t,r,n,a,o,i,s;return __generator(this,function(u){switch(u.label){case 0:return[4,this.getFetchFunc()(this.path,this.requestInit)];case 1:if(!(e=u.sent()).ok)throw new Error("BrowserHTTPRequest.load() failed due to HTTP response: "+e.statusText);return[4,e.json()];case 2:if(t=u.sent(),r=t.modelTopology,n=t.weightsManifest,null==r&&null==n)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==n?[3,4]:(i=t.weightsManifest,[4,this.loadWeights(i)]);case 3:s=u.sent(),a=s[0],o=s[1],u.label=4;case 4:return[2,{modelTopology:r,weightSpecs:a,weightData:o}]}})})},e.prototype.loadWeights=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n,a,o,i,s,u,l,p,c,d;return __generator(this,function(h){switch(h.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,r=parseUrl(t),n=r[0],a=r[1],o=this.weightPathPrefix||n,i=[],s=0,u=e;st?e.substring(r):""]}function isHTTPScheme(e){return null!=e.match(BrowserHTTPRequest.URL_SCHEME_REGEX)}var httpRequestRouter=function(e){return"undefined"==typeof fetch?null:(Array.isArray(e)?e.every(function(e){return isHTTPScheme(e)}):isHTTPScheme(e))?browserHTTPRequest(e):null};function browserHTTPRequest(e,t,r,n){return new BrowserHTTPRequest(e,t,r,n)}IORouterRegistry.registerSaveRouter(httpRequestRouter),IORouterRegistry.registerLoadRouter(httpRequestRouter);var PassthroughLoader=function(){function e(e,t,r){this.modelTopology=e,this.weightSpecs=t,this.weightData=r}return e.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(t){return e={},null!=this.modelTopology&&(e=__assign({modelTopology:this.modelTopology},e)),null!=this.weightSpecs&&this.weightSpecs.length>0&&(e=__assign({weightSpecs:this.weightSpecs},e)),null!=this.weightData&&this.weightData.byteLength>0&&(e=__assign({weightData:this.weightData},e)),[2,e]})})},e}(),PassthroughSaver=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return[2,this.saveHandler(e)]})})},e}();function fromMemory(e,t,r){return new PassthroughLoader(e,t,r)}function withSaveHandler(e){return new PassthroughSaver(e)}var registerSaveRouter=IORouterRegistry.registerSaveRouter,registerLoadRouter=IORouterRegistry.registerLoadRouter,getSaveHandlers=IORouterRegistry.getSaveHandlers,getLoadHandlers=IORouterRegistry.getLoadHandlers,io=Object.freeze({browserFiles:browserFiles,browserHTTPRequest:browserHTTPRequest,concatenateArrayBuffers:concatenateArrayBuffers,decodeWeights:decodeWeights,encodeWeights:encodeWeights,fromMemory:fromMemory,getLoadHandlers:getLoadHandlers,getModelArtifactsInfoForJSON:getModelArtifactsInfoForJSON,getSaveHandlers:getSaveHandlers,isHTTPScheme:isHTTPScheme,loadWeights:loadWeights,registerLoadRouter:registerLoadRouter,registerSaveRouter:registerSaveRouter,weightsLoaderFactory:weightsLoaderFactory,withSaveHandler:withSaveHandler,copyModel:copyModel,listModels:listModels,moveModel:moveModel,removeModel:removeModel});function confusionMatrix_(e,t,r){var n=convertToTensor(e,"labels","confusionMatrix"),a=convertToTensor(t,"predictions","confusionMatrix");assert(null==r||r>0&&Number.isInteger(r),"If provided, numClasses must be a positive integer, but got "+r),assert(1===n.rank,"Expected the rank of labels to be 1, but got "+n.rank),assert(1===a.rank,"Expected the rank of predictions to be 1, but got "+a.rank),assert(n.shape[0]===a.shape[0],"Mismatch in the number of examples: "+n.shape[0]+" vs. "+a.shape[0]+". Labels and predictions should have the same number of elements."),assert(r>0&&Number.isInteger(r),"numClasses is required to be a positive integer, but got "+r);var o=oneHot(n.asType("int32"),r),i=oneHot(a.asType("int32"),r);return o.transpose().matMul(i).asType("int32")}var confusionMatrix=op({confusionMatrix_:confusionMatrix_}),math=Object.freeze({confusionMatrix:confusionMatrix}),Serializable=function(){function e(){}return e.prototype.getClassName=function(){return this.constructor.className},e.fromConfig=function(e,t){return new e(t)},e}(),SerializationMap=function(){function e(){this.classNameMap={}}return e.getMap=function(){return null==e.instance&&(e.instance=new e),e.instance},e.register=function(t){e.getMap().classNameMap[t.className]=[t,t.fromConfig]},e}();function registerClass(e){assert(null!=e.className,"Class being registered does not have the static className property defined."),assert("string"==typeof e.className,"className is required to be a string, but got type "+typeof e.className),assert(e.className.length>0,"Class being registered has an empty-string as its className, which is disallowed."),SerializationMap.register(e)}var serialization=Object.freeze({Serializable:Serializable,SerializationMap:SerializationMap,registerClass:registerClass}),WEBGL_ENVS={HAS_WEBGL:!0},NODE_ENVS={IS_NODE:!0},CHROME_ENVS={IS_CHROME:!0},BROWSER_ENVS={IS_BROWSER:!0},CPU_ENVS={HAS_WEBGL:!1},ALL_ENVS={};function expectArraysClose(e,t,r){return null==r&&(r=ENV.get("TEST_EPSILON")),expectArraysPredicate(e,t,function(e,t){return areClose(e,Number(t),r)})}function expectArraysPredicate(e,t,r){if(e instanceof Tensor||t instanceof Tensor){if(e instanceof Tensor&&t instanceof Tensor){if(e.dtype!==t.dtype)throw new Error("Arrays are of different type actual: "+e.dtype+" vs expected: "+t.dtype+".");if(!arraysEqual(e.shape,t.shape))throw new Error("Arrays are of different shape actual: "+e.shape+" vs expected: "+t.shape+".")}}else{var n=e.constructor.name,a=t.constructor.name;if(n!==a)throw new Error("Arrays are of different type actual: "+n+" vs expected: "+a)}var o,i;if(o=e instanceof Tensor?e.dataSync():e,i=t instanceof Tensor?t.dataSync():t,o.length!==i.length)throw new Error("Arrays have different lengths actual: "+o.length+" vs expected: "+i.length+".\nActual: "+o+".\nExpected: "+i+".");for(var s=0;sr)}function expectValuesInRange(e,t,r){var n;n=e instanceof Tensor?e.dataSync():e;for(var a=0;ar)throw new Error("Value out of range:"+n[a]+" low: "+t+", high: "+r)}function expectArrayBuffersEqual(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var test_util=Object.freeze({WEBGL_ENVS:WEBGL_ENVS,NODE_ENVS:NODE_ENVS,CHROME_ENVS:CHROME_ENVS,BROWSER_ENVS:BROWSER_ENVS,CPU_ENVS:CPU_ENVS,ALL_ENVS:ALL_ENVS,expectArraysClose:expectArraysClose,expectPromiseToFail:expectPromiseToFail,expectArraysEqual:expectArraysEqual,expectNumbersClose:expectNumbersClose,expectValuesInRange:expectValuesInRange,expectArrayBuffersEqual:expectArrayBuffersEqual}),version="0.14.2",webgl=Object.freeze({gpgpu_util:gpgpu_util,webgl_util:webgl_util,MathBackendWebGL:MathBackendWebGL,GPGPUContext:GPGPUContext}),Optimizer=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.minimize=function(e,t,r){void 0===t&&(t=!1);var n=this.computeGradients(e,r),a=n.value,o=n.grads;return this.applyGradients(o),Object.keys(o).forEach(function(e){return o[e].dispose()}),t?a:(a.dispose(),null)},t.prototype.computeGradients=function(e,t){return variableGrads(e,t)},t}(Serializable),AdadeltaOptimizer=function(e){function t(t,r,n){void 0===n&&(n=null);var a=e.call(this)||this;return a.learningRate=t,a.rho=r,a.epsilon=n,a.accumulatedGrads={},a.accumulatedUpdates={},a.c=keep(scalar(-t)),a.rhoScalar=keep(scalar(r)),a.oneMinusRho=keep(scalar(1-r)),null===n&&(n=ENV.get("EPSILON")),a.epsilonScalar=keep(scalar(n)),a}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this,r=function(r){var a=ENV.engine.registeredVariables[r];null==n.accumulatedGrads[r]&&tidy(function(){t.accumulatedGrads[r]=zerosLike(a).variable(!1)}),null==n.accumulatedUpdates[r]&&tidy(function(){t.accumulatedUpdates[r]=zerosLike(a).variable(!1)});var o=e[r],i=n.accumulatedGrads[r],s=n.accumulatedUpdates[r];tidy(function(){var e=t.rhoScalar.mul(i).add(t.oneMinusRho.mul(o.square())),n=s.add(t.epsilonScalar).sqrt().div(i.add(t.epsilonScalar).sqrt()).mul(o),u=t.rhoScalar.mul(s).add(t.oneMinusRho.mul(n.square()));t.accumulatedGrads[r].assign(e),t.accumulatedUpdates[r].assign(u);var l=t.c.mul(n).add(a);a.assign(l)})},n=this;for(var a in e)r(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(t){return e.accumulatedUpdates[t].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon)},t.className="AdadeltaOptimizer",t}(Optimizer);registerClass(AdadeltaOptimizer);var AdagradOptimizer=function(e){function t(t,r){void 0===r&&(r=.1);var n=e.call(this)||this;return n.learningRate=t,n.initialAccumulatorValue=r,n.accumulatedGrads={},n.c=keep(scalar(-t)),n.epsilon=keep(scalar(ENV.get("EPSILON"))),n}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this,r=function(r){var a=ENV.engine.registeredVariables[r];null==n.accumulatedGrads[r]&&tidy(function(){t.accumulatedGrads[r]=fill(a.shape,t.initialAccumulatorValue).variable(!1)});var o=e[r],i=n.accumulatedGrads[r];tidy(function(){var e=i.add(o.square());t.accumulatedGrads[r].assign(e);var n=t.c.mul(o.div(e.add(t.epsilon).sqrt())).add(a);a.assign(n)})},n=this;for(var a in e)r(a)},t.prototype.dispose=function(){var e=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue)},t.className="AdagradOptimizer",t}(Optimizer);registerClass(AdagradOptimizer);var AdamOptimizer=function(e){function t(t,r,n,a){void 0===a&&(a=null);var o=e.call(this)||this;return o.learningRate=t,o.beta1=r,o.beta2=n,o.epsilon=a,o.accumulatedFirstMoment={},o.accumulatedSecondMoment={},o.c=keep(scalar(-t)),o.beta1Scalar=keep(scalar(r)),o.beta2Scalar=keep(scalar(n)),tidy(function(){o.accBeta1=scalar(r).variable(),o.accBeta2=scalar(n).variable()}),o.oneMinusBeta1=keep(scalar(1-r)),o.oneMinusBeta2=keep(scalar(1-n)),o.one=keep(scalar(1)),null===a&&(a=ENV.get("EPSILON")),o.epsScalar=keep(scalar(a)),o}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this;tidy(function(){var r=t.one.sub(t.accBeta1),n=t.one.sub(t.accBeta2);for(var a in e){var o=ENV.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var i=!1;t.accumulatedFirstMoment[a]=zerosLike(o).variable(i)}null==t.accumulatedSecondMoment[a]&&(i=!1,t.accumulatedSecondMoment[a]=zerosLike(o).variable(i));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedSecondMoment[a],p=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),c=t.beta2Scalar.mul(l).add(t.oneMinusBeta2.mul(s.square())),d=p.div(r),h=c.div(n);t.accumulatedFirstMoment[a].assign(p),t.accumulatedSecondMoment[a].assign(c);var f=t.c.mul(d.div(t.epsScalar.add(h.sqrt()))).add(o);o.assign(f)}t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar)),t.accBeta2.assign(t.accBeta2.mul(t.beta2Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(t){return e.accumulatedSecondMoment[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)},t.className="AdamOptimizer",t}(Optimizer);registerClass(AdamOptimizer);var AdamaxOptimizer=function(e){function t(t,r,n,a,o){void 0===a&&(a=null),void 0===o&&(o=0);var i=e.call(this)||this;return i.learningRate=t,i.beta1=r,i.beta2=n,i.epsilon=a,i.decay=o,i.accumulatedFirstMoment={},i.accumulatedWeightedInfNorm={},i.c=keep(scalar(-t)),i.beta1Scalar=keep(scalar(r)),i.beta2Scalar=keep(scalar(n)),i.decayScalar=keep(scalar(o)),tidy(function(){i.iteration=scalar(0).variable(),i.accBeta1=scalar(r).variable()}),i.oneMinusBeta1=keep(scalar(1-r)),i.one=keep(scalar(1)),null===a&&(a=ENV.get("EPSILON")),i.epsScalar=keep(scalar(a)),i}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this;tidy(function(){var r=t.one.sub(t.accBeta1),n=t.c.div(t.one.add(t.decayScalar.mul(t.iteration)));for(var a in e){var o=ENV.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var i=!1;t.accumulatedFirstMoment[a]=zerosLike(o).variable(i)}null==t.accumulatedWeightedInfNorm[a]&&(i=!1,t.accumulatedWeightedInfNorm[a]=zerosLike(o).variable(i));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedWeightedInfNorm[a],p=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),c=t.beta2Scalar.mul(l),d=s.abs(),h=c.maximum(d);t.accumulatedFirstMoment[a].assign(p),t.accumulatedWeightedInfNorm[a].assign(h);var f=n.div(r).mul(p.div(t.epsScalar.add(h))).add(o);o.assign(f)}t.iteration.assign(t.iteration.add(t.one)),t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(t){return e.accumulatedWeightedInfNorm[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},t.className="AdamaxOptimizer",t}(Optimizer);registerClass(AdamaxOptimizer);var SGDOptimizer=function(e){function t(t){var r=e.call(this)||this;return r.learningRate=t,r.setLearningRate(t),r}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this;Object.keys(e).forEach(function(r){var n=e[r],a=ENV.engine.registeredVariables[r];tidy(function(){var e=t.c.mul(n).add(a);a.assign(e)})})},t.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=keep(scalar(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,t){return new e(t.learningRate)},t.className="SGDOptimizer",t}(Optimizer);registerClass(SGDOptimizer);var MomentumOptimizer=function(e){function t(t,r,n){void 0===n&&(n=!1);var a=e.call(this,t)||this;return a.learningRate=t,a.momentum=r,a.useNesterov=n,a.m=scalar(a.momentum),a.accumulations={},a}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this,r=function(r){var a=ENV.engine.registeredVariables[r];null==n.accumulations[r]&&tidy(function(){t.accumulations[r]=zerosLike(a).variable(!1)});var o=n.accumulations[r],i=e[r];tidy(function(){var e,n=t.m.mul(o).add(i);e=t.useNesterov?t.c.mul(i.add(n.mul(t.m))).add(a):t.c.mul(n).add(a),t.accumulations[r].assign(n),a.assign(e)})},n=this;for(var a in e)r(a)},t.prototype.dispose=function(){if(e.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var t in this.accumulations)this.accumulations[t].dispose()},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)},t.className="MomentumOptimizer",t}(SGDOptimizer);registerClass(MomentumOptimizer);var RMSPropOptimizer=function(e){function t(t,r,n,a,o){void 0===r&&(r=.9),void 0===n&&(n=0),void 0===a&&(a=null),void 0===o&&(o=!1);var i=e.call(this)||this;return i.learningRate=t,i.decay=r,i.momentum=n,i.epsilon=a,i.accumulatedMeanSquares={},i.accumulatedMeanGrads={},i.accumulatedMoments={},i.c=keep(scalar(t)),i.decayScalar=keep(scalar(r)),i.momentumScalar=keep(scalar(n)),i.oneMinusDecay=keep(scalar(1-r)),i.centered=o,null===a&&(a=ENV.get("EPSILON")),i.epsilonScalar=keep(scalar(a)),i}return __extends(t,e),t.prototype.applyGradients=function(e){var t=this,r=function(r){var a=ENV.engine.registeredVariables[r];null==n.accumulatedMeanSquares[r]&&tidy(function(){t.accumulatedMeanSquares[r]=zerosLike(a).variable(!1)}),null==n.accumulatedMeanGrads[r]&&n.centered&&tidy(function(){t.accumulatedMeanGrads[r]=zerosLike(a).variable(!1)}),null==n.accumulatedMoments[r]&&tidy(function(){t.accumulatedMoments[r]=zerosLike(a).variable(!1)});var o=n.accumulatedMeanSquares[r],i=n.accumulatedMeanGrads[r],s=n.accumulatedMoments[r],u=e[r];tidy(function(){var e=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u.square()));if(t.centered){var n=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u)),l=t.momentumScalar.mul(s).add(t.c.mul(u).div(e.sub(n.square().add(t.epsilonScalar)).sqrt()));t.accumulatedMeanSquares[r].assign(e),t.accumulatedMeanGrads[r].assign(n),t.accumulatedMoments[r].assign(l);var p=a.sub(l);a.assign(p)}else{var c=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u.square()));l=t.momentumScalar.mul(s).add(t.c.mul(u).div(c.add(t.epsilonScalar).sqrt())),t.accumulatedMeanSquares[r].assign(c),t.accumulatedMoments[r].assign(l),p=a.sub(l),a.assign(p)}})},n=this;for(var a in e)r(a)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(t){return e.accumulatedMeanSquares[t].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(t){return e.accumulatedMeanGrads[t].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(t){return e.accumulatedMoments[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},t.className="RMSPropOptimizer",t}(Optimizer);registerClass(RMSPropOptimizer);var OptimizerConstructors=function(){function e(){}return e.sgd=function(e){return new SGDOptimizer(e)},e.momentum=function(e,t,r){return void 0===r&&(r=!1),new MomentumOptimizer(e,t,r)},e.rmsprop=function(e,t,r,n,a){return void 0===t&&(t=.9),void 0===r&&(r=0),void 0===n&&(n=null),void 0===a&&(a=!1),new RMSPropOptimizer(e,t,r,n,a)},e.adam=function(e,t,r,n){return void 0===e&&(e=.001),void 0===t&&(t=.9),void 0===r&&(r=.999),void 0===n&&(n=null),new AdamOptimizer(e,t,r,n)},e.adadelta=function(e,t,r){return void 0===e&&(e=.001),void 0===t&&(t=.95),void 0===r&&(r=null),new AdadeltaOptimizer(e,t,r)},e.adamax=function(e,t,r,n,a){return void 0===e&&(e=.002),void 0===t&&(t=.9),void 0===r&&(r=.999),void 0===n&&(n=null),void 0===a&&(a=0),new AdamaxOptimizer(e,t,r,n,a)},e.adagrad=function(e,t){return void 0===t&&(t=.1),new AdagradOptimizer(e,t)},e}(),train={sgd:OptimizerConstructors.sgd,momentum:OptimizerConstructors.momentum,adadelta:OptimizerConstructors.adadelta,adagrad:OptimizerConstructors.adagrad,rmsprop:OptimizerConstructors.rmsprop,adamax:OptimizerConstructors.adamax,adam:OptimizerConstructors.adam},setBackend=Environment.setBackend,getBackend=Environment.getBackend,disposeVariables=Environment.disposeVariables,memory=Environment.memory;setOpHandler(ops);var extendStatics$1=function(e,t){return(extendStatics$1=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function __extends$1(e,t){function r(){this.constructor=e}extendStatics$1(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var __assign$1=function(){return(__assign$1=Object.assign||function(e){for(var t,r=1,n=arguments.length;r0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]t?1:0}function reverseNumberCompare(e,t){return-1*numberCompare(e,t)}function stringToDType(e){switch(e){case"float32":return"float32";default:throw new ValueError("Invalid dtype: "+e)}}function unique(e){if(null==e)return e;for(var t=[],r=0,n=e;r=0),assert$1(n>=r),Array.isArray(e)&&e.length>=r&&e.length<=n&&e.every(function(e){return typeof e===t})}function calcL2Norms(e,t){return tidy(function(){return sqrt(sum$1(mulStrict(e,e),t,!0))})}var Constraint=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.getConfig=function(){return{}},t}(serialization.Serializable),MaxNorm=function(e){function t(t){var r=e.call(this)||this;return r.defaultMaxValue=2,r.defaultAxis=0,r.maxValue=null!=t.maxValue?t.maxValue:r.defaultMaxValue,r.axis=null!=t.axis?t.axis:r.defaultAxis,r}return __extends$1(t,e),t.prototype.apply=function(e){var t=this;return tidy(function(){var r=calcL2Norms(e,t.axis),n=clipByValue(r,0,t.maxValue);return mul(e,div(n,add(getScalar(epsilon()),r)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(Constraint);serialization.registerClass(MaxNorm);var UnitNorm=function(e){function t(t){var r=e.call(this)||this;return r.defaultAxis=0,r.axis=null!=t.axis?t.axis:r.defaultAxis,r}return __extends$1(t,e),t.prototype.apply=function(e){var t=this;return tidy(function(){return div(e,add(getScalar(epsilon()),calcL2Norms(e,t.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(Constraint);serialization.registerClass(UnitNorm);var NonNeg=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e){return relu(e)},t.className="NonNeg",t}(Constraint);serialization.registerClass(NonNeg);var MinMaxNorm=function(e){function t(t){var r=e.call(this)||this;return r.defaultMinValue=0,r.defaultMaxValue=1,r.defaultRate=1,r.defaultAxis=0,r.minValue=null!=t.minValue?t.minValue:r.defaultMinValue,r.maxValue=null!=t.maxValue?t.maxValue:r.defaultMaxValue,r.rate=null!=t.rate?t.rate:r.defaultRate,r.axis=null!=t.axis?t.axis:r.defaultAxis,r}return __extends$1(t,e),t.prototype.apply=function(e){var t=this;return tidy(function(){var r=calcL2Norms(e,t.axis),n=add(mul(getScalar(t.rate),clipByValue(r,t.minValue,t.maxValue)),mul(getScalar(1-t.rate),r));return mul(e,div(n,add(getScalar(epsilon()),r)))})},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},t.className="MinMaxNorm",t}(Constraint);serialization.registerClass(MinMaxNorm);var CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function serializeConstraint(e){return serializeKerasObject(e)}function deserializeConstraint(e,t){return void 0===t&&(t={}),deserializeKerasObject(e,serialization.SerializationMap.getMap().classNameMap,t,"constraint")}function getConstraint(e){return null==e?null:"string"==typeof e?deserializeConstraint({className:e in CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP?CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e,config:{}}):e instanceof Constraint?e:deserializeConstraint(e)}function maxNorm(e){return new MaxNorm(e)}function unitNorm(e){return new UnitNorm(e)}function nonNeg(){return new NonNeg}function minMaxNorm(e){return new MinMaxNorm(e)}var exports_constraints=Object.freeze({maxNorm:maxNorm,unitNorm:unitNorm,nonNeg:nonNeg,minMaxNorm:minMaxNorm}),nameMap=new Map,VALID_DATA_FORMAT_VALUES=["channelsFirst","channelsLast"];function checkDataFormat(e){checkStringTypeUnionValue(VALID_DATA_FORMAT_VALUES,"DataFormat",e)}var VALID_PADDING_MODE_VALUES=["valid","same","causal"];function checkPaddingMode(e){checkStringTypeUnionValue(VALID_PADDING_MODE_VALUES,"PaddingMode",e)}var VALID_POOL_MODE_VALUES=["max","avg"];function checkPoolMode(e){checkStringTypeUnionValue(VALID_POOL_MODE_VALUES,"PoolMode",e)}var _nameScopeStack=[],_nameScopeDivider="/";function nameScope(e,t){_nameScopeStack.push(e);try{var r=t();return _nameScopeStack.pop(),r}catch(e){throw _nameScopeStack.pop(),e}}function currentNameScopePrefix(){return 0===_nameScopeStack.length?"":_nameScopeStack.join(_nameScopeDivider)+_nameScopeDivider}function getScopedTensorName(e){if(!isValidTensorName(e))throw new Error("Not a valid tensor name: '"+e+"'");return currentNameScopePrefix()+e}function getUniqueTensorName(e){if(!isValidTensorName(e))throw new Error("Not a valid tensor name: '"+e+"'");nameMap.has(e)||nameMap.set(e,0);var t=nameMap.get(e);if(nameMap.set(e,nameMap.get(e)+1),t>0){var r=e+"_"+t;return nameMap.set(r,1),r}return e}var tensorNameRegex=new RegExp(/^[A-Za-z][-A-Za-z0-9\._\/]*$/);function isValidTensorName(e){return!!e.match(tensorNameRegex)}function isInteger(e){return e===parseInt(e.toString(),10)}function arrayProd(e,t,r){null==t&&(t=0),null==r&&(r=e.length);for(var n=1,a=t;a= 2 but got x shape = "+e.shape+" and y shape = "+t.shape);if(t.rank>=3&&(n=e.shape.slice(-1)[0])!==(i=t.shape.slice(-2)[0]))throw new NotImplementedError("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+e.shape+" and y shape = "+t.shape);if(2===e.rank&&2===t.rank)return matMul(e,t);var r=e.shape.slice(),n=r.pop();e=e.reshape([-1,n]);var a=t.shape.slice(),o=a.pop(),i=a.pop(),s=a.concat([o]),u=Array.from({length:t.rank},function(e,r){return 0===r?t.rank-2:r<=t.rank-2?r-1:r});t=t.transpose(u).reshape([i,-1]);var l=r.concat(s);return matMul(e,t).reshape(l)}function gather$1(e,t,r){return tidy(function(){return t=Array.isArray(t)?tensor1d(t,"int32"):t.toInt(),gather(e,t,r)})}function square$1(e){return mulStrict(e,e)}function biasAdd(e,t,r){return tidy(function(){if(null==r&&(r=imageDataFormat()),checkDataFormat(r),1!==t.rank&&t.rank!==e.rank)throw new ValueError("Unexpected bias dimensions: "+t.rank+"; expected it to be 1 or "+e.rank);var n,a=t.shape;if(5===e.rank)"channelsFirst"===r?n=1===a.length?e.add(t.reshape([1,a[0],1,1,1])):e.add(t.reshape([1,a[3],a[0],a[1],a[2]])):"channelsLast"===r&&(n=1===a.length?e.add(t.reshape([1,1,1,1,a[0]])):e.add(t.reshape([1].concat(a))));else if(4===e.rank)"channelsFirst"===r?n=1===a.length?e.add(t.reshape([1,a[0],1,1])):e.add(t.reshape([1,a[2],a[0],a[1]])):"channelsLast"===r&&(n=1===a.length?e.add(t.reshape([1,1,1,a[0]])):e.add(t.reshape([1].concat(a))));else if(3===e.rank)"channelsFirst"===r?n=1===a.length?e.add(t.reshape([1,a[0],1])):e.add(t.reshape([1,a[1],a[0]])):"channelsLast"===r&&(n=1===a.length?e.add(t.reshape([1,1,a[0]])):e.add(t.reshape([1].concat(a))));else{if(!(e.rank<3))throw new ValueError("Unsupported input rank by biasAdd: "+e.rank);n=e.add(t)}return n})}function elu$1(e,t){if(void 0===t&&(t=1),1!==t)throw new NotImplementedError("Support for alpha values other than 1 ("+t+") is not implemented yet.");return elu(e)}function softsign(e){return tidy(function(){return div(e,add(getScalar(1),abs(e)))})}function dropout(e,t,r,n){return tidy(function(){if(null!=r&&!util.arraysEqual(e.shape,r))throw new NotImplementedError("Non-default noise shape is not implemented yet: "+JSON.stringify(r));if(null!=n)throw new NotImplementedError("seed is not implemented for dropout yet.");var a=step(add(neg(t),randomUniform(e.shape,0,1,"float32")));return a=mul(div(getScalar(1),sub(getScalar(1),t)),a),mul(e,a)})}function hardSigmoid(e){return tidy(function(){var t=add(getScalar(.5),mul(getScalar(.2),e));return clipByValue(t,0,1)})}function inTrainPhase(e,t,r){return void 0===r&&(r=!1),r?e():t()}var VALID_FAN_MODE_VALUES=["fanIn","fanOut","fanAvg"];function checkFanMode(e){checkStringTypeUnionValue(VALID_FAN_MODE_VALUES,"FanMode",e)}var VALID_DISTRIBUTION_VALUES=["normal","uniform"];function checkDistribution(e){checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES,"Distribution",e)}var Initializer=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.fromConfigUsesCustomObjects=function(){return!1},t.prototype.getConfig=function(){return{}},t}(serialization.Serializable),Zeros=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e,t){return zeros(e,t)},t.className="Zeros",t}(Initializer);serialization.registerClass(Zeros);var Ones=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.apply=function(e,t){return ones$1(e,t)},t.className="Ones",t}(Initializer);serialization.registerClass(Ones);var Constant=function(e){function t(t){var r=e.call(this)||this;if("object"!=typeof t)throw new ValueError("Expected argument of type ConstantConfig but got "+t);if(void 0===t.value)throw new ValueError("config must have value set but got "+t);return r.value=t.value,r}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=this;return tidy(function(){return mul(scalar(r.value),ones$1(e,t))})},t.prototype.getConfig=function(){return{value:this.value}},t.className="Constant",t}(Initializer);serialization.registerClass(Constant);var RandomUniform=function(e){function t(t){var r=e.call(this)||this;return r.DEFAULT_MINVAL=-.05,r.DEFAULT_MAXVAL=.05,r.minval=t.minval||r.DEFAULT_MINVAL,r.maxval=t.maxval||r.DEFAULT_MAXVAL,r.seed=t.seed,r}return __extends$1(t,e),t.prototype.apply=function(e,t){return randomUniform(e,this.minval,this.maxval,t)},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(Initializer);serialization.registerClass(RandomUniform);var RandomNormal=function(e){function t(t){var r=e.call(this)||this;return r.DEFAULT_MEAN=0,r.DEFAULT_STDDEV=.05,r.mean=t.mean||r.DEFAULT_MEAN,r.stddev=t.stddev||r.DEFAULT_STDDEV,r.seed=t.seed,r}return __extends$1(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new NotImplementedError("randomNormal does not support dType "+t+".");return randomNormal$1(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(Initializer);serialization.registerClass(RandomNormal);var TruncatedNormal=function(e){function t(t){var r=e.call(this)||this;return r.DEFAULT_MEAN=0,r.DEFAULT_STDDEV=.05,r.mean=t.mean||r.DEFAULT_MEAN,r.stddev=t.stddev||r.DEFAULT_STDDEV,r.seed=t.seed,r}return __extends$1(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new NotImplementedError("truncatedNormal does not support dType "+t+".");return truncatedNormal(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(Initializer);serialization.registerClass(TruncatedNormal);var Identity=function(e){function t(t){var r=e.call(this)||this;return r.gain=null!=t.gain?scalar(t.gain):getScalar(1),r}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=this;return tidy(function(){if(2!==e.length||e[0]!==e[1])throw new ValueError("Identity matrix initializer can only be used for 2D square matrices.");return mul(r.gain,eye(e[0]))})},t.prototype.getConfig=function(){return{gain:this.gain.get()}},t.className="Identity",t}(Initializer);function computeFans(e,t){var r,n;if(void 0===t&&(t="channelsLast"),checkDataFormat(t),2===e.length)r=e[0],n=e[1];else if(-1!==[3,4,5].indexOf(e.length))if("channelsFirst"===t){var a=arrayProd(e,2);r=e[1]*a,n=e[0]*a}else"channelsLast"===t&&(a=arrayProd(e,0,e.length-2),r=e[e.length-2]*a,n=e[e.length-1]*a);else{var o=arrayProd(e);r=Math.sqrt(o),n=Math.sqrt(o)}return[r,n]}serialization.registerClass(Identity);var VarianceScaling=function(e){function t(t){var r=e.call(this)||this;if(t.scale<0)throw new ValueError("scale must be a positive float. Got: "+t.scale);return r.scale=null==t.scale?1:t.scale,r.mode=t.mode,checkFanMode(r.mode),r.distribution=t.distribution,checkDistribution(r.distribution),r.seed=t.seed,r}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=computeFans(e),n=r[0],a=r[1],o=this.scale;if("fanIn"===this.mode?o/=Math.max(1,n):"fanOut"===this.mode?o/=Math.max(1,a):o/=Math.max(1,(n+a)/2),"normal"===this.distribution){var i=Math.sqrt(o);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new NotImplementedError(this.getClassName()+" does not support dType "+t+".");return truncatedNormal(e,0,i,t,this.seed)}var s=Math.sqrt(3*o);return randomUniform(e,-s,s,t)},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(Initializer);serialization.registerClass(VarianceScaling);var GlorotUniform=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==t?null:t.seed})||this}return __extends$1(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="GlorotUniform",t}(VarianceScaling);serialization.registerClass(GlorotUniform);var GlorotNormal=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends$1(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="GlorotNormal",t}(VarianceScaling);serialization.registerClass(GlorotNormal);var HeNormal=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends$1(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="HeNormal",t}(VarianceScaling);serialization.registerClass(HeNormal);var LeCunNormal=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends$1(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="LeCunNormal",t}(VarianceScaling);serialization.registerClass(LeCunNormal);var Orthogonal=function(e){function t(t){var r=e.call(this)||this;if(r.DEFAULT_GAIN=1,r.gain=null==t.gain?r.DEFAULT_GAIN:t.gain,r.seed=t.seed,null!=r.seed)throw new NotImplementedError("Random seed is not implemented for Orthogonal Initializer yet.");return r}return __extends$1(t,e),t.prototype.apply=function(e,t){var r=this;return tidy(function(){if(2!==e.length)throw new NotImplementedError("The Orthogonal Initializer does not support non-2D shapes yet.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+e[0]*e[1]+") elements: Slowness may result.");var t=randomNormal$1(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32"),n=linalg_ops.gramSchmidt(t);return e[0]>e[1]&&(n=n.transpose()),mul(getScalar(r.gain),n)})},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(Initializer);serialization.registerClass(Orthogonal);var INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",identity:"Identity",leCunNormal:"LeCunNormal",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function deserializeInitializer(e,t){return void 0===t&&(t={}),deserializeKerasObject(e,serialization.SerializationMap.getMap().classNameMap,t,"initializer")}function serializeInitializer(e){return serializeKerasObject(e)}function getInitializer(e){if("string"==typeof e){var t=e in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP?INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e;return"GlorotUniform"===t?new GlorotUniform:"GlorotNormal"===t?new GlorotNormal:"HeNormal"===t?new HeNormal:"LeCunNormal"===t?new LeCunNormal:deserializeInitializer({className:t,config:{}})}return e instanceof Initializer?e:deserializeInitializer(e)}function zeros$1(){return new Zeros}function ones$1$1(){return new Ones}function constant(e){return new Constant(e)}function randomUniform$1(e){return new RandomUniform(e)}function randomNormal$2(e){return new RandomNormal(e)}function truncatedNormal$1(e){return new TruncatedNormal(e)}function identity(e){return new Identity(e)}function varianceScaling(e){return new VarianceScaling(e)}function glorotUniform(e){return new GlorotUniform(e)}function glorotNormal(e){return new GlorotNormal(e)}function heNormal(e){return new HeNormal(e)}function leCunNormal(e){return new LeCunNormal(e)}function orthogonal(e){return new Orthogonal(e)}var exports_initializers=Object.freeze({zeros:zeros$1,ones:ones$1$1,constant:constant,randomUniform:randomUniform$1,randomNormal:randomNormal$2,truncatedNormal:truncatedNormal$1,identity:identity,varianceScaling:varianceScaling,glorotUniform:glorotUniform,glorotNormal:glorotNormal,heNormal:heNormal,leCunNormal:leCunNormal,orthogonal:orthogonal});function isArrayOfShapes(e){return Array.isArray(e)&&Array.isArray(e[0])}function normalizeShapeList(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function getExactlyOneTensor(e){var t;if(Array.isArray(e)){if(1!==e.length)throw new ValueError("Expected Tensor length to be 1; got "+e.length);t=e[0]}else t=e;return t}function getExactlyOneShape(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return(e=e)[0];throw new ValueError("Expected exactly 1 Shape; got "+e.length)}return e}function countParamsInWeights(e){for(var t=0,r=0,n=e;r1)throw new AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(0===this.inboundNodes.length)throw new AttributeError("Layer "+this.name+" is not connected, no input to return.");return singletonOrArray(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new AttributeError("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return singletonOrArray(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this._trainableWeights:[]},set:function(e){this._trainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._nonTrainableWeights:this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},t.prototype.assertInputCompatibility=function(e){if(e=toList(e),null!=this.inputSpec&&0!==this.inputSpec.length){var t=toList(this.inputSpec);if(e.length!==t.length)throw new ValueError("Layer "+this.name+" expects "+t.length+" inputs, but it received "+e.length+" input tensors. Input received: "+e);for(var r=0;r=0?i[u]:i[i.length+u];if(null!=l&&-1===[l,null].indexOf(p))throw new ValueError("Input "+r+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+l+" but got shape "+i+".")}}if(null!=a.shape)for(var c=0;c0&&Array.isArray(f[0])?f.map(function(n,a){return new SymbolicTensor(g,n,r,toList(e),t,r.name,a)}):new SymbolicTensor(g,f,r,toList(e),t,r.name),r.addInboundNode(e,m,null,null,h,f,t),r._refCount++,null!=r.activityRegularizer)throw new NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m})},t.prototype.warnOnIncompatibleInputShape=function(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(e)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var t=!1;this.batchInputShape.forEach(function(r,n){null!=r&&null!=e[n]&&e[n]!==r&&(t=!0)}),t&&console.warn("The shape of the input tensor ("+JSON.stringify(e)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new AttributeError("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],t=0,r=this.inboundNodes;t0)&&(t=e.sourceLayer,r=e.nodeIndex),0===t.inboundNodes.length)return[e];var n=t.inboundNodes[r];if(0===n.inboundLayers.length)return n.inputTensors;for(var a=[],o=0;oe.SKIP_FIRST_BATCHES&&(this.batchDurationsMillis.push(r-this.batchStartMillis),this.batchDurationsMillis.length>=e.DECISION_BATCH_COUNT&&(n=this.batchDurationsMillis.reduce(function(e,t){return e+t})/this.batchDurationsMillis.length,this.autoYieldEveryBatches=Math.round(e.THRESHOLD_MILLIS/n),this.autoYieldEveryBatches<1&&(this.autoYieldEveryBatches=1))),this.batchStartMillis=util.now(),this.lastYieldBatchCount=this.batchCount,[3,6];case 3:return this.batchCount-this.lastYieldBatchCount>=this.autoYieldEveryBatches?[4,nextFrame()]:[3,6];case 4:return a.sent(),[4,this.resolveOneTensorInLogs(t)];case 5:a.sent(),this.lastYieldBatchCount=this.batchCount,a.label=6;case 6:return[3,9];case 7:return"batch"!==this.yieldEvery?[3,9]:[4,nextFrame()];case 8:a.sent(),a.label=9;case 9:return[2]}})})},e.prototype.maybeYieldOnEpoch=function(){return __awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(e){switch(e.label){case 0:return"epoch"!==this.yieldEvery?[3,2]:[4,nextFrame()];case 1:e.sent(),e.label=2;case 2:return[2]}})})},e.SKIP_FIRST_BATCHES=1,e.DECISION_BATCH_COUNT=2,e.THRESHOLD_MILLIS=16,e}(),BaseLogger=function(e){function t(t){var r=e.call(this)||this;return r.yieldEvery=t||"auto",r}return __extends$1(t,e),t.prototype.onTrainBegin=function(e){return __awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(e){return this.autoYielder=new ModelTrainingYielder(this.yieldEvery),[2]})})},t.prototype.onEpochBegin=function(e){return __awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(e){return this.seen=0,this.totals={},[2]})})},t.prototype.onBatchEnd=function(e,t){return __awaiter$1(this,void 0,void 0,function(){var e,r,n,a,o=this;return __generator$1(this,function(i){switch(i.label){case 0:return[4,this.autoYielder.maybeYieldOnBatch(t)];case 1:for(a in i.sent(),null==t&&(t={}),e=null==t.size?0:t.size,this.seen+=e,r=function(r){var a=t[r];if("number"==typeof a)n.totals.hasOwnProperty(r)||(n.totals[r]=0),n.totals[r]=n.totals[r]+a*e;else{var i=void 0;r in n.totals?i=n.totals[r]:n.totals[r]=getScalar(0),n.totals[r]=tidy(function(){return add(o.totals[r],mul(a,getScalar(e)))}),null!=i&&i.dispose()}},n=this,t)r(a);return[2]}})})},t.prototype.onEpochEnd=function(e,t){return __awaiter$1(this,void 0,void 0,function(){var e,r,n,a,o,i=this;return __generator$1(this,function(s){switch(s.label){case 0:return[4,this.autoYielder.maybeYieldOnEpoch()];case 1:if(s.sent(),null!=t)for(e=function(e){if(null==r.totals[e])return"continue";"number"==typeof r.totals[e]?t[e]=r.totals[e]/r.seen:tidy(function(){t[e]=mul(div(getScalar(1),getScalar(i.seen)),i.totals[e]),i.totals[e].dispose(),keep(t[e])})},r=this,n=0,a=this.params.metrics;n=0&&Number.isInteger(t),"Verbosity level is expected to be an integer >= 0, but got "+t),e.checkForDuplicate(r),null==e.constructors[t]&&(e.constructors[t]=[]),e.constructors[t].push(r)},e.checkForDuplicate=function(t){for(var r in e.constructors)e.constructors[+r].forEach(function(e){if(e===t)throw new ValueError("Duplicate callback constructor.")})},e.clear=function(){e.constructors={}},e.createCallbacks=function(t){var r=[];for(var n in e.constructors){var a=+n;t>=a&&r.push.apply(r,e.constructors[a])}return r.map(function(e){return new e})},e.constructors={},e}();function configureCallbacks(e,t,r,n,a,o,i,s,u,l){var p=new History,c=[new BaseLogger(t)].concat(CallbackConstructorRegistry.createCallbacks(r));null!=e&&c.push.apply(c,e),c.push(p);var d=new CallbackList(c);return d.setParams({epochs:n,initialEpoch:a,samples:o,steps:i,batchSize:s,verbose:r,doValidation:u,metrics:l}),{callbackList:d,history:p}}function l2Normalize(e,t){return tidy(function(){var r=sum$1(square$1(e),t,!0),n=mul(scalar(epsilon()),onesLike(e)),a=sqrt(maximum(r,n));return div(e,a)})}function meanSquaredError$1(e,t){return tidy(function(){return mean(square$1(sub(t,e)),-1)})}function meanAbsoluteError(e,t){return tidy(function(){return mean(abs(sub(t,e)),-1)})}function meanAbsolutePercentageError(e,t){return tidy(function(){var r=sub(e,t),n=clipByValue(abs(e),epsilon(),Number.MAX_VALUE),a=abs(div(r,n));return mul(getScalar(100),mean(a,-1))})}function meanSquaredLogarithmicError(e,t){return tidy(function(){var r=getScalar(1),n=clipByValue(t,epsilon(),Number.MAX_VALUE),a=log$1(add(r,n)),o=clipByValue(e,epsilon(),Number.MAX_VALUE),i=log$1(add(r,o));return mean(square$1(sub(a,i)),-1)})}function squaredHinge(e,t){return tidy(function(){var r=getScalar(0),n=getScalar(1),a=maximum(r,sub(n,mul(e,t)));return mean(square$1(a),-1)})}function hinge(e,t){return tidy(function(){var r=getScalar(0),n=getScalar(1),a=maximum(r,sub(n,mul(e,t)));return mean(a,-1)})}function categoricalHinge(e,t){return tidy(function(){var r=getScalar(0),n=getScalar(1),a=sum$1(mul(e,t),-1),o=max(mul(sub(n,e),t),-1);return maximum(r,add(n,sub(o,a)))})}function logcosh(e,t){return tidy(function(){var r=getScalar(Math.log(2)),n=sub(t,e),a=sub(add(n,softplus(mul(getScalar(-2),n))),r);return mean(a,-1)})}function categoricalCrossentropy(e,t,r){return void 0===r&&(r=!1),tidy(function(){if(r)t=softmax(t);else{var n=sum$1(t,t.shape.length-1,!0);t=div(t,n)}return t=clipByValue(t,epsilon(),1-epsilon()),neg(sum$1(mul(e.toFloat(),log$1(t)),t.shape.length-1))})}function sparseCategoricalCrossentropy(e,t){return tidy(function(){var r=floor(flatten$1(e)).toInt(),n=(t=clipByValue(t,epsilon(),1-epsilon())).shape;return categoricalCrossentropy(oneHot(r,n[n.length-1]).reshape(n),t,!1)})}function sigmoidCrossEntropyWithLogits(e,t){if(!util.arraysEqual(e.shape,t.shape))throw new ValueError("logits and labels must have the same shape, but got shapes "+JSON.stringify(e.shape)+" and "+JSON.stringify(t.shape));return tidy(function(){var r=t.relu(),n=t.abs().neg();return r.sub(t.mul(e)).add(n.exp().log1p())})}function binaryCrossentropy(e,t){return tidy(function(){var r;return r=clipByValue(t,epsilon(),1-epsilon()),r=log$1(div(r,sub(getScalar(1),r))),mean(sigmoidCrossEntropyWithLogits(e,r),-1)})}function kullbackLeiblerDivergence(e,t){return tidy(function(){var r=clipByValue(e,epsilon(),1),n=clipByValue(t,epsilon(),1);return sum$1(mul(e,log$1(div(r,n))),-1)})}function poisson(e,t){return tidy(function(){var r=log$1(add(getScalar(epsilon()),t));return mean(sub(t,mul(e,r)),-1)})}function cosineProximity(e,t){return tidy(function(){var r=l2Normalize(e,-1),n=l2Normalize(t,-1),a=mul(r,n);return neg(sum$1(a,-1))})}function get(e){var t={meanSquaredError:meanSquaredError$1,meanAbsoluteError:meanAbsoluteError,meanAbsolutePercentageError:meanAbsolutePercentageError,meanSquaredLogarithmicError:meanSquaredLogarithmicError,squaredHinge:squaredHinge,hinge:hinge,categoricalHinge:categoricalHinge,logcosh:logcosh,categoricalCrossentropy:categoricalCrossentropy,sparseCategoricalCrossentropy:sparseCategoricalCrossentropy,binaryCrossentropy:binaryCrossentropy,kullbackLeiblerDivergence:kullbackLeiblerDivergence,poisson:poisson,cosineProximity:cosineProximity};if("string"==typeof e){if(e in t)return t[e];var r="Unknown loss "+e;throw e.toLowerCase().includes("softmaxcrossentropy")&&(r="Unknown loss "+e+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new ValueError(r)}return e}function binaryAccuracy(e,t){return tidy(function(){var r=mul(getScalar(.5),onesLike(t)),n=cast$1(greater(t,r),e.dtype);return mean(equal(e,n),-1)})}function categoricalAccuracy(e,t){return tidy(function(){return cast$1(equal(argMax(e,-1),argMax(t,-1)),"float32")})}function truePositives(e,t){return tidy(function(){var r=getScalar(1);return logicalAnd(e.equal(r),t.equal(r)).sum().cast("float32")})}function falseNegatives(e,t){return tidy(function(){var r=getScalar(1),n=getScalar(0);return logicalAnd(e.equal(r),t.equal(n)).sum().cast("float32")})}function falsePositives(e,t){return tidy(function(){var r=getScalar(1),n=getScalar(0);return logicalAnd(e.equal(n),t.equal(r)).sum().cast("float32")})}function precision(e,t){return tidy(function(){var r=getScalar(0),n=truePositives(e,t),a=falsePositives(e,t),o=n.add(a);return where(greater(o,r),n.div(o),r).cast("float32")})}function recall(e,t){return tidy(function(){var r=getScalar(0),n=truePositives(e,t),a=falseNegatives(e,t),o=n.add(a);return where(greater(o,r),n.div(o),r).cast("float32")})}function binaryCrossentropy$1(e,t){return binaryCrossentropy(e,t)}function sparseCategoricalAccuracy(e,t){return e.rank===t.rank&&(e=e.squeeze([e.rank-1])),(t=t.argMax(-1)).dtype!==e.dtype&&(t=t.asType(e.dtype)),equal(e,t).asType("float32")}var mse$1=meanSquaredError$1,MSE$1=meanSquaredError$1,mae$1=meanAbsoluteError,MAE$1=meanAbsoluteError,mape$1=meanAbsolutePercentageError,MAPE$1=meanAbsolutePercentageError,categoricalCrossentropy$1=categoricalCrossentropy,cosine$1=cosineProximity,sparseCategoricalCrossentropy$1=sparseCategoricalCrossentropy;function get$1(e){var t={binaryAccuracy:binaryAccuracy,categoricalAccuracy:categoricalAccuracy,precision:precision,categoricalCrossentropy:categoricalCrossentropy$1,sparseCategoricalCrossentropy:sparseCategoricalCrossentropy$1,mse:mse$1,MSE:MSE$1,mae:mae$1,MAE:MAE$1,mape:mape$1,MAPE:MAPE$1,cosine:cosine$1};if("string"==typeof e&&e in t)return t[e];if("string"!=typeof e&&null!=e)return e;throw new ValueError("Unknown metric "+e)}function getOptimizer(e){var t={Adagrad:function(){return train.adagrad(.01)},Adadelta:function(){return train.adadelta(1,.95,epsilon())},Adam:function(){return train.adam(.001,.9,.999,epsilon())},Adamax:function(){return train.adamax(.002,.9,.999,epsilon(),0)},RMSProp:function(){return train.rmsprop(.001,.9,0,epsilon())},SGD:function(){return train.sgd(.01)}};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new ValueError("Unknown Optimizer "+e)}function printSummary(e,t,r,n){void 0===n&&(n=console.log);var a,o=isModelSequentialLike(e),i=["Layer (type)","Output shape","Param #"];if(o?(t=t||65,r=r||[.45,.85,1]):(t=t||98,r=r||[.33,.55,.67,1]),r[r.length-1]<=1&&(r=r.map(function(e){return Math.floor(t*e)})),!o)for(var s in i.push("Receives inputs"),a=[],e.nodesByDepth)a.push.apply(a,e.nodesByDepth[s]);n("_".repeat(t)),printRow(i,r,n),n("=".repeat(t));for(var u=e.layers,l=0;l1||1===s.length&&s[0].inboundLayers.length>1){t=!1;break}n.push.apply(n,s)}if(t)for(var u=0,l=e.layers;u0&&(n=n.slice(0,n.length-1)+" "),n=(n+=e[a]).slice(0,t[a]),n+=" ".repeat(t[a]-n.length);r(n)}function printLayerSummary(e,t,r){var n;try{n=JSON.stringify(e.outputShape)}catch(e){n="multiple"}printRow([e.name+" ("+e.getClassName()+")",n,e.countParams().toString()],t,r)}function printLayerSummaryWithConnections(e,t,r,n){var a;try{a=JSON.stringify(e.outputShape)}catch(e){a="multiple"}for(var o=[],i=0,s=e.inboundNodes;i0&&-1===r.indexOf(u)))for(var l=0;ln.maxNumTensors&&(n.maxNumTensors=x),x0,"Exepcted at least one fetch, got none");var r=[],n={};if(1===e.length){var a=getTopologicalSortAndRecipientCountsForOneFetch(e[0],t);r=a.sorted,n=a.recipientMap}else for(var o=new Set,i=0,s=e;i0;){var p=u[u.length-1];if(r.has(p.name))u.pop();else{var c=l[l.length-1]===u.length-1;if(0===p.inputs.length||c)u.pop(),n.push(p),r.add(p.name),c&&l.pop();else{l.push(u.length-1);for(var d=0,h=p.inputs;d0)throw new ValueError(d.length+" of "+a+" weights are not set: "+d)}batchSetValue(p)}var Container=function(e){function t(r){var n=e.call(this,{})||this;if(n.containerNodes=new Set,n.name=r.name,null==n.name){var a=n.getClassName().toLowerCase();n.name=getUid(a)}if(n.supportsMasking=!1,n.trainable=!0,n.updatable=!0,Array.isArray(r.inputs)?n.inputs=r.inputs.slice():n.inputs=[r.inputs],Array.isArray(r.outputs)?n.outputs=r.outputs.slice():n.outputs=[r.outputs],unique(n.inputs).length!==n.inputs.length)throw new ValueError("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+n.inputs.map(function(e){return e.name}));unique(n.outputs).length!==n.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+n.outputs.map(function(e){return e.name})),n.inputLayers=[],n.inputLayersNodeIndices=[],n.inputLayersTensorIndices=[],n.outputLayers=[],n.outputLayersNodeIndices=[],n.outputLayersTensorIndices=[],n.layers=[];for(var o=0,i=n.outputs;o1 nodes"),assert$1(0===l,"input layer has >1 tensors"),n.inputLayers.push(s),n.inputLayersNodeIndices.push(u),n.inputLayersTensorIndices.push(l);n.inputNames=[],n.outputNames=[],n.feedInputShapes=[],n.feedInputNames=[],n.feedOutputNames=[];for(var d=0;d=0;)a.splice(a.indexOf(u),1);b.push(u)}},N=[],S=[],T=0,E=n.outputs;Tn?1:0});for(var U=0,W=$;U0)throw new ValueError("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var e=[],t=0,r=this.layers;t1)for(var s=0,u=i;s0){for(var h=[],f=0;f0&&e.apply(singletonOrArray(o),n)}function i(e){var n=e.name,o=deserialize(e,null!=t.customObjects?t.customObjects:{});r[n]=o;for(var i=0,s=e.inboundNodes;i1)throw new NotImplementedError("Support for training a model with multiple output tensors with a dataset object is not implemented yet.");util.assert(Array.isArray(t)&&2===t.length,"Dataset iterator for fitDataset() is expected to generate an Array of length 2: `[xs, ys]`, but instead generates "+t);var r=(t=t)[1],n=t[0];if(n instanceof Tensor)return util.assert(1===e.inputs.length,"Model has multiple "+e.inputs.length+" inputs, hence it expects the input dataset to generate a dictionary of tensors (with keys "+JSON.stringify(e.inputNames)+", but received a single tensor."),util.assert(n.shape[0]===r.shape[0],"Mismatch in batch size between x and y tensors ("+n.shape[0]+" vs. "+r.shape[0]+")"),[n,r];var a=void 0;n=n;for(var o=[],i=0,s=e.inputNames;i0&&Number.isInteger(r.epochs),"For fitDataset(), config.epochs is expected to be a positive integer, but got "+r.epochs),util.assert(!n||r.batchesPerEpoch>0&&Number.isInteger(r.batchesPerEpoch),"For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got "+r.batchesPerEpoch),util.assert(null==r.validationSplit,"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0,A.label=1;case 1:return A.trys.push([1,,21,22]),a=null!=r.validationData,o=void 0,i=void 0,a&&(isDatasetObject(r.validationData)?util.assert(null==r.validationBatches||r.validationBatches>0&&Number.isInteger(r.validationBatches),"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got "+r.validationBatches):(s=standardizeTensorValidationData(r.validationData),o=s.xs,i=s.ys)),u=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),p=void 0,p=a?l.slice().concat(l.map(function(e){return"val_"+e})):l.slice(),c=standardizeCallbacks(r.callbacks),d=configureCallbacks(c,r.yieldEvery,r.verbose,r.epochs,null,null,r.batchesPerEpoch,null,a,p),h=d.callbackList,f=d.history,h.setModel(e),e.history=f,[4,h.onTrainBegin()];case 2:return A.sent(),e.stopTraining_=!1,m=null==r.initialEpoch?0:r.initialEpoch,g={},[4,t.iterator()];case 3:y=A.sent(),A.label=4;case 4:return m=r.batchesPerEpoch:b.done)?a?(I=void 0,isDatasetObject(r.validationData)?(_=toList,[4,e.evaluateDataset(r.validationData,{batches:r.validationBatches})]):[3,12]):[3,14]:[3,15];case 11:return I=_.apply(void 0,[A.sent()]),[3,13];case 12:I=toList(e.evaluate(o,i,{batchSize:null==r.validationBatchSize?DEFAULT_VALIDATION_BATCH_SIZE:r.validationBatchSize,verbose:0})),A.label=13;case 13:for(C=0;C0)throw new NotImplementedError("Verbose mode is not implemented yet.");return util.assert(!n||r.batches>0&&Number.isInteger(r.batches),"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(r.batches)),isLazyIteratorObject(t)?(s=t,[3,3]):[3,1];case 1:return[4,t.iterator()];case 2:s=h.sent(),h.label=3;case 3:i=s,u=0,l=0,p=function(){var t,s,p,c,d,h;return __generator$1(this,function(f){switch(f.label){case 0:return[4,i.next()];case 1:if((t=f.sent()).value){if(s=standardizeDataIteratorOutput(e,t.value),p=tidy(function(){return a(s)}),dispose(s),0===l)for(h=0;h0&&dispose(r)},h=0;h0&&Number.isInteger(e),"batchSize is required to be a positive integer, but got "+e)}function sliceArrays(e,t,r){return null==e?[null]:Array.isArray(e)?e.map(function(e){return sliceAlongFirstAxis(e,t,r-t)}):sliceAlongFirstAxis(e,t,r-t)}function sliceArraysByIndices(e,t){return tidy(function(){return null==e?null:Array.isArray(e)?e.map(function(e){return sliceArraysByIndices(e,t)}):gather$1(e,"int32"===t.dtype?t:t.toInt())})}function makeBatches(e,t){for(var r=[],n=0,a=null;n=e&&(a=e),r.push([n,a]),n=a;return r}function fitLoop(e,t,r,n,a,o,i,s,u,l,p,c,d,h,f,m){return __awaiter$1(this,void 0,void 0,function(){var g,y,v,x,b,w,N,S;return __generator$1(this,function(T){switch(T.label){case 0:if(null==a&&(a=32),null==o&&(o=1),null==p&&(p=!0),null==d&&(d=0),g=!1,null!=u&&null!=l&&(g=!0),null!=f&&(g=!0,null==h))throw new ValueError("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(y=e.checkNumSamples(r,a,h,"steps_per_epoch"))&&(v=range$1(0,y)),null==i&&(i=1),x=configureCallbacks(s,m,i,o,d,y,h,a,g,c),b=x.callbackList,w=x.history,b.setModel(e),e.history=w,[4,b.onTrainBegin()];case 1:T.sent(),e.stopTraining_=!1,N=function(o){var i,s,c,d,f;return __generator$1(this,function(m){switch(m.label){case 0:return[4,b.onEpochBegin(o)];case 1:if(m.sent(),i={},null==h)return[3,2];throw new NotImplementedError("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===p)throw new NotImplementedError("batch shuffling is not implemneted yet");p&&util.shuffle(v),s=tensor1d(v),c=makeBatches(y,a),d=function(o){var p;return __generator$1(this,function(d){switch(d.label){case 0:return p={},[4,b.onBatchBegin(o,p)];case 1:return d.sent(),tidy(function(){var d=c[o][0],h=c[o][1],f=sliceAlongFirstAxis(s,d,h-d);p.batch=o,p.size=h-d;for(var m=sliceArraysByIndices(r,f),y=t(m),v=0;v0){if(d=!0,2!==n.validationData.length)throw 3===n.validationData.length?new NotImplementedError("validationData including sample weights is not supported yet."):new ValueError("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+n.validationData+" is invalid.");i=n.validationData[0],s=n.validationData[1],f=e.standardizeUserData(i,s,!0,p),u=f[0],l=f[1],h=u.concat(l)}else null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1?(d=!0,m=Math.floor(a[0].shape[0]*(1-n.validationSplit)),g=a[0].shape[0],u=sliceArrays(a,m,g),a=sliceArrays(a,0,m),l=sliceArrays(o,m,g),o=sliceArrays(o,0,m),h=u.concat(l)):null!=n.validationSteps&&(d=!0);return y=a.concat(o),e.checkTrainableWeightsConsistency(),v=e.makeTrainFunction(),x=e.getDedupedMetricsNames(),b=void 0,w=void 0,d?(e.makeTestFunction(),b=e.testFunction,w=x.slice().concat(x.map(function(e){return"val_"+e}))):(b=null,h=[],w=x.slice()),N=standardizeCallbacks(n.callbacks),[4,fitLoop(e,v,y,x,p,n.epochs,n.verbose,N,b,h,n.shuffle,w,n.initialEpoch,null,null,n.yieldEvery)];case 2:return[2,S.sent()];case 3:return e.isTraining=!1,disposeNewTensors(a,t),disposeNewTensors(o,r),disposeNewTensors(u,i),disposeNewTensors(l,s),[7];case 4:return[2]}})})}function ensureTensorsRank2OrHigher(e){var t=[];e instanceof Tensor&&(e=[e]);for(var r=0;r0)o=!0;else if(isDataDict(e)){for(var i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new ValueError("Error when checking model "+a+" expected no data, but got "+e)}return[]}if(null==e)return t.map(function(e){return null});var s;if(isDataDict(e)){e=e,s=[];for(var u=0,l=t;u1)throw new ValueError("The model "+a+" expects "+t.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+e.shape);s=[e]}if(s=ensureTensorsRank2OrHigher(s),null!=r)for(var c=0;c=0&&f!==m)throw new ValueError("Error when checking "+a+": expected "+t[c]+" to have shape ["+r[c]+"], but got array with shape ["+d.shape+"].")}}return s}function checkArrayLengths(e,t,r){var n=unique(e.map(function(e){return e.shape[0]}));n.sort();var a=unique(t.map(function(e){return e.shape[0]}));if(a.sort(),n.length>1)throw new ValueError("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(e){return e.shape})));if(a.length>1)throw new ValueError("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(e){return e.shape})));if(n.length>0&&a.length>0&&!util.arraysEqual(n,a))throw new ValueError("Input Tensors should have the same number of samples as target Tensors. Found "+n[0]+" input sample(s) and "+a[0]+" target sample(s).")}function checkLossAndTargetCompatibility(e,t,r){for(var n=[meanSquaredError$1,binaryCrossentropy,categoricalCrossentropy],a=0;a1)throw new ValueError("The model expects "+t.length+" "+a+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(e.shape)+".");o=[e]}if(null!=r)for(var i=0;i1&&(t.metricsTensors.push([r,e]),t.metricsNames.push(t.outputNames[e]+"_loss"))}});var c=collectMetrics(e.metrics,this.outputNames);nameScope("metric",function(){for(var e=function(e){if(-1!==p.indexOf(e))return"continue";!function(r){for(var n,a,o,i=function(r){if(-1!==["accuracy","acc","crossentropy","ce"].indexOf(r)){var i=t.internalOutputShapes[e];1===i[i.length-1]||t.lossFunctions[e]===binaryCrossentropy?-1!==["accuracy","acc"].indexOf(r)?a=binaryAccuracy:-1!==["crossentropy","ce"].indexOf(r)&&(a=binaryCrossentropy$1):t.lossFunctions[e]===sparseCategoricalCrossentropy?-1!==["accuracy","acc"].indexOf(r)?a=sparseCategoricalAccuracy:-1!==["crossentropy","ce"].indexOf(r)&&(a=sparseCategoricalCrossentropy$1):-1!==["accuracy","acc"].indexOf(r)?a=categoricalAccuracy:-1!==["crossentropy","ce"].indexOf(r)&&(a=categoricalCrossentropy$1);var s=void 0;-1!==["accuracy","acc"].indexOf(r)?s="acc":-1!==["crossentropy","ce"].indexOf(r)&&(s="ce"),o=a,n=""+s}else{var u=get$1(r);o=u,n=""+r}var l;nameScope(n,function(){l=o}),function(e,r,n){t.outputNames.length>1&&(r=t.outputNames[e]+"_"+r),t.metricsNames.push(r),t.metricsTensors.push([n,e])}(e,n,l)},s=0,u=c[e];s0){var p=[];throw t.forEach(function(t,r){null==t&&p.push(e[r])}),new ValueError("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(p))}return t},t.prototype.predictLoop=function(e,t,r){var n=this;return void 0===t&&(t=32),void 0===r&&(r=!1),tidy(function(){var a=n.checkNumSamples(e);if(r)throw new NotImplementedError("Verbose predictLoop() is not implemented yet.");for(var o=makeBatches(a,t),i=[],s=function(t){var r=tidy(function(){var r=o[t][0],a=o[t][1],i=sliceArrays(e,r,a),s=[];if(Array.isArray(i))for(var u=0;u0&&e[0].shape[0]%n!=0)throw new ValueError("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+n+". Found: "+e[0].shape[0]+" sample(s).");return[e,t,null]},t.prototype.testLoop=function(e,t,r,n,a){var o=this;return void 0===n&&(n=0),tidy(function(){var i=o.checkNumSamples(t,r,a,"steps"),s=[];if(n>0)throw new NotImplementedError("Verbose mode is not implemented yet.");if(null!=a)throw new NotImplementedError("steps mode in testLoop() is not implemented yet");for(var u=makeBatches(i,r),l=tensor1d(range$1(0,i)),p=0;p1&&(a+="_"+count(e.slice(0,r),n)),t.push(a)}return t},t.prototype.makeTrainFunction=function(){var e=this;return function(t){var r=t.slice(0,e.inputs.length),n=t.slice(e.inputs.length,e.inputs.length+e.outputs.length),a=[],o=e.collectedTrainableWeights.map(function(e){return e.read()});return[e.optimizer.minimize(function(){for(var t=[],o=0;o1)throw new ValueError("Found more than one ("+r.length+") save handlers for URL '"+e+"'");e=r[0]}if(null==e.save)throw new ValueError("Model.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,io.encodeWeights(this.getNamedWeights(t))];case 1:return n=s.sent(),a=!1,o=null,i=this.toJSON(o,a),[2,e.save({modelTopology:i,weightData:n.data,weightSpecs:n.specs})]}})})},t.className="Model",t}(Container);function modelFromJSON(e,t){return __awaiter$1(this,void 0,void 0,function(){var r,n,a,o,i,s,u,l,p,c;return __generator$1(this,function(d){switch(d.label){case 0:return"modelTopology"in e||(e={modelTopology:e}),null!=(r=(e=e).modelTopology).model_config&&(r=r.model_config),n=convertPythonicToTs(r),a=deserialize(n,t),null==e.weightsManifest?[3,2]:[4,io.loadWeights(e.weightsManifest,e.pathPrefix,a.weights.map(function(e){return e.originalName}))];case 1:for(o=d.sent(),i={},s=0,u=a.weights;s1)throw new ValueError("Found more than one ("+r.length+") load handlers for URL '"+e+"'");e=r[0]}return[2,loadModelFromIOHandler(e,void 0,t)]})})}function loadModelFromIOHandler(e,t,r){return void 0===r&&(r=!0),__awaiter$1(this,void 0,void 0,function(){var n,a,o,i,s;return __generator$1(this,function(u){switch(u.label){case 0:if(null==e.load)throw new ValueError("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,e.load()];case 1:if(n=u.sent(),null!=(a=n.modelTopology).model_config&&(a=a.model_config),o=deserialize(convertPythonicToTs(a),t),null!=n.weightData){if(null==n.weightSpecs)throw new ValueError("Model artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");i=!1,s=!0,o.loadWeights(io.decodeWeights(n.weightData,n.weightSpecs),i,s,r)}return[2,o]}})})}serialization.registerClass(Model);var Sequential=function(e){function t(t){var r=e.call(this,{inputs:[],outputs:[]})||this;if(t=t||{},r.trainable=!0,r._updatable=!0,r.built=!1,r.name=null!=t.name?t.name:getUid("sequential_"),null!=t.layers)for(var n=0,a=t.layers;n 0 but got "+JSON.stringify(e.filters))},t}(BaseConv),Conv2D=function(e){function t(r){var n=e.call(this,2,r)||this;return t.verifyConfig(r),n}return __extends$1(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t},t.verifyConfig=function(e){if("number"!=typeof e.kernelSize&&!checkArrayTypeAndLength(e.kernelSize,"number",1,2))throw new ValueError("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv2D",t}(Conv);serialization.registerClass(Conv2D);var Conv2DTranspose=function(e){function t(t){var r=e.call(this,t)||this;if(r.inputSpec=[new InputSpec({ndim:4})],"same"!==r.padding&&"valid"!==r.padding)throw new ValueError("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+r.padding);return r}return __extends$1(t,e),t.prototype.build=function(e){if(4!==(e=getExactlyOneShape(e)).length)throw new ValueError("Input should have rank 4; Received input shape: "+JSON.stringify(e));var t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new ValueError("The channel dimension of the inputs should be defined. Found `None`.");var r,n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new InputSpec({ndim:4,axes:(r={},r[t]=n,r)})],this.built=!0},t.prototype.call=function(e,t){var r=this;return tidy(function(){var t=getExactlyOneTensor(e);if(4!==t.shape.length)throw new ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+t.shape.length);var n,a,o=t.shape,i=o[0];"channelsFirst"===r.dataFormat?(n=2,a=3):(n=1,a=2);var s=o[n],u=o[a],l=r.kernelSize[0],p=r.kernelSize[1],c=r.strides[0],d=r.strides[1],h=[i,deconvLength(s,c,l,r.padding),deconvLength(u,d,p,r.padding),r.filters];"channelsLast"!==r.dataFormat&&(t=transpose(t,[0,2,3,1]));var f=conv2dTranspose(t,r.kernel.read(),h,r.strides,r.padding);return"channelsLast"!==r.dataFormat&&(f=transpose(f,[0,3,1,2])),null!=r.bias&&(f=biasAdd(f,r.bias.read(),r.dataFormat)),null!=r.activation&&(f=r.activation.apply(f)),f})},t.prototype.computeOutputShape=function(e){var t,r,n,a=(e=getExactlyOneShape(e)).slice();"channelsFirst"===this.dataFormat?(t=1,r=2,n=3):(t=3,r=1,n=2);var o=this.kernelSize[0],i=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return a[t]=this.filters,a[r]=deconvLength(a[r],s,o,this.padding),a[n]=deconvLength(a[n],u,i,this.padding),a},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.dilationRate,t},t.className="Conv2DTranspose",t}(Conv2D);serialization.registerClass(Conv2DTranspose);var SeparableConv=function(e){function t(t,r){var n=e.call(this,t,r)||this;if(n.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",n.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",n.depthwiseKernel=null,n.pointwiseKernel=null,null==r.filters)throw new ValueError("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=r.kernelInitializer||null!=r.kernelRegularizer||null!=r.kernelConstraint)throw new ValueError("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=r.padding&&"same"!==r.padding&&"valid"!==r.padding)throw new ValueError("SeparableConv"+n.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(r.padding));return n.depthMultiplier=null==r.depthMultiplier?1:r.depthMultiplier,n.depthwiseInitializer=getInitializer(r.depthwiseInitializer||n.DEFAULT_DEPTHWISE_INITIALIZER),n.depthwiseRegularizer=getRegularizer(r.depthwiseRegularizer),n.depthwiseConstraint=getConstraint(r.depthwiseConstraint),n.pointwiseInitializer=getInitializer(r.depthwiseInitializer||n.DEFAULT_POINTWISE_INITIALIZER),n.pointwiseRegularizer=getRegularizer(r.pointwiseRegularizer),n.pointwiseConstraint=getConstraint(r.pointwiseConstraint),n}return __extends$1(t,e),t.prototype.build=function(e){if((e=getExactlyOneShape(e)).length1)throw new ValueError("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(e)+".");for(var a=null==e[0]?null:e[0].slice(1),o=1;o1){var y=range$1(1,s).concat([0]);t.push(transpose(d,y)),l=!0}else t.push(d)}var v=r.mergeFunction(t),x=v.rank;if(l)if(null==x){var b=v.shape;m=[f=b[b.length-1]].concat(b.slice(0,b.length-1)),v=transpose(v.reshape([-1,f]),[1,0]).reshape(m)}else x>1&&(y=[x-1].concat(range$1(0,x-1)),v=transpose(v,y));return v}return r.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){var t;t=null==(e=e)[0]?null:e[0].slice(1);for(var r=1;r1)throw new ValueError("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}},t.prototype.mergeFunction=function(e){var t=this;return tidy(function(){return concatenate(e,t.axis)})},t.prototype.computeOutputShape=function(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new ValueError("A `Concatenate` layer should be called on a list of inputs.");for(var t=e,r=t[0].slice(),n=this.axis<0?r.length+this.axis:this.axis,a=0,o=t.slice(1);a3||t.shape.length>3)throw new NotImplementedError("batchDot is not implemented for tensors of 4D or higher rank yet");if(util.assert(e.shape.length>=2,"batchDot requires the rank of x to be >= 2, but got "+e.shape.length),util.assert(e.shape.length>=2,"batchDot requires the rank of y to be >= 2, but got "+t.shape.length),"number"==typeof r&&(r=[r,r]),"complex64"===e.dtype||"complex64"===t.dtype)throw new NotImplementedError("batchDot is not implemented for complex64-type Tensors yet.");var n=e.shape.length,a=t.shape.length;null==r&&(r=[n-1,a-2]);var o=r;return tidy(function(){var r,i;if(n>a){r=n-a;for(var s=[],u=0;un){for(r=a-n,s=[],u=0;u0){var c,d=[];for(u=c=n>a?n+a-3:n-1;u3||r.length>3)throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");var n=this.interpretAxes(t,r);if(t[n[0]]!==r[n[1]])throw new ValueError("Dimension incompatibility: "+t[n[0]]+" !== "+r[n[1]])},t.prototype.mergeFunction=function(e){if(2!==e.length)throw new ValueError("A `Dot` layer must be called on exactly 2 inputs, but received "+e.length+" input(s).");var t,r=e[0],n=e[1];return t=Array.isArray(this.axes)?this.axes.map(function(t,r){return interpretAxis(t,e[r].shape.length)}):[interpretAxis(this.axes,r.shape.length),interpretAxis(this.axes,n.shape.length)],this.normalize&&(r=l2Normalize(r,t[0]),n=l2Normalize(n,t[1])),batchDot(r,n,t)},t.prototype.interpretAxes=function(e,t){return Array.isArray(this.axes)?this.axes:[interpretAxis(this.axes,e.length),interpretAxis(this.axes,t.length)]},t.prototype.computeOutputShape=function(e){util.assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),"A `Dot` layer should be called on a list of exactly 2 inputs.");var t=e[0].slice(),r=e[1].slice();if(t.length>3||r.length>3)throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");var n=this.interpretAxes(t,r);t.splice(n[0],1),r.splice(n[1],1),r.splice(0,1);var a=t.concat(r);return 1===a.length&&a.push(1),a},t.prototype.computeMask=function(e,t){throw new NotImplementedError("computeMask has not been implemented for Dot yet")},t.prototype.getConfig=function(){var t={axes:this.axes,normalize:this.normalize},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="Dot",t}(Merge);function batchNormalization$1(e,t,r,n,a,o){var i;if(void 0===o&&(o=.001),2===e.rank)i=batchNormalization2d(e,t,r,o,a,n);else if(3===e.rank)i=batchNormalization3d(e,t,r,o,a,n);else{if(4!==e.rank)throw new NotImplementedError("batchNormalization is not implemented for array of rank "+e.rank+" yet");i=batchNormalization4d(e,t,r,o,a,n)}return i}function regularNormalizeBatchInTraining(e,t,r,n,a){return void 0===a&&(a=.001),tidy(function(){var o=moments(e,n),i=o.mean,s=o.variance;return[batchNormalization$1(e,i,s,r,t,a),i,s]})}function broadcastNormalizeBatchInTraining(e,t,r,n,a){return void 0===a&&(a=.001),tidy(function(){for(var o=moments(e,n),i=o.mean,s=o.variance,u=[],l=0,p=range$1(0,e.rank);l=0?this.axis:this.axis+e.length,r=e[t];if(null==r)throw new ValueError("Axis "+t+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(e)+".");this.inputSpec=[new InputSpec({ndim:e.length,axes:(n={},n[t]=r,n)})];var n,a=[r];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0},t.prototype.call=function(e,t){var r=this;return tidy(function(){var n=null!=t.training&&t.training,a=getExactlyOneTensor(e),o=a.shape,i=o.length,s=range$1(0,i),u=r.axis>=0?r.axis:r.axis+i;s.splice(u,1);var l=pyListRepeat(1,i);l[u]=o[u];var p=s.slice();p.sort();var c=!util.arraysEqual(p,range$1(0,i).slice(0,i-1));if(!n)return function(){if(c){var e=r.movingMean.read().reshape(l),t=r.movingVariance.read().reshape(l),n=r.center?r.beta.read().reshape(l):null,o=r.scale?r.gamma.read().reshape(l):null;return batchNormalization$1(a,e,t,n,o,r.epsilon)}return batchNormalization$1(a,r.movingMean.read(),r.movingVariance.read(),null==r.beta?null:r.beta.read(),null==r.gamma?null:r.gamma.read(),r.epsilon)}();var d=normalizeBatchInTraining(a,r.gamma.read(),r.beta.read(),s,r.epsilon),h=d[0],f=d[1],m=d[2],g=function(e,t,r){tidy(function(){var n=getScalar(1).sub(getScalar(r)),a=e.read(),o=a.sub(t).mul(n);e.write(a.sub(o))})};return g(r.movingMean,f,r.momentum),g(r.movingVariance,m,r.momentum),h})},t.prototype.getConfig=function(){var t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:serializeInitializer(this.betaInitializer),gammaInitializer:serializeInitializer(this.gammaInitializer),movingMeanInitializer:serializeInitializer(this.movingMeanInitializer),movingVarianceInitializer:serializeInitializer(this.movingVarianceInitializer),betaRegularizer:serializeRegularizer(this.betaRegularizer),gammaRegularizer:serializeRegularizer(this.gammaRegularizer),betaConstraint:serializeConstraint(this.betaConstraint),gammaConstraint:serializeConstraint(this.gammaConstraint)},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="BatchNormalization",t}(Layer);function spatial2dPadding(e,t,r){return tidy(function(){if(4!==e.rank)throw new ValueError("temporalPadding expects input tensor to be 4-D, but received a "+e.rank+"-D tensor.");if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new ValueError("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==r&&(r=imageDataFormat()),"channelsLast"!==r&&"channelsFirst"!==r)throw new ValueError("Unknown data format: "+r+". Supported data formats are 'channelsLast' and 'channelsFirst.");var n;return n="channelsFirst"===r?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],pad(e,n)})}serialization.registerClass(BatchNormalization);var ZeroPadding2D=function(e){function t(t){var r=this;if(null==t&&(t={}),(r=e.call(this,t)||this).dataFormat=null==t.dataFormat?imageDataFormat():t.dataFormat,null==t.padding)r.padding=[[1,1],[1,1]];else if("number"==typeof t.padding)r.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,2!==t.padding.length)throw new ValueError("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+t.padding.length+" array.");var n=void 0,a=void 0;if("number"==typeof t.padding[0])n=[t.padding[0],t.padding[0]],a=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,2!==t.padding[0].length)throw new ValueError("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+t.padding[0].length+" array.");if(n=t.padding[0],2!==t.padding[1].length)throw new ValueError("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+t.padding[1].length+" array.");a=t.padding[1]}r.padding=[n,a]}return r.inputSpec=[new InputSpec({ndim:4})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){var t,r;return e=getExactlyOneShape(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,r=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,r]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,r=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,r,e[3]])},t.prototype.call=function(e,t){var r=this;return tidy(function(){return spatial2dPadding(getExactlyOneTensor(e),r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var t={padding:this.padding,dataFormat:this.dataFormat},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.className="ZeroPadding2D",t}(Layer);function pool2d(e,t,r,n,a,o){return tidy(function(){var i;checkDataFormat(a),checkPoolMode(o),checkPaddingMode(n),null==r&&(r=[1,1]),null==n&&(n="valid"),null==a&&(a=imageDataFormat()),null==o&&(o="max"),e=preprocessConv2DInput(e,a);var s="same"===n?"same":"valid";return i="max"===o?maxPool(e,t,r,s):avgPool(e,t,r,s),"channelsFirst"===a&&(i=transpose(i,[0,3,1,2])),i})}serialization.registerClass(ZeroPadding2D);var Pooling1D=function(e){function t(t){var r=this;if(null==t.poolSize&&(t.poolSize=2),r=e.call(this,t)||this,"number"==typeof t.poolSize)r.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new ValueError("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.poolSize));r.poolSize=t.poolSize}if(null==t.strides)r.strides=r.poolSize;else if("number"==typeof t.strides)r.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new ValueError("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.strides));r.strides=t.strides}return r.padding=null==t.padding?"valid":t.padding,checkPaddingMode(r.padding),r.inputSpec=[new InputSpec({ndim:3})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){var t=convOutputLength((e=getExactlyOneShape(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]},t.prototype.call=function(e,t){var r=this;return tidy(function(){r.invokeCallHook(e,t),e=expandDims$1(getExactlyOneTensor(e),2);var n=r.poolingFunction(getExactlyOneTensor(e),[r.poolSize[0],1],[r.strides[0],1],r.padding,"channelsLast");return squeeze(n,[2])})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t}(Layer),MaxPooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.poolingFunction=function(e,t,r,n,a){return checkDataFormat(a),checkPaddingMode(n),pool2d(e,t,r,n,a,"max")},t.className="MaxPooling1D",t}(Pooling1D);serialization.registerClass(MaxPooling1D);var AveragePooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.poolingFunction=function(e,t,r,n,a){return checkDataFormat(a),checkPaddingMode(n),pool2d(e,t,r,n,a,"avg")},t.className="AveragePooling1D",t}(Pooling1D);serialization.registerClass(AveragePooling1D);var Pooling2D=function(e){function t(t){var r=this;if(null==t.poolSize&&(t.poolSize=[2,2]),(r=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)r.strides=r.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new ValueError("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+t.strides.length+".");r.strides=t.strides}else r.strides=[t.strides,t.strides];return r.padding=null==t.padding?"valid":t.padding,r.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,checkDataFormat(r.dataFormat),checkPaddingMode(r.padding),r.inputSpec=[new InputSpec({ndim:4})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){e=getExactlyOneShape(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],r="channelsFirst"===this.dataFormat?e[3]:e[2];return t=convOutputLength(t,this.poolSize[0],this.padding,this.strides[0]),r=convOutputLength(r,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,r]:[e[0],t,r,e[3]]},t.prototype.call=function(e,t){var r=this;return tidy(function(){return r.invokeCallHook(e,t),r.poolingFunction(getExactlyOneTensor(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t}(Layer),MaxPooling2D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.poolingFunction=function(e,t,r,n,a){return checkDataFormat(a),checkPaddingMode(n),pool2d(e,t,r,n,a,"max")},t.className="MaxPooling2D",t}(Pooling2D);serialization.registerClass(MaxPooling2D);var AveragePooling2D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.poolingFunction=function(e,t,r,n,a){return checkDataFormat(a),checkPaddingMode(n),pool2d(e,t,r,n,a,"avg")},t.className="AveragePooling2D",t}(Pooling2D);serialization.registerClass(AveragePooling2D);var GlobalPooling1D=function(e){function t(t){var r=e.call(this,t)||this;return r.inputSpec=[new InputSpec({ndim:3})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){return[e[0],e[2]]},t.prototype.call=function(e,t){throw new NotImplementedError},t}(Layer),GlobalAveragePooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.call=function(e,t){return tidy(function(){var t=getExactlyOneTensor(e);return mean(t,1)})},t.className="GlobalAveragePooling1D",t}(GlobalPooling1D);serialization.registerClass(GlobalAveragePooling1D);var GlobalMaxPooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends$1(t,e),t.prototype.call=function(e,t){return tidy(function(){var t=getExactlyOneTensor(e);return max(t,1)})},t.className="GlobalMaxPooling1D",t}(GlobalPooling1D);serialization.registerClass(GlobalMaxPooling1D);var GlobalPooling2D=function(e){function t(t){var r=e.call(this,t)||this;return r.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,checkDataFormat(r.dataFormat),r.inputSpec=[new InputSpec({ndim:4})],r}return __extends$1(t,e),t.prototype.computeOutputShape=function(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,t){throw new NotImplementedError},t.prototype.getConfig=function(){var t={dataFormat:this.dataFormat},r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t}(Layer),GlobalAveragePooling2D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.call=function(e,t){var r=this;return tidy(function(){var t=getExactlyOneTensor(e);return"channelsLast"===r.dataFormat?mean(t,[1,2]):mean(t,[2,3])})},t.className="GlobalAveragePooling2D",t}(GlobalPooling2D);serialization.registerClass(GlobalAveragePooling2D);var GlobalMaxPooling2D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t.prototype.call=function(e,t){var r=this;return tidy(function(){var t=getExactlyOneTensor(e);return"channelsLast"===r.dataFormat?max(t,[1,2]):max(t,[2,3])})},t.className="GlobalMaxPooling2D",t}(GlobalPooling2D);function standardizeArgs(e,t,r,n){if(Array.isArray(e)){if(null!=t||null!=r)throw new ValueError("When inputs is an array, neither initialState or constants should be provided");null!=n&&(r=e.slice(e.length-n,e.length),e=e.slice(0,e.length-n)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:r=a(r)}}function rnn(e,t,r,n,a,o,i,s){void 0===n&&(n=!1),void 0===i&&(i=!1),void 0===s&&(s=!1);var u=t.shape.length;if(u<3)throw new ValueError("Input should be at least 3D, but is "+u+"D.");var l,p,c=[1,0].concat(range$1(2,u));if(t=transpose(t,c),null!=a)throw new NotImplementedError("The rnn() function of the deeplearn.js backend does not support masking yet.");if(null!=o)throw new NotImplementedError("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),n&&(t=reverse(t,0));for(var d=r,h=t.shape[0],f=function(r){var n=sliceAlongFirstAxis(t,r,1);n=n.reshape(n.shape.slice(1));var a=tidy(function(){return e(n,d)});if(p=a[0],s)if(0===r)l=p.expandDims(1);else{var o=concat([l,p.expandDims(1)],1);l.dispose(),l=o}d=a[1]},m=0;m1?tile$1(r,[1,e]):r}):t.cell.stateSize>1?[tile$1(r,[1,t.cell.stateSize])]:[r]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);var r=this.cell.getConfig();t.cell={className:this.cell.getClassName(),config:r};var n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="RNN",t}(Layer);serialization.registerClass(RNN);var RNNCell=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$1(t,e),t}(Layer),SimpleRNNCell=function(e){function t(t){var r=e.call(this,t)||this;return r.DEFAULT_ACTIVATION="tanh",r.DEFAULT_KERNEL_INITIALIZER="glorotNormal",r.DEFAULT_RECURRENT_INITIALIZER="orthogonal",r.DEFAULT_BIAS_INITIALIZER="zeros",r.units=t.units,r.activation=getActivation(null==t.activation?r.DEFAULT_ACTIVATION:t.activation),r.useBias=null==t.useBias||t.useBias,r.kernelInitializer=getInitializer(t.kernelInitializer||r.DEFAULT_KERNEL_INITIALIZER),r.recurrentInitializer=getInitializer(t.recurrentInitializer||r.DEFAULT_RECURRENT_INITIALIZER),r.biasInitializer=getInitializer(t.biasInitializer||r.DEFAULT_BIAS_INITIALIZER),r.kernelRegularizer=getRegularizer(t.kernelRegularizer),r.recurrentRegularizer=getRegularizer(t.recurrentRegularizer),r.biasRegularizer=getRegularizer(t.biasRegularizer),r.kernelConstraint=getConstraint(t.kernelConstraint),r.recurrentConstraint=getConstraint(t.recurrentConstraint),r.biasConstraint=getConstraint(t.biasConstraint),r.dropout=min$1([1,max$1([0,null==t.dropout?0:t.dropout])]),r.recurrentDropout=min$1([1,max$1([0,null==t.recurrentDropout?0:t.recurrentDropout])]),r.stateSize=r.units,r.dropoutMask=null,r.recurrentDropoutMask=null,r}return __extends$1(t,e),t.prototype.build=function(e){e=getExactlyOneShape(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,t){var r=this;return tidy(function(){if(2!==(e=e).length)throw new ValueError("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var n=e[1];e=e[0];var a,o=null!=t.training&&t.training;01){for(var o=[],i=0;i= 3D, but received input shape "+JSON.stringify(t));this.inputSpec=[{shape:t}];var r=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(r),this.layer.built=!0),e.prototype.build.call(this,t)},t.prototype.computeOutputShape=function(e){var t=[(e=getExactlyOneShape(e))[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(t),n=e[1];return[r[0],n].concat(r.slice(1))},t.prototype.call=function(e,t){var r=this;return tidy(function(){return rnn(function(e,n){return[getExactlyOneTensor(r.layer.call(e,t)),[]]},e=getExactlyOneTensor(e),[],!1,null,null,!1,!0)[1]})},t.className="TimeDistributed",t}(Wrapper);serialization.registerClass(TimeDistributed);var VALID_BIDIRECTIONAL_MERGE_MODES=["sum","mul","concat","ave"];function checkBidirectionalMergeMode(e){checkStringTypeUnionValue(VALID_BIDIRECTIONAL_MERGE_MODES,"BidirectionalMergeMode",e)}var Bidirectional=function(e){function t(t){var r=e.call(this,t)||this,n=t.layer.getConfig();if(r.forwardLayer=deserialize({className:t.layer.getClassName(),config:n}),n.goBackwards=!0!==n.goBackwards,r.backwardLayer=deserialize({className:t.layer.getClassName(),config:n}),r.forwardLayer.name="forward_"+r.forwardLayer.name,r.backwardLayer.name="backward_"+r.backwardLayer.name,checkBidirectionalMergeMode(t.mergeMode),r.mergeMode=t.mergeMode,t.weights)throw new NotImplementedError("weights support is not implemented for Bidirectional layer yet.");return r._stateful=t.layer.stateful,r.returnSequences=t.layer.returnSequences,r.returnState=t.layer.returnState,r.supportsMasking=!0,r._trainable=!0,r.inputSpec=t.layer.inputSpec,r.numConstants=null,r}return __extends$1(t,e),Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var t=e.length,r=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))},t.prototype.computeOutputShape=function(e){var t,r,n,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),a=a,this.returnState?(n=a.slice(1),t=a[0]):t=a[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,r=[t]):r=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?r.concat(n).concat(n.slice()):[t].concat(n).concat(n.slice()):singletonOrArray(r)},t.prototype.apply=function(t,r){var n=null==r?null:r.initialState,a=null==r?null:r.constants;null==r&&(r={});var o=standardizeArgs(t,n,a,this.numConstants);if(t=o.inputs,n=o.initialState,a=o.constants,Array.isArray(t)&&(n=t.slice(1),t=t[0]),(null==n||0===n.length)&&null==a)return e.prototype.apply.call(this,t,r);var i=[],s=[];if(null!=n){var u=n.length;if(u%2>0)throw new ValueError("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");r.initialState=n,i.push.apply(i,n);var l=n.map(function(e){return new InputSpec({shape:e.shape})});this.forwardLayer.stateSpec=l.slice(0,u/2),this.backwardLayer.stateSpec=l.slice(u/2),s.push.apply(s,l)}if(null!=a)throw new NotImplementedError("Support for constants in Bidirectional layers is not implemented yet.");for(var p=i[0]instanceof SymbolicTensor,c=0,d=i;c0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),a=new Array(123),o=0;o<64;)a[n[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;r.encode=function(e,t,r){for(var a,o=null,i=[],s=0,u=0;t>2],a=(3&l)<<4,u=1;break;case 1:i[s++]=n[a|l>>4],a=(15&l)<<2,u=2;break;case 2:i[s++]=n[a|l>>6],i[s++]=n[63&l],u=0}s>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),s=0)}return u&&(i[s++]=n[a],i[s++]=61,1===u&&(i[s++]=61)),o?(s&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))},r.decode=function(e,t,r){for(var n,o=r,i=0,s=0;s1)break;if(void 0===(u=a[u]))throw Error("invalid encoding");switch(i){case 0:n=u,i=1;break;case 1:t[r++]=n<<2|(48&u)>>4,n=u,i=2;break;case 2:t[r++]=(15&n)<<4|(60&u)>>2,n=u,i=3;break;case 3:t[r++]=(3&n)<<6|u,i=0}}if(1===i)throw Error("invalid encoding");return r-o},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}),eventemitter=EventEmitter;function EventEmitter(){this._listeners={}}EventEmitter.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},EventEmitter.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>3.4028234663852886e38)e((a<<31|2139095040)>>>0,r,n);else if(t<1.1754943508222875e-38)e((a<<31|Math.round(t/1.401298464324817e-45))>>>0,r,n);else{var o=Math.floor(Math.log(t)/Math.LN2);e((a<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,r,n)}}function r(e,t,r){var n=e(t,r),a=2*(n>>31)+1,o=n>>>23&255,i=8388607&n;return 255===o?i?NaN:a*(1/0):0===o?1.401298464324817e-45*a*i:a*Math.pow(2,o-150)*(i+8388608)}e.writeFloatLE=t.bind(null,writeUintLE),e.writeFloatBE=t.bind(null,writeUintBE),e.readFloatLE=r.bind(null,readUintLE),e.readFloatBE=r.bind(null,readUintBE)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function a(e,n,a){t[0]=e,n[a]=r[0],n[a+1]=r[1],n[a+2]=r[2],n[a+3]=r[3],n[a+4]=r[4],n[a+5]=r[5],n[a+6]=r[6],n[a+7]=r[7]}function o(e,n,a){t[0]=e,n[a]=r[7],n[a+1]=r[6],n[a+2]=r[5],n[a+3]=r[4],n[a+4]=r[3],n[a+5]=r[2],n[a+6]=r[1],n[a+7]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function s(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?a:o,e.writeDoubleBE=n?o:a,e.readDoubleLE=n?i:s,e.readDoubleBE=n?s:i}():function(){function t(e,t,r,n,a,o){var i=n<0?1:0;if(i&&(n=-n),0===n)e(0,a,o+t),e(1/n>0?0:2147483648,a,o+r);else if(isNaN(n))e(0,a,o+t),e(2146959360,a,o+r);else if(n>1.7976931348623157e308)e(0,a,o+t),e((i<<31|2146435072)>>>0,a,o+r);else{var s;if(n<2.2250738585072014e-308)e((s=n/5e-324)>>>0,a,o+t),e((i<<31|s/4294967296)>>>0,a,o+r);else{var u=Math.floor(Math.log(n)/Math.LN2);1024===u&&(u=1023),e(4503599627370496*(s=n*Math.pow(2,-u))>>>0,a,o+t),e((i<<31|u+1023<<20|1048576*s&1048575)>>>0,a,o+r)}}}function r(e,t,r,n,a){var o=e(n,a+t),i=e(n,a+r),s=2*(i>>31)+1,u=i>>>20&2047,l=4294967296*(1048575&i)+o;return 2047===u?l?NaN:s*(1/0):0===u?5e-324*s*l:s*Math.pow(2,u-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,writeUintLE,0,4),e.writeDoubleBE=t.bind(null,writeUintBE,4,0),e.readDoubleLE=r.bind(null,readUintLE,0,4),e.readDoubleBE=r.bind(null,readUintBE,4,0)}(),e}function writeUintLE(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function writeUintBE(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function readUintLE(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function readUintBE(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}var inquire_1=inquire;function inquire(moduleName){try{var mod$$1=eval("quire".replace(/^/,"re"))(moduleName);if(mod$$1&&(mod$$1.length||Object.keys(mod$$1).length))return mod$$1}catch(e){}return null}var utf8_1=createCommonjsModule$1(function(e,t){var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?o[i++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[i++]=55296+(n>>10),o[i++]=56320+(1023&n)):o[i++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,o)),i=0);return a?(i&&a.push(String.fromCharCode.apply(String,o.slice(0,i))),a.join("")):String.fromCharCode.apply(String,o.slice(0,i))},r.write=function(e,t,r){for(var n,a,o=r,i=0;i>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(a=e.charCodeAt(i+1)))?(n=65536+((1023&n)<<10)+(1023&a),++i,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-o}}),pool_1=pool$1;function pool$1(e,t,r){var n=r||8192,a=n>>>1,o=null,i=n;return function(r){if(r<1||r>a)return e(r);i+r>n&&(o=e(n),i=0);var s=t.call(o,i,i+=r);return 7&i&&(i=1+(7|i)),s}}var longbits=LongBits;function LongBits(e,t){this.lo=e>>>0,this.hi=t>>>0}var zero=LongBits.zero=new LongBits(0,0);zero.toNumber=function(){return 0},zero.zzEncode=zero.zzDecode=function(){return this},zero.length=function(){return 1};var zeroHash=LongBits.zeroHash="\0\0\0\0\0\0\0\0";LongBits.fromNumber=function(e){if(0===e)return zero;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new LongBits(r,n)},LongBits.from=function(e){if("number"==typeof e)return LongBits.fromNumber(e);if(minimal.isString(e)){if(!minimal.Long)return LongBits.fromNumber(parseInt(e,10));e=minimal.Long.fromString(e)}return e.low||e.high?new LongBits(e.low>>>0,e.high>>>0):zero},LongBits.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},LongBits.prototype.toLong=function(e){return minimal.Long?new minimal.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var charCodeAt=String.prototype.charCodeAt;LongBits.fromHash=function(e){return e===zeroHash?zero:new LongBits((charCodeAt.call(e,0)|charCodeAt.call(e,1)<<8|charCodeAt.call(e,2)<<16|charCodeAt.call(e,3)<<24)>>>0,(charCodeAt.call(e,4)|charCodeAt.call(e,5)<<8|charCodeAt.call(e,6)<<16|charCodeAt.call(e,7)<<24)>>>0)},LongBits.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},LongBits.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},LongBits.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},LongBits.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10};var minimal=createCommonjsModule$1(function(e,t){var r=t;function n(e,t,r){for(var n=Object.keys(t),a=0;a0)},r.Buffer=function(){try{var e=r.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(e){return"number"==typeof e?r.Buffer?r._Buffer_allocUnsafe(e):new r.Array(e):r.Buffer?r._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=commonjsGlobal$1.dcodeIO&&commonjsGlobal$1.dcodeIO.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(e){return e?r.LongBits.from(e).toHash():r.LongBits.zeroHash},r.longFromHash=function(e,t){var n=r.LongBits.fromHash(e);return r.Long?r.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},r.merge=n,r.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},r.newError=a,r.ProtocolError=a("ProtocolError"),r.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},r.oneOfSetter=function(e){return function(t){for(var r=0;r127;)t[r++]=127&e|128,e>>>=7;t[r]=e}function VarintOp(e,t){this.len=e,this.next=void 0,this.val=t}function writeVarint64(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function writeFixed32(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}Writer.create=minimal.Buffer?function(){return(Writer.create=function(){return new BufferWriter})()}:function(){return new Writer},Writer.alloc=function(e){return new minimal.Array(e)},minimal.Array!==Array&&(Writer.alloc=minimal.pool(Writer.alloc,minimal.Array.prototype.subarray)),Writer.prototype._push=function(e,t,r){return this.tail=this.tail.next=new Op(e,t,r),this.len+=t,this},VarintOp.prototype=Object.create(Op.prototype),VarintOp.prototype.fn=writeVarint32,Writer.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new VarintOp((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},Writer.prototype.int32=function(e){return e<0?this._push(writeVarint64,10,LongBits$1.fromNumber(e)):this.uint32(e)},Writer.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},Writer.prototype.uint64=function(e){var t=LongBits$1.from(e);return this._push(writeVarint64,t.length(),t)},Writer.prototype.int64=Writer.prototype.uint64,Writer.prototype.sint64=function(e){var t=LongBits$1.from(e).zzEncode();return this._push(writeVarint64,t.length(),t)},Writer.prototype.bool=function(e){return this._push(writeByte,1,e?1:0)},Writer.prototype.fixed32=function(e){return this._push(writeFixed32,4,e>>>0)},Writer.prototype.sfixed32=Writer.prototype.fixed32,Writer.prototype.fixed64=function(e){var t=LongBits$1.from(e);return this._push(writeFixed32,4,t.lo)._push(writeFixed32,4,t.hi)},Writer.prototype.sfixed64=Writer.prototype.fixed64,Writer.prototype.float=function(e){return this._push(minimal.float.writeFloatLE,4,e)},Writer.prototype.double=function(e){return this._push(minimal.float.writeDoubleLE,8,e)};var writeBytes=minimal.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(writeByte,1,0);if(minimal.isString(e)){var r=Writer.alloc(t=base64.length(e));base64.decode(e,r,0),e=r}return this.uint32(t)._push(writeBytes,t,e)},Writer.prototype.string=function(e){var t=utf8.length(e);return t?this.uint32(t)._push(utf8.write,t,e):this._push(writeByte,1,0)},Writer.prototype.fork=function(){return this.states=new State(this),this.head=this.tail=new Op(noop,0,0),this.len=0,this},Writer.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op(noop,0,0),this.len=0),this},Writer.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},Writer.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},Writer._configure=function(e){BufferWriter=e};var writer_buffer=BufferWriter$1;(BufferWriter$1.prototype=Object.create(writer.prototype)).constructor=BufferWriter$1;var Buffer$1=minimal.Buffer;function BufferWriter$1(){writer.call(this)}BufferWriter$1.alloc=function(e){return(BufferWriter$1.alloc=minimal._Buffer_allocUnsafe)(e)};var writeBytesBuffer=Buffer$1&&Buffer$1.prototype instanceof Uint8Array&&"set"===Buffer$1.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(writeBytesBuffer,t,e),this},BufferWriter$1.prototype.string=function(e){var t=Buffer$1.byteLength(e);return this.uint32(t),t&&this._push(writeStringBuffer,t,e),this};var reader=Reader,BufferReader,LongBits$2=minimal.LongBits,utf8$1=minimal.utf8;function indexOutOfRange(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function Reader(e){this.buf=e,this.pos=0,this.len=e.length}var create_array="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Reader(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Reader(e);throw Error("illegal buffer")};function readLongVarint(){var e=new LongBits$2(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function readFixed32_end(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits$2(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader.create=minimal.Buffer?function(e){return(Reader.create=function(e){return minimal.Buffer.isBuffer(e)?new BufferReader(e):create_array(e)})(e)}:create_array,Reader.prototype._slice=minimal.Array.prototype.subarray||minimal.Array.prototype.slice,Reader.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return e}}(),Reader.prototype.int32=function(){return 0|this.uint32()},Reader.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},Reader.prototype.bool=function(){return 0!==this.uint32()},Reader.prototype.fixed32=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)},Reader.prototype.sfixed32=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return 0|readFixed32_end(this.buf,this.pos+=4)},Reader.prototype.float=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var e=minimal.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},Reader.prototype.double=function(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var e=minimal.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},Reader.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw indexOutOfRange(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?new this.buf.constructor(0):this._slice.call(this.buf,t,r)},Reader.prototype.string=function(){var e=this.bytes();return utf8$1.read(e,0,e.length)},Reader.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw indexOutOfRange(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw indexOutOfRange(this)}while(128&this.buf[this.pos++]);return this},Reader.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},Reader._configure=function(e){BufferReader=e;var t=minimal.Long?"toLong":"toNumber";minimal.merge(Reader.prototype,{int64:function(){return readLongVarint.call(this)[t](!1)},uint64:function(){return readLongVarint.call(this)[t](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[t](!1)},fixed64:function(){return readFixed64.call(this)[t](!0)},sfixed64:function(){return readFixed64.call(this)[t](!1)}})};var reader_buffer=BufferReader$1;function BufferReader$1(e){reader.call(this,e)}(BufferReader$1.prototype=Object.create(reader.prototype)).constructor=BufferReader$1,minimal.Buffer&&(BufferReader$1.prototype._slice=minimal.Buffer.prototype.slice),BufferReader$1.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len))};var service=Service;function Service(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");minimal.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(Service.prototype=Object.create(minimal.EventEmitter.prototype)).constructor=Service,Service.prototype.rpcCall=function e(t,r,n,a,o){if(!a)throw TypeError("request must be specified");var i=this;if(!o)return minimal.asPromise(e,i,t,r,n,a);if(i.rpcImpl)try{return i.rpcImpl(t,r[i.requestDelimited?"encodeDelimited":"encode"](a).finish(),function(e,r){if(e)return i.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof n))try{r=n[i.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return i.emit("error",e,t),o(e)}return i.emit("data",r,t),o(null,r)}i.end(!0)})}catch(e){return i.emit("error",e,t),void setTimeout(function(){o(e)},0)}else setTimeout(function(){o(Error("already ended"))},0)},Service.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this};var rpc_1=createCommonjsModule$1(function(e,t){t.Service=service}),roots={},indexMinimal=createCommonjsModule$1(function(e,t){var r=t;function n(){r.Reader._configure(r.BufferReader),r.util._configure()}r.build="minimal",r.Writer=writer,r.BufferWriter=writer_buffer,r.Reader=reader,r.BufferReader=reader_buffer,r.util=minimal,r.rpc=rpc_1,r.roots=roots,r.configure=n,r.Writer._configure(r.BufferWriter),n()}),minimal$1=indexMinimal,minimal_1=minimal$1.roots,minimal_2=minimal$1.Reader,minimal_3=minimal$1.util,$Reader=minimal$1.Reader,$util=minimal$1.util,$root=minimal$1.roots.default||(minimal$1.roots.default={});$root.tensorflow=function(){var e,t,r={};return r.Any=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.typeUrl=e.string();break;case 2:n.value=e.bytes();break;default:e.skipType(7&a)}}return n},e}(),r.DataType=(e={},(t=Object.create(e))[e[0]="DT_INVALID"]=0,t[e[1]="DT_FLOAT"]=1,t[e[2]="DT_DOUBLE"]=2,t[e[3]="DT_INT32"]=3,t[e[4]="DT_UINT8"]=4,t[e[5]="DT_INT16"]=5,t[e[6]="DT_INT8"]=6,t[e[7]="DT_STRING"]=7,t[e[8]="DT_COMPLEX64"]=8,t[e[9]="DT_INT64"]=9,t[e[10]="DT_BOOL"]=10,t[e[11]="DT_QINT8"]=11,t[e[12]="DT_QUINT8"]=12,t[e[13]="DT_QINT32"]=13,t[e[14]="DT_BFLOAT16"]=14,t[e[101]="DT_FLOAT_REF"]=101,t[e[102]="DT_DOUBLE_REF"]=102,t[e[103]="DT_INT32_REF"]=103,t[e[104]="DT_UINT8_REF"]=104,t[e[105]="DT_INT16_REF"]=105,t[e[106]="DT_INT8_REF"]=106,t[e[107]="DT_STRING_REF"]=107,t[e[108]="DT_COMPLEX64_REF"]=108,t[e[109]="DT_INT64_REF"]=109,t[e[110]="DT_BOOL_REF"]=110,t[e[111]="DT_QINT8_REF"]=111,t[e[112]="DT_QUINT8_REF"]=112,t[e[113]="DT_QINT32_REF"]=113,t[e[114]="DT_BFLOAT16_REF"]=114,t),r.TensorShape=function(){function e(e){if(this.dim=[],e)for(var t=Object.keys(e),r=0;r>>3){case 2:n.dim&&n.dim.length||(n.dim=[]),n.dim.push($root.tensorflow.TensorShape.Dim.decode(e,e.uint32()));break;case 3:n.unknownRank=e.bool();break;default:e.skipType(7&a)}}return n},e.Dim=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.size=e.int64();break;case 2:n.name=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}(),r.Tensor=function(){function e(e){if(this.floatVal=[],this.doubleVal=[],this.intVal=[],this.stringVal=[],this.scomplexVal=[],this.int64Val=[],this.boolVal=[],this.uint32Val=[],this.uint64Val=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.dtype=e.int32();break;case 2:n.tensorShape=$root.tensorflow.TensorShape.decode(e,e.uint32());break;case 3:n.versionNumber=e.int32();break;case 4:n.tensorContent=e.bytes();break;case 5:if(n.floatVal&&n.floatVal.length||(n.floatVal=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:n.list=$root.tensorflow.AttrValue.ListValue.decode(e,e.uint32());break;case 2:n.s=e.bytes();break;case 3:n.i=e.int64();break;case 4:n.f=e.float();break;case 5:n.b=e.bool();break;case 6:n.type=e.int32();break;case 7:n.shape=$root.tensorflow.TensorShape.decode(e,e.uint32());break;case 8:n.tensor=$root.tensorflow.Tensor.decode(e,e.uint32());break;case 9:n.placeholder=e.string();break;case 10:n.func=$root.tensorflow.NameAttrList.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e.ListValue=function(){function e(e){if(this.s=[],this.i=[],this.f=[],this.b=[],this.type=[],this.shape=[],this.tensor=[],this.func=[],e)for(var t=Object.keys(e),r=0;r>>3){case 2:n.s&&n.s.length||(n.s=[]),n.s.push(e.bytes());break;case 3:if(n.i&&n.i.length||(n.i=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:a.name=e.string();break;case 2:e.skip().pos++,a.attr===$util.emptyObject&&(a.attr={}),r=e.string(),e.pos++,a.attr[r]=$root.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&o)}}return a},e}(),r.NodeDef=function(){function e(e){if(this.input=[],this.attr={},e)for(var t=Object.keys(e),r=0;r>>3){case 1:a.name=e.string();break;case 2:a.op=e.string();break;case 3:a.input&&a.input.length||(a.input=[]),a.input.push(e.string());break;case 4:a.device=e.string();break;case 5:e.skip().pos++,a.attr===$util.emptyObject&&(a.attr={}),r=e.string(),e.pos++,a.attr[r]=$root.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&o)}}return a},e}(),r.VersionDef=function(){function e(e){if(this.badConsumers=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.producer=e.int32();break;case 2:n.minConsumer=e.int32();break;case 3:if(n.badConsumers&&n.badConsumers.length||(n.badConsumers=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:n.node&&n.node.length||(n.node=[]),n.node.push($root.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:n.versions=$root.tensorflow.VersionDef.decode(e,e.uint32());break;case 2:n.library=$root.tensorflow.FunctionDefLibrary.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e}(),r.CollectionDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.nodeList=$root.tensorflow.CollectionDef.NodeList.decode(e,e.uint32());break;case 2:n.bytesList=$root.tensorflow.CollectionDef.BytesList.decode(e,e.uint32());break;case 3:n.int64List=$root.tensorflow.CollectionDef.Int64List.decode(e,e.uint32());break;case 4:n.floatList=$root.tensorflow.CollectionDef.FloatList.decode(e,e.uint32());break;case 5:n.anyList=$root.tensorflow.CollectionDef.AnyList.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e.NodeList=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.value&&n.value.length||(n.value=[]),n.value.push(e.string());break;default:e.skipType(7&a)}}return n},e}(),e.BytesList=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.value&&n.value.length||(n.value=[]),n.value.push(e.bytes());break;default:e.skipType(7&a)}}return n},e}(),e.Int64List=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:if(n.value&&n.value.length||(n.value=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:if(n.value&&n.value.length||(n.value=[]),2==(7&a))for(var o=e.uint32()+e.pos;e.pos>>3){case 1:n.value&&n.value.length||(n.value=[]),n.value.push($root.tensorflow.Any.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return n},e}(),e}(),r.SaverDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.filenameTensorName=e.string();break;case 2:n.saveTensorName=e.string();break;case 3:n.restoreOpName=e.string();break;case 4:n.maxToKeep=e.int32();break;case 5:n.sharded=e.bool();break;case 6:n.keepCheckpointEveryNHours=e.float();break;case 7:n.version=e.int32();break;default:e.skipType(7&a)}}return n},e.CheckpointFormatVersion=(t={},(r=Object.create(t))[t[0]="LEGACY"]=0,r[t[1]="V1"]=1,r[t[2]="V2"]=2,r),e}(),r.TensorInfo=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.name=e.string();break;case 4:n.cooSparse=$root.tensorflow.TensorInfo.CooSparse.decode(e,e.uint32());break;case 2:n.dtype=e.int32();break;case 3:n.tensorShape=$root.tensorflow.TensorShape.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e.CooSparse=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.valuesTensorName=e.string();break;case 2:n.indicesTensorName=e.string();break;case 3:n.denseShapeTensorName=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}(),r.SignatureDef=function(){function e(e){if(this.inputs={},this.outputs={},e)for(var t=Object.keys(e),r=0;r>>3){case 1:e.skip().pos++,a.inputs===$util.emptyObject&&(a.inputs={}),r=e.string(),e.pos++,a.inputs[r]=$root.tensorflow.TensorInfo.decode(e,e.uint32());break;case 2:e.skip().pos++,a.outputs===$util.emptyObject&&(a.outputs={}),r=e.string(),e.pos++,a.outputs[r]=$root.tensorflow.TensorInfo.decode(e,e.uint32());break;case 3:a.methodName=e.string();break;default:e.skipType(7&o)}}return a},e}(),r.AssetFileDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.tensorInfo=$root.tensorflow.TensorInfo.decode(e,e.uint32());break;case 2:n.filename=e.string();break;default:e.skipType(7&a)}}return n},e}(),r.OpDef=function(){function e(e){if(this.inputArg=[],this.outputArg=[],this.attr=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.name=e.string();break;case 2:n.inputArg&&n.inputArg.length||(n.inputArg=[]),n.inputArg.push($root.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 3:n.outputArg&&n.outputArg.length||(n.outputArg=[]),n.outputArg.push($root.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 4:n.attr&&n.attr.length||(n.attr=[]),n.attr.push($root.tensorflow.OpDef.AttrDef.decode(e,e.uint32()));break;case 8:n.deprecation=$root.tensorflow.OpDef.OpDeprecation.decode(e,e.uint32());break;case 5:n.summary=e.string();break;case 6:n.description=e.string();break;case 18:n.isCommutative=e.bool();break;case 16:n.isAggregate=e.bool();break;case 17:n.isStateful=e.bool();break;case 19:n.allowsUninitializedInput=e.bool();break;default:e.skipType(7&a)}}return n},e.ArgDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.name=e.string();break;case 2:n.description=e.string();break;case 3:n.type=e.int32();break;case 4:n.typeAttr=e.string();break;case 5:n.numberAttr=e.string();break;case 6:n.typeListAttr=e.string();break;case 16:n.isRef=e.bool();break;default:e.skipType(7&a)}}return n},e}(),e.AttrDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.name=e.string();break;case 2:n.type=e.string();break;case 3:n.defaultValue=$root.tensorflow.AttrValue.decode(e,e.uint32());break;case 4:n.description=e.string();break;case 5:n.hasMinimum=e.bool();break;case 6:n.minimum=e.int64();break;case 7:n.allowedValues=$root.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&a)}}return n},e}(),e.OpDeprecation=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.version=e.int32();break;case 2:n.explanation=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}(),r.OpList=function(){function e(e){if(this.op=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.op&&n.op.length||(n.op=[]),n.op.push($root.tensorflow.OpDef.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return n},e}(),r.MetaGraphDef=function(){function e(e){if(this.collectionDef={},this.signatureDef={},this.assetFileDef=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:a.metaInfoDef=$root.tensorflow.MetaGraphDef.MetaInfoDef.decode(e,e.uint32());break;case 2:a.graphDef=$root.tensorflow.GraphDef.decode(e,e.uint32());break;case 3:a.saverDef=$root.tensorflow.SaverDef.decode(e,e.uint32());break;case 4:e.skip().pos++,a.collectionDef===$util.emptyObject&&(a.collectionDef={}),r=e.string(),e.pos++,a.collectionDef[r]=$root.tensorflow.CollectionDef.decode(e,e.uint32());break;case 5:e.skip().pos++,a.signatureDef===$util.emptyObject&&(a.signatureDef={}),r=e.string(),e.pos++,a.signatureDef[r]=$root.tensorflow.SignatureDef.decode(e,e.uint32());break;case 6:a.assetFileDef&&a.assetFileDef.length||(a.assetFileDef=[]),a.assetFileDef.push($root.tensorflow.AssetFileDef.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return a},e.MetaInfoDef=function(){function e(e){if(this.tags=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.metaGraphVersion=e.string();break;case 2:n.strippedOpList=$root.tensorflow.OpList.decode(e,e.uint32());break;case 3:n.anyInfo=$root.tensorflow.Any.decode(e,e.uint32());break;case 4:n.tags&&n.tags.length||(n.tags=[]),n.tags.push(e.string());break;case 5:n.tensorflowVersion=e.string();break;case 6:n.tensorflowGitVersion=e.string();break;default:e.skipType(7&a)}}return n},e}(),e}(),r.SavedModel=function(){function e(e){if(this.metaGraphs=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.savedModelSchemaVersion=e.int64();break;case 2:n.metaGraphs&&n.metaGraphs.length||(n.metaGraphs=[]),n.metaGraphs.push($root.tensorflow.MetaGraphDef.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return n},e}(),r.FunctionDefLibrary=function(){function e(e){if(this.function=[],this.gradient=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.function&&n.function.length||(n.function=[]),n.function.push($root.tensorflow.FunctionDef.decode(e,e.uint32()));break;case 2:n.gradient&&n.gradient.length||(n.gradient=[]),n.gradient.push($root.tensorflow.GradientDef.decode(e,e.uint32()));break;default:e.skipType(7&a)}}return n},e}(),r.FunctionDef=function(){function e(e){if(this.attr={},this.nodeDef=[],this.ret={},e)for(var t=Object.keys(e),r=0;r>>3){case 1:a.signature=$root.tensorflow.OpDef.decode(e,e.uint32());break;case 5:e.skip().pos++,a.attr===$util.emptyObject&&(a.attr={}),r=e.string(),e.pos++,a.attr[r]=$root.tensorflow.AttrValue.decode(e,e.uint32());break;case 3:a.nodeDef&&a.nodeDef.length||(a.nodeDef=[]),a.nodeDef.push($root.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:e.skip().pos++,a.ret===$util.emptyObject&&(a.ret={}),r=e.string(),e.pos++,a.ret[r]=e.string();break;default:e.skipType(7&o)}}return a},e}(),r.GradientDef=function(){function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.functionName=e.string();break;case 2:n.gradientFunc=e.string();break;default:e.skipType(7&a)}}return n},e}(),r}();var compiled_api=$root,compiled_api_1=compiled_api.tensorflow;function getParamValue(e,t,r,n){var a=t.params[e];if(a&&void 0!==a.inputIndex){if("tensor"===a.type)return getTensor(t.inputNames[a.inputIndex],r,n);if("tensors"===a.type)return(0===a.inputIndex?0===a.inputParamLength?t.inputNames:t.inputNames.slice(a.inputIndex,-a.inputParamLength):t.inputNames.splice(a.inputIndex)).map(function(e){return getTensor(e,r,n)});var o=Array.prototype.slice.call(getTensor(t.inputNames.slice(a.inputIndex)[0],r,n).dataSync());return"number"===a.type?o[0]:o}return a&&a.value}function getTensor(e,t,r){var n=parseNodeName(e),a=n[0],o=n[1],i=r.currentContextIds.find(function(e){return!!t[getNodeNameWithContextId(a,e)]});return void 0!==i?t[getNodeNameWithContextId(a,i)][o]:void 0}function getTensorsForCurrentContenxt(e,t,r){return t[getNodeNameWithContextId(e,r.currentContextId)]}function getNodeNameAndIndex(e,t){var r=parseNodeName(e),n=r[0],a=r[1];return[getNodeNameWithContextId(n,t&&t.currentContextId),a]}function getNodeNameWithContextId(e,t){return t?e+"-"+t:e}function parseNodeName(e){var t=e.lastIndexOf(":");return-1===t?[e,0]:[e.substring(0,t),Number(e.substring(t+1))]}function split$1$1(e,t){for(var r=[],n=0;n=this.tensors.length)throw new Error("Tried to read from index "+e+", but array size is: "+this.tensors.length);var t=this.tensors[e];if(t.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+e+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor},e.prototype.readMany=function(e){var t=this;return e.map(function(e){return t.read(e)})},e.prototype.write=function(e,t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error("Tried to write to index "+e+", but array is not resizeable and size is: "+this.maxSize);var r=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+",\n because the value dtype is "+t.dtype+", but TensorArray dtype is "+this.dtype+".");if(0===this.size()&&0===this.elementShape.length&&(this.elementShape=t.shape),this.assertShapesMatch(this.elementShape,t.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+e+"."),r&&r.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been read.");if(r&&r.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been written.");r.tensor=t,r.written=!0,this.tensors[e]=r},e.prototype.writeMany=function(e,t){var r=this;if(e.length!==t.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+e.length+" is not the same as tensors size: "+t.length+".");e.forEach(function(e,n){return r.write(e,t[n])})},e.prototype.gather=function(e,t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+t);if(!e){e=[];for(var r=0;r=this.maxSize)throw new Error("Max index must be < array size ("+r+" vs. "+this.maxSize+")");this.writeMany(e,unstack(t,0))},e.prototype.split=function(e,t){var r=this;if(t.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+t.dtype);var n=0,a=e.map(function(e){return n+=e});if(n!==t.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+n+", and tensor's shape is: "+t.shape);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+e.length+"), and the TensorArray is not marked as dynamically resizeable");var o=0===n?0:t.size/n,i=[];tidy(function(){t=t.reshape([1,n,o]);for(var s=0;s1)for(var y=1;y1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},e.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},e.prototype.getWeight=function(e){return this.weightMap[e]},e.prototype.addTensorArray=function(e){this.tensorArrayMap[e.id]=e},e.prototype.getTensorArray=function(e){return this.tensorArrayMap[e]},e}(),GraphExecutor=function(){function e(e){this.graph=e,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=e.placeholders,this._outputs=e.outputs,this.compile()}return Object.defineProperty(e.prototype,"weightMap",{get:function(){return this._weightMap},set:function(e){var t=Object.keys(e).map(function(t){return e[t].map(function(e){return e.id})});this.weightIds=[].concat.apply([],t),this._weightMap=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.placeholders.map(function(e){return{name:e.name,shape:e.params.shape?e.params.shape.value:void 0,dtype:e.params.dtype?e.params.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this._outputs.map(function(e){return{name:e.name,shape:e.params.shape?e.params.shape.value:void 0,dtype:e.params.dtype?e.params.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.placeholders.map(function(e){return e.name})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.outputs.map(function(e){return e.name})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isControlFlowModel",{get:function(){return this.graph.withControlFlow},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isDynamicShapeModel",{get:function(){return this.graph.withDynamicShape},enumerable:!0,configurable:!0}),e.prototype.compile=function(e){if(!this.graph.withControlFlow&&!this.graph.withDynamicShape){var t=[],r=e||this.graph.placeholders,n=r.map(function(e){return e.name}).sort().join(this.SEPERATOR);if(!this.compiledMap.get(n)){for(var a=r.concat(this.graph.weights),o={};a.length>0;){var i=a.pop();o[i.name]=!0,t.push(i),i.children.forEach(function(e){!o[e.name]&&e.inputNames.every(function(e){var t=getNodeNameAndIndex(e)[0];return o[t]})&&a.push(e)})}this.compiledMap.set(n,t)}}},e.prototype.execute=function(e,t,r){var n=this;void 0===t&&(t=!0);var a=Object.keys(e).sort();this.checkInput(e,t),this.checkInputShapeAndType(e,t),this.compile(a.map(function(e){return n.graph.nodes[e]}));var o=this.calculateOutputs(r);this.checkOutput(this.compiledMap.get(a.join(this.SEPERATOR)),o);var i={};return tidy(function(){for(var t=new ExecutionContext(n._weightMap,i),r=__assign$2({},n.weightMap,e),s=n.getFrozenTensorIds(r),u={},l=n.compiledMap.get(a.join(n.SEPERATOR)),p=0;p0?(p=this.processStack(a,o,t,i,l,u,r,s),[4,Promise.all(p)]):[3,3];case 2:return d.sent(),[3,1];case 3:return[2,i]}})})},e.prototype.processStack=function(e,t,r,n,a,o,i,s){for(var u=this,l=[],p=function(){var p=t.pop();r.currentContext=p.contexts;var d="";if("enter"===p.node.op&&getParamValue("isConstant",p.node,n,r)&&(d=getNodeNameAndIndex(p.node.name,r)[0]),-1===e.indexOf(p.node)){var h=executeOp$16(p.node,n,r);d||(d=getNodeNameAndIndex(p.node.name,r)[0]);var f=r.currentContext;h instanceof Promise?l.push(h.then(function(e){return n[d]=e,r.currentContext=f,u.checkTensorForDisposal(d,p.node,n,r,o,i,s),u.processChildNodes(p.node,t,r,n,a),e})):(n[d]=h,c.checkTensorForDisposal(d,p.node,n,r,o,i,s),c.processChildNodes(p.node,t,r,n,a))}else c.processChildNodes(p.node,t,r,n,a)},c=this;t.length>0;)p();return l},e.prototype.processChildNodes=function(e,t,r,n,a){e.children.forEach(function(e){var o=getNodeNameAndIndex(e.name,r)[0];a[o]||("merge"===e.op?e.inputNames.some(function(e){return!!getTensor(e,n,r)})&&(a[o]=!0,t.push({contexts:r.currentContext,node:e})):e.inputNames.every(function(e){return!!getTensor(e,n,r)})&&(a[o]=!0,t.push({contexts:r.currentContext,node:e})))})},e.prototype.calculateOutputs=function(e){return!e||e instanceof Array||(e=[e]),e||this.graph.outputs.map(function(e){return e.name})},e.prototype.findOutputs=function(e,t,r){return this.calculateOutputs(r).reduce(function(r,n){return r[n]=getTensor(n,e,t),r},{})},e.prototype.dispose=function(){var e=this;Object.keys(this.weightMap).forEach(function(t){return e.weightMap[t].forEach(function(e){return e.dispose()})})},e.prototype.checkInputShapeAndType=function(e,t){void 0===t&&(t=!0),this.placeholders.forEach(function(r){var n=e[r.name];if(t||n){var a=n[0];if(r.params.shape&&r.params.shape.value){var o=r.params.shape.value,i=o.length===a.shape.length&&a.shape.every(function(e,t){return-1===o[t]||o[t]===e});util.assert(i,"The shape of dict['"+r.name+"'] provided in model.execute(dict) must be ["+o+"], but was ["+a.shape+"]")}r.params.dtype&&r.params.dtype.value&&util.assert(a.dtype===r.params.dtype.value,"The dtype of dict['"+r.name+"'] provided in model.execute(dict) must be "+r.params.dtype.value+", but was "+a.dtype)}})},e.prototype.checkInput=function(e,t){var r=this;void 0===t&&(t=!0);var n=Object.keys(e),a=[],o=[];this.inputNodes.forEach(function(e){-1===n.indexOf(e)&&a.push(e)}),n.forEach(function(e){-1===r.inputNodes.indexOf(e)&&o.push(e)});var i=o.filter(function(e){return!r.graph.nodes[e]});if(a.length>0&&t)throw new Error("The dict provided in model.execute(dict) has the keys ["+n+"], but is missing the required keys: ["+a+"].");if(o.length>0&&t)throw new Error("The dict provided in model.execute(dict) has unused keys: ["+o+"]. Please provide only the following keys: ["+this.inputNodes+"].");if(i.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+i+"] not part of model graph.")},e.prototype.checkOutput=function(e,t){var r=e.map(function(e){return e.name}),n=[];if(t.forEach(function(e){-1===r.indexOf(e)&&n.push(e)}),n.length>0)throw new Error("The following outputs are not generated by the execution: ["+n+"].")},e}(),TFHUB_SEARCH_PARAM="?tfjs-format=file",DEFAULT_MODEL_NAME="tensorflowjs_model.pb",DEFAULT_MANIFEST_NAME="weights_manifest.json",FrozenModel=function(){function e(e,t,r,n){this.modelUrl=e,this.weightManifestUrl=t,this.requestOption=r,this.weightPrefix=n,this.version="n/a"}return Object.defineProperty(e.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),e.prototype.findIOHandler=function(){var e=[this.modelUrl,this.weightManifestUrl];if(this.requestOption)this.handler=io.browserHTTPRequest(e,this.requestOption,this.weightPrefix);else{var t=io.getLoadHandlers(e);if(0===t.length)t.push(io.browserHTTPRequest(e,this.requestOption));else if(t.length>1)throw new Error("Found more than one ("+t.length+") load handlers for URL '"+[e]+"'");this.handler=t[0]}},e.prototype.load=function(){return __awaiter$2(this,void 0,void 0,function(){var e,t,r;return __generator$2(this,function(n){switch(n.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return e=n.sent(),t=compiled_api_1.GraphDef.decode(new Uint8Array(e.modelTopology)),this.version=t.versions.producer+"."+t.versions.minConsumer,r=io.decodeWeights(e.weightData,e.weightSpecs),this.executor=new GraphExecutor(OperationMapper.Instance.transformGraph(t)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),[2,!0]}})})},e.prototype.predict=function(e,t){return this.execute_(e,!0,this.outputNodes)},e.prototype.constructTensorMap=function(e){var t=e instanceof Tensor?[e]:e;if(t.length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the frozen model has "+this.inputNodes.length+" placeholders, while there are "+t.length+" input tensors.");return this.inputNodes.reduce(function(e,r,n){return e[r]=t[n],e},{})},e.prototype.execute=function(e,t){return this.execute_(e,!1,t)},e.prototype.execute_=function(e,t,r){if(void 0===t&&(t=!0),r=r||this.outputNodes,(e instanceof Tensor||Array.isArray(e))&&(e=this.constructTensorMap(e)),this.executor.isControlFlowModel||this.executor.isDynamicShapeModel)throw new Error("The model contains control flow or dynamic shape ops, please use executeAsync method");var n=this.executor.execute(this.convertTensorMapToTensorsMap(e),t,r),a=Object.keys(n);return Array.isArray(r)&&r.length>1?r.map(function(e){return n[e]}):n[a[0]]},e.prototype.executeAsync=function(e,t){return __awaiter$2(this,void 0,void 0,function(){var r,n;return __generator$2(this,function(a){switch(a.label){case 0:if(!this.executor.isControlFlowModel&&!this.executor.isDynamicShapeModel)throw new Error("The model does not contain control flow or dynamic shape ops, please use execute method for better performance.");return t=t||this.outputNodes,(e instanceof Tensor||Array.isArray(e))&&(e=this.constructTensorMap(e)),[4,this.executor.executeAsync(this.convertTensorMapToTensorsMap(e),t)];case 1:return r=a.sent(),n=Object.keys(r),[2,Array.isArray(t)&&t.length>1?t.map(function(e){return r[e]}):r[n[0]]]}})})},e.prototype.convertTensorMapToTensorsMap=function(e){return Object.keys(e).reduce(function(t,r){return t[r]=[e[r]],t},{})},e.prototype.dispose=function(){this.executor.dispose()},e}();function loadFrozenModel(e,t,r){return __awaiter$2(this,void 0,void 0,function(){var n;return __generator$2(this,function(a){switch(a.label){case 0:return[4,(n=new FrozenModel(e,t,r)).load()];case 1:return a.sent(),[2,n]}})})}function loadTfHubModule(e,t){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(r){return e.endsWith("/")||(e+="/"),[2,loadFrozenModel(""+e+DEFAULT_MODEL_NAME+TFHUB_SEARCH_PARAM,""+e+DEFAULT_MANIFEST_NAME+TFHUB_SEARCH_PARAM,t)]})})}var version$2="0.7.1",extendStatics$2=function(e,t){return(extendStatics$2=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function __extends$2(e,t){function r(){this.constructor=e}extendStatics$2(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function __awaiter$3(e,t,r,n){return new(r||(r=Promise))(function(a,o){function i(e){try{u(n.next(e))}catch(e){o(e)}}function s(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){e.done?a(e.value):new r(function(t){t(e.value)}).then(i,s)}u((n=n.apply(e,t||[])).next())})}function __generator$3(e,t){var r,n,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,n&&(a=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,n=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=(a=i.trys).length>0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]>>0,t=(n*=t)>>>0,t+=4294967296*(n-=t)}return 2.3283064365386963e-10*(t>>>0)});r.next=function(){var e=2091639*r.s0+2.3283064365386963e-10*r.c;return r.s0=r.s1,r.s1=r.s2,r.s2=e-(r.c=0|e)},r.c=1,r.s0=n(" "),r.s1=n(" "),r.s2=n(" "),r.s0-=n(e),r.s0<0&&(r.s0+=1),r.s1-=n(e),r.s1<0&&(r.s1+=1),r.s2-=n(e),r.s2<0&&(r.s2+=1),n=null}(e),a=t&&t.state,o=r.next;return o.int32=function(){return 4294967296*r.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.alea=a}(0,e)}),xor128$1=createCommonjsModule$2(function(e){!function(e,t,r){function n(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var r=new function(e){var t=this,r="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:r+=e;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xor128=a}(0,e)}),xorwow$1=createCommonjsModule$2(function(e){!function(e,t,r){function n(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var r=new function(e){var t=this,r="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:r+=e;for(var n=0;n>>4),t.next()}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xorwow=a}(0,e)}),xorshift7$1=createCommonjsModule$2(function(e){!function(e,t,r){function n(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var r=new function(e){var t=this;t.next=function(){var e,r,n=t.x,a=t.i;return e=n[a],r=(e^=e>>>7)^e<<24,r^=(e=n[a+1&7])^e>>>10,r^=(e=n[a+3&7])^e>>>3,r^=(e=n[a+4&7])^e<<7,e=n[a+7&7],r^=(e^=e<<13)^e<<9,n[a]=r,t.i=a+1&7,r},function(e,t){var r,n=[];if(t===(0|t))n[0]=t;else for(t=""+t,r=0;r0;--r)e.next()}(t,e)}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&(a.x&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xorshift7=a}(0,e)}),xor4096$1=createCommonjsModule$2(function(e){!function(e,t,r){function n(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var r=new function(e){var t=this;t.next=function(){var e,r,n=t.w,a=t.X,o=t.i;return t.w=n=n+1640531527|0,r=a[o+34&127],e=a[o=o+1&127],r^=r<<13,e^=e<<17,r^=r>>>15,e^=e>>>12,r=a[o]=r^e,t.i=o,r+(n^n>>>16)|0},function(e,t){var r,n,a,o,i,s=[],u=128;for(t===(0|t)?(n=t,t=null):(t+="\0",n=0,u=Math.max(u,t.length)),a=0,o=-32;o>>15,n^=n<<4,n^=n>>>13,o>=0&&(i=i+1640531527|0,a=0==(r=s[127&o]^=n+i)?a+1:0);for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,o=512;o>0;--o)n=s[a+34&127],r=s[a=a+1&127],n^=n<<13,r^=r<<17,n^=n>>>15,r^=r>>>12,s[a]=n^r;e.w=i,e.X=s,e.i=a}(t,e)}(e),a=t&&t.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&(a.X&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.xor4096=a}(0,e)}),tychei$1=createCommonjsModule$2(function(e){!function(e,t,r){function n(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var r=new function(e){var t=this,r="";t.next=function(){var e=t.b,r=t.c,n=t.d,a=t.a;return e=e<<25^e>>>7^r,r=r-n|0,n=n<<24^n>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^r,t.c=r=r-n|0,t.d=n<<16^r>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):r+=e;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=r.next,o.quick=o,a&&("object"==typeof a&&n(a,r),o.state=function(){return n(r,{})}),o}t&&t.exports?t.exports=a:this.tychei=a}(0,e)}),seedrandom$2=createCommonjsModule$2(function(e){!function(t,r){var n,a=(0,eval)("this"),o=256,i=6,s="random",u=r.pow(o,i),l=r.pow(2,52),p=2*l,c=o-1;function d(e,d,g){var y=[],v=f(function e(t,r){var n,a=[],o=typeof t;if(r&&"object"==o)for(n in t)try{a.push(e(t[n],r-1))}catch(e){}return a.length?a:"string"==o?t:t+"\0"}((d=1==d?{entropy:!0}:d||{}).entropy?[e,m(t)]:null==e?function(){try{var e;return n&&(e=n.randomBytes)?e=e(o):(e=new Uint8Array(o),(a.crypto||a.msCrypto).getRandomValues(e)),m(e)}catch(e){var r=a.navigator,i=r&&r.plugins;return[+new Date,a,i,a.screen,m(t)]}}():e,3),y),x=new function(e){var t,r=e.length,n=this,a=0,i=n.i=n.j=0,s=n.S=[];for(r||(e=[r++]);a=p;)e/=2,t/=2,r>>>=1;return(e+r)/t};return b.int32=function(){return 0|x.g(4)},b.quick=function(){return x.g(4)/4294967296},b.double=b,f(m(x.S),t),(d.pass||g||function(e,t,n,a){return a&&(a.S&&h(a,x),e.state=function(){return h(x,{})}),n?(r[s]=e,t):e})(b,v,"global"in d?d.global:this==r,d.state)}function h(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function f(e,t){for(var r,n=e+"",a=0;a0;)n=Math.random()*t|0,r=e[--t],e[t]=e[n],e[n]=r}function n(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function a(e,t){if(void 0===t&&(t=[]),Array.isArray(e)||s(e))for(var r=0;r1;--t)if(e%t==0)return[t,e/t];return[1,e]},t.createShuffledIndices=function(e){for(var t=new Uint32Array(e),n=0;n=r?a():setTimeout(i,s)}};i()})},t.inferFromImplicitShape=function(e,t){for(var r=1,n=-1,a=0;a=0)r*=e[a];else if(-1===e[a]){if(-1!==n)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+n+" and dim "+a);n=a}else if(e[a]<0)throw Error("Shapes can not be < 0. Found "+e[a]+" at dim "+a);if(-1===n){if(t>0&&t!==r)throw Error("Size("+t+") must match the product of shape "+e);return e}if(0===r)throw Error("Cannot infer the missing size in ["+e+"] when there are 0 elements");if(t%r!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+r);var o=e.slice();return o[n]=t/r,o},t.squeezeShape=function(e,t){for(var r=[],n=[],a=0,o=0;oo)&&1===e[o]&&(r.push(e[o]),n.push(o)),t[a]<=o&&a++}1!==e[o]&&(r.push(e[o]),n.push(o))}return{newShape:r,keptDims:n}},t.getTypedArrayFromDType=function(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);r=new Uint8Array(t)}return r},t.getArrayFromDType=function(e,t){var r=null;if(null==e||"float32"===e)r=new Float32Array(t);else if("int32"===e)r=new Int32Array(t);else if("bool"===e)r=new Uint8Array(t);else{if("string"!==e)throw new Error("Unknown data type "+e);r=new Array(t)}return r},t.checkComputationForNaN=function(e,t,r){if("float32"===t)for(var n=0;n=0;--n)r[n]=r[n+1]*e[n+1];return r},t.toTypedArray=function(e,t,r){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(Array.isArray(e)&&(e=a(e)),null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return r&&i(e,t),new Int32Array(e);if("bool"===t){for(var n=new Uint8Array(e.length),o=0;o1)for(var c=0;c20){var d=3*l,h=Array.from(t.slice(0,d)),f=Array.from(t.slice(p-3*l,p));return"complex64"===o&&(h=a(h),f=a(f)),["["+h.map(function(e,t){return n(e,s[t])}).join(", ")+", ..., "+f.map(function(e,t){return n(e,s[p-3+t])}).join(", ")+"]"]}return["["+("complex64"===o?a(t):Array.from(t)).map(function(e,t){return n(e,s[t])}).join(", ")+"]"]}var m=r.slice(1),g=i.slice(1),y=i[0]*l,v=[];if(p>20){for(var x=0;x<3;x++){var b=(w=x*y)+y;v.push.apply(v,e(t.slice(w,b),m,o,g,s,!1))}v.push("...");for(x=p-3;x0&&a[a.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]0?this.prefetch(t):this,n=[],a=0,[4,r.next()];case 1:o=i.sent(),i.label=2;case 2:return o.done?[3,4]:(n.push(o.value),++a>=e?[2,n]:[4,r.next()]);case 3:return o=i.sent(),[3,2];case 4:return[2,n]}})})},e.prototype.resolveFully=function(){return __awaiter$3(this,void 0,void 0,function(){var e;return __generator$3(this,function(t){switch(t.label){case 0:return[4,this.next()];case 1:e=t.sent(),t.label=2;case 2:return e.done?[3,4]:[4,this.next()];case 3:return e=t.sent(),[3,2];case 4:return[2]}})})},e.prototype.resolveWhile=function(e){return __awaiter$3(this,void 0,void 0,function(){var t,r;return __generator$3(this,function(n){switch(n.label){case 0:return[4,this.next()];case 1:t=n.sent(),r=e(t.value),n.label=2;case 2:return t.done||!r?[3,4]:[4,this.next()];case 3:return t=n.sent(),r=e(t.value),[3,2];case 4:return[2]}})})},e.prototype.handleErrors=function(e){return new ErrorHandlingLazyIterator(this,e)},e.prototype.filter=function(e){return new FilterIterator(this,e)},e.prototype.map=function(e){return new MapIterator(this,e)},e.prototype.mapAsync=function(e){return new AsyncMapIterator(this,e)},e.prototype.serialMapAsync=function(e){return new AsyncMapIterator(this,e).serial()},e.prototype.flatmap=function(e){return new FlatmapIterator(this,e)},e.prototype.forEach=function(e){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(t){return[2,this.map(e).resolveFully()]})})},e.prototype.serialForEach=function(e){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(t){return[2,this.serialMapAsync(e).resolveWhile(function(e){return!0===e})]})})},e.prototype.rowMajorBatch=function(e,t){return void 0===t&&(t=!0),new RowMajorBatchIterator(this,e,t)},e.prototype.columnMajorBatch=function(e,t,r){return void 0===t&&(t=!0),void 0===r&&(r=zipToList),this.rowMajorBatch(e,t).map(function(e){return deepZip(e,r)})},e.prototype.concatenate=function(e,t){return new ChainedIterator(iteratorFromItems([this,e]),t)},e.prototype.take=function(e){return e<0||null==e?this:new TakeIterator(this,e)},e.prototype.skip=function(e){return e<0||null==e?this:new SkipIterator(this,e)},e.prototype.prefetch=function(e){return new PrefetchIterator(this,e)},e.prototype.shuffle=function(e,t){return new ShuffleIterator(this,e,t)},e.prototype.serial=function(){return new SerialIterator(this)},e}(),ArrayIterator=function(e){function t(t){var r=e.call(this)||this;return r.items=t,r.trav=0,r}return __extends$2(t,e),t.prototype.summary=function(){return"Array of "+this.items.length+" items"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e;return __generator$3(this,function(t){return this.trav>=this.items.length?[2,{value:null,done:!0}]:(e=this.items[this.trav],this.trav++,[2,{value:e,done:!1}])})})},t}(LazyIterator),FunctionCallIterator=function(e){function t(t){var r=e.call(this)||this;return r.nextFn=t,r}return __extends$2(t,e),t.prototype.summary=function(){return"Function call"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){try{return[2,this.nextFn()]}catch(e){throw e.message="Error thrown while iterating through a dataset: "+e.message,e}return[2]})})},t}(LazyIterator),SerialIterator=function(e){function t(t){var r=e.call(this)||this;return r.upstream=t,r.lastRead=Promise.resolve({value:null,done:!1}),r}return __extends$2(t,e),t.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e=this;return __generator$3(this,function(t){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){return[2,this.upstream.next()]})})},t}(LazyIterator),SkipIterator=function(e){function t(t,r){var n=e.call(this)||this;return n.upstream=t,n.maxCount=r,n.count=0,n.lastRead=Promise.resolve({value:null,done:!1}),n}return __extends$2(t,e),t.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e=this;return __generator$3(this,function(t){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return __awaiter$3(this,void 0,void 0,function(){var e;return __generator$3(this,function(t){switch(t.label){case 0:return this.count++ Take"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},t}(LazyIterator),RowMajorBatchIterator=function(e){function t(t,r,n){void 0===n&&(n=!0);var a=e.call(this)||this;return a.upstream=t,a.batchSize=r,a.enableSmallLastBatch=n,a.lastRead=Promise.resolve({value:null,done:!1}),a}return __extends$2(t,e),t.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e=this;return __generator$3(this,function(t){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return __awaiter$3(this,void 0,void 0,function(){var e,t;return __generator$3(this,function(r){switch(r.label){case 0:e=[],r.label=1;case 1:return e.length0?[2,{value:e,done:!1}]:[2,{value:null,done:!0}]:(e.push(t.value),[3,1]);case 3:return[2,{value:e,done:!1}]}})})},t}(LazyIterator),FilterIterator=function(e){function t(t,r){var n=e.call(this)||this;return n.upstream=t,n.predicate=r,n.lastRead=Promise.resolve({value:null,done:!1}),n}return __extends$2(t,e),t.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e=this;return __generator$3(this,function(t){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return __awaiter$3(this,void 0,void 0,function(){var e;return __generator$3(this,function(t){switch(t.label){case 0:return[4,this.upstream.next()];case 1:return(e=t.sent()).done||this.predicate(e.value)?[2,e]:(dispose(e.value),[3,0]);case 2:return[2]}})})},t}(LazyIterator),MapIterator=function(e){function t(t,r){var n=e.call(this)||this;return n.upstream=t,n.transform=r,n}return __extends$2(t,e),t.prototype.summary=function(){return this.upstream.summary()+" -> Map"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e,t,r,n,a,o,i;return __generator$3(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((e=s.sent()).done)return[2,{value:null,done:!0}];for(t=tensor_util_6(e.value),r=this.transform(e.value),n=tensor_util_6(r),a=0,o=t;a handleErrors"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e=this;return __generator$3(this,function(t){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return __awaiter$3(this,void 0,void 0,function(){var e;return __generator$3(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return[2,t.sent()];case 3:return e=t.sent(),this.handler(e)?[3,4]:[2,{value:null,done:!0}];case 4:return[3,0];case 5:return[2]}})})},t}(LazyIterator),AsyncMapIterator=function(e){function t(t,r){var n=e.call(this)||this;return n.upstream=t,n.transform=r,n}return __extends$2(t,e),t.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e,t,r,n,a,o,i;return __generator$3(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:return(e=s.sent()).done?[2,{value:null,done:!0}]:(t=tensor_util_6(e.value),[4,this.transform(e.value)]);case 2:for(r=s.sent(),n=tensor_util_6(r),a=0,o=t;a Flatmap"},t.prototype.pump=function(){return __awaiter$3(this,void 0,void 0,function(){var e,t,r,n,a,o,i;return __generator$3(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((e=s.sent()).done)return[2,!1];for(t=tensor_util_6(e.value),r=this.transform(e.value),n=tensor_util_6(r),this.outputQueue.pushAll(r),a=0,o=t;a Chained"},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},t.prototype.readFromChain=function(e){return __awaiter$3(this,void 0,void 0,function(){var t,r;return __generator$3(this,function(n){switch(n.label){case 0:return[4,e];case 1:return n.sent(),null!=this.iterator?[3,3]:[4,this.moreIterators.next()];case 2:if((t=n.sent()).done)return[2,{value:null,done:!0}];this.iterator=t.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),n.label=3;case 3:return[4,this.iterator.next()];case 4:return(r=n.sent()).done?(this.iterator=null,[2,this.readFromChain(e)]):[2,r]}})})},t}(LazyIterator),t;t=ZipMismatchMode||(ZipMismatchMode={}),t[t.FAIL=0]="FAIL",t[t.SHORTEST=1]="SHORTEST",t[t.LONGEST=2]="LONGEST";var ZipIterator=function(e){function t(t,r){void 0===r&&(r=ZipMismatchMode.FAIL);var n=e.call(this)||this;return n.iterators=t,n.mismatchMode=r,n.count=0,n.currentPromise=null,n}return __extends$2(t,e),t.prototype.summary=function(){return"{TODO: fill in upstream of zip summaries} -> Zip"},t.prototype.nextState=function(e){return __awaiter$3(this,void 0,void 0,function(){function t(e){return e instanceof LazyIterator?{value:e.next().then(function(e){return r++,e.done&&n++,e.value}),recurse:!1}:{value:null,recurse:!0}}var r,n,a;return __generator$3(this,function(o){switch(o.label){case 0:return[4,e];case 1:return o.sent(),r=0,n=0,[4,deepMapAndAwaitAll(this.iterators,t)];case 2:if(a=o.sent(),r===n)return[2,{value:null,done:!0}];if(n>0)switch(this.mismatchMode){case ZipMismatchMode.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case ZipMismatchMode.SHORTEST:return[2,{value:null,done:!0}];case ZipMismatchMode.LONGEST:}return this.count++,[2,{value:a,done:!1}]}})})},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){switch(e.label){case 0:return this.currentPromise=this.nextState(this.currentPromise),[4,this.currentPromise];case 1:return[2,e.sent()]}})})},t}(LazyIterator),PrefetchIterator=function(e){function t(t,r){var n=e.call(this)||this;return n.upstream=t,n.bufferSize=r,n.buffer=new RingBuffer(r),n}return __extends$2(t,e),t.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},t.prototype.refill=function(){for(;!this.buffer.isFull();){var e=this.upstream.next();this.buffer.push(e)}},t.prototype.next=function(){return this.refill(),this.buffer.shift()},t}(LazyIterator),ShuffleIterator=function(e){function t(t,r,n){var a=e.call(this,t,r)||this;return a.upstream=t,a.windowSize=r,a.upstreamExhausted=!1,a.random=seedrandom_1$1(n||util.now().toString()),a.lastRead=Promise.resolve({value:null,done:!1}),a}return __extends$2(t,e),t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e=this;return __generator$3(this,function(t){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.randomInt=function(e){return Math.floor(this.random()*e)},t.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},t.prototype.serialNext=function(){return __awaiter$3(this,void 0,void 0,function(){var e,t;return __generator$3(this,function(r){switch(r.label){case 0:this.upstreamExhausted||this.refill(),r.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(e=this.chooseIndex(),[4,this.buffer.shuffleExcise(e)]);case 2:return(t=r.sent()).done?(this.upstreamExhausted=!0,[3,1]):(this.refill(),[2,t]);case 3:return[2,{value:null,done:!0}]}})})},t}(PrefetchIterator),Dataset=function(){function e(){}return e.prototype.filter=function(e){var t=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){return __generator$3(this,function(t){switch(t.label){case 0:return[4,r.iterator()];case 1:return[2,t.sent().filter(function(t){return tidy(function(){return e(t)})})]}})})})},e.prototype.map=function(e){var t=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){return __generator$3(this,function(t){switch(t.label){case 0:return[4,r.iterator()];case 1:return[2,t.sent().map(function(t){return tidy(function(){return e(t)})})]}})})})},e.prototype.mapAsync=function(e){var t=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){return __generator$3(this,function(t){switch(t.label){case 0:return[4,r.iterator()];case 1:return[2,t.sent().mapAsync(e)]}})})})},e.prototype.batch=function(e,t){var r=this;void 0===t&&(t=!0);var n=this;return datasetFromIteratorFn(function(){return __awaiter$3(r,void 0,void 0,function(){return __generator$3(this,function(r){switch(r.label){case 0:return[4,n.iterator()];case 1:return[2,r.sent().columnMajorBatch(e,t,deepBatchConcat)]}})})})},e.prototype.concatenate=function(e){var t=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){var t,n;return __generator$3(this,function(a){switch(a.label){case 0:return[4,r.iterator()];case 1:return n=(t=a.sent()).concatenate,[4,e.iterator()];case 2:return[2,n.apply(t,[a.sent()])]}})})})},e.prototype.repeat=function(e){var t=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){var t=this;return __generator$3(this,function(n){return[2,iteratorFromConcatenated(iteratorFromFunction(function(){return __awaiter$3(t,void 0,void 0,function(){var e;return __generator$3(this,function(t){switch(t.label){case 0:return e={},[4,r.iterator()];case 1:return[2,(e.value=t.sent(),e.done=!1,e)]}})})}).take(e))]})})})},e.prototype.take=function(e){var t=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){return __generator$3(this,function(t){switch(t.label){case 0:return[4,r.iterator()];case 1:return[2,t.sent().take(e)]}})})})},e.prototype.skip=function(e){var t=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){return __generator$3(this,function(t){switch(t.label){case 0:return[4,r.iterator()];case 1:return[2,t.sent().skip(e)]}})})})},e.prototype.shuffle=function(e,t,r){var n=this;void 0===r&&(r=!0);var a=this,o=seedrandom_1$1(t||util.now().toString());return datasetFromIteratorFn(function(){return __awaiter$3(n,void 0,void 0,function(){var t;return __generator$3(this,function(n){switch(n.label){case 0:return t=o.int32(),r&&(t+=o.int32()),[4,a.iterator()];case 1:return[2,n.sent().shuffle(e,t.toString())]}})})})},e.prototype.prefetch=function(e){var t=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){return __generator$3(this,function(t){switch(t.label){case 0:return[4,r.iterator()];case 1:return[2,t.sent().prefetch(e)]}})})})},e.prototype.collectAll=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){switch(e.label){case 0:return[4,this.iterator()];case 1:return[2,e.sent().collect()]}})})},e.prototype.forEach=function(e){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(t){switch(t.label){case 0:return[4,this.iterator()];case 1:return[2,t.sent().forEach(e)]}})})},e}();function datasetFromIteratorFn(e){return new(function(t){function r(){return null!==t&&t.apply(this,arguments)||this}return __extends$2(r,t),r.prototype.iterator=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(t){return[2,e()]})})},r}(Dataset))}function array(e){var t=this;return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){return __generator$3(this,function(t){return[2,iteratorFromItems(e)]})})})}function zip(e){var t=this;if(!isIterable$1(e))throw new Error("The argument to zip() must be an object or array.");return datasetFromIteratorFn(function(){return __awaiter$3(t,void 0,void 0,function(){return __generator$3(this,function(t){switch(t.label){case 0:return[4,deepMapAndAwaitAll(e,function(e){if(e instanceof Dataset)return{value:e.iterator(),recurse:!1};if(isIterable$1(e))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})];case 1:return[2,iteratorFromZipped(t.sent(),ZipMismatchMode.SHORTEST)]}})})})}function deepBatchConcat(e){if(null===e)return null;var t=e[0];return"string"==typeof t?{value:e,recurse:!1}:isIterable$1(t)?isNumericArray(t)?{value:batchConcat(e),recurse:!1}:{value:null,recurse:!0}:{value:batchConcat(e),recurse:!1}}function batchConcat(e){for(var t=shapeAndValues(e[0])[0],r=[e.length].concat(t),n=new Float32Array(r.reduce(function(e,t){return e*t})),a=0,o=0,i=e;o1}),util.assert(0===r.length,"Duplicate column names found: "+r.toString()),this.columnConfigs)for(n=0,a=Object.keys(this.columnConfigs);n=55296&&t<=56319&&a=55296&&e<=57343)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value")}function d(e,t){return l(e>>t&63|128)}function h(e){if(0==(4294967168&e))return l(e);var t="";return 0==(4294965248&e)?t=l(e>>6&31|192):0==(4294901760&e)?(c(e),t=l(e>>12&15|224),t+=d(e,6)):0==(4292870144&e)&&(t=l(e>>18&7|240),t+=d(e,12),t+=d(e,6)),t+l(63&e|128)}function f(){if(u>=s)throw Error("Invalid byte index");var e=255&i[u];if(u++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function m(){var e,t;if(u>s)throw Error("Invalid byte index");if(u==s)return!1;if(e=255&i[u],u++,0==(128&e))return e;if(192==(224&e)){if((t=(31&e)<<6|f())>=128)return t;throw Error("Invalid continuation byte")}if(224==(240&e)){if((t=(15&e)<<12|f()<<6|f())>=2048)return c(t),t;throw Error("Invalid continuation byte")}if(240==(248&e)&&(t=(7&e)<<18|f()<<12|f()<<6|f())>=65536&&t<=1114111)return t;throw Error("Invalid UTF-8 detected")}var g={version:"2.1.2",encode:function(e){for(var t=p(e),r=t.length,n=-1,a="";++n65535&&(a+=l((t-=65536)>>>10&1023|55296),t=56320|1023&t),a+=l(t);return a}(r)}};if(n&&!n.nodeType)if(a)a.exports=g;else{var y={}.hasOwnProperty;for(var v in g)y.call(g,v)&&(n[v]=g[v])}else r.utf8=g}(commonjsGlobal$2)}),utf8_1$1=utf8$2.decode,StringIterator=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends$2(t,e),t.prototype.split=function(e){return new SplitIterator(this,e)},t}(LazyIterator),SplitIterator=function(e){function t(t,r){var n=e.call(this)||this;return n.upstream=t,n.impl=new SplitIteratorImpl(t,r),n}return __extends$2(t,e),t.prototype.summary=function(){return this.impl.summary()},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){return[2,this.impl.next()]})})},t}(StringIterator),SplitIteratorImpl=function(e){function t(t,r){var n=e.call(this)||this;return n.upstream=t,n.separator=r,n.carryover="",n}return __extends$2(t,e),t.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},t.prototype.pump=function(){return __awaiter$3(this,void 0,void 0,function(){var e,t,r,n,a;return __generator$3(this,function(o){switch(o.label){case 0:return[4,this.upstream.next()];case 1:if((e=o.sent()).done)return""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((t=e.value.split(this.separator))[0]=this.carryover+t[0],r=0,n=t.slice(0,-1);r Utf8"},t.prototype.pump=function(){return __awaiter$3(this,void 0,void 0,function(){var e,t,r,n,a,o,i,s;return __generator$3(this,function(u){switch(u.label){case 0:return[4,this.upstream.next()];case 1:if((e=u.sent()).done){if(0===this.partial.length)return[2,!1];t=new Uint8Array([])}else t=e.value;for(r=this.partial.length-this.partialBytesValid,a=n=r,o=0;n0?(this.partial.set(t.slice(0,r),this.partialBytesValid),s=utf8_1$1(String.fromCharCode.apply(null,this.partial)),this.outputQueue.push(s+i)):this.outputQueue.push(i),a===t.length?(this.partial=new Uint8Array([]),this.partialBytesValid=0):(this.partial=new Uint8Array(new ArrayBuffer(o)),this.partial.set(t.slice(a),0),this.partialBytesValid=t.length-a),[2,!0]}})})},t}(OneToManyIterator);function utfWidth(e){return e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1}var FileChunkIterator=function(e){function t(t,r){void 0===r&&(r={});var n=e.call(this)||this;return n.file=t,n.options=r,util.assert(t instanceof Uint8Array||!!ENV.get("IS_BROWSER")&&(t instanceof File||t instanceof Blob),"FileChunkIterator only supports File, Blob and Uint8Array right now."),n.offset=r.offset||0,n.chunkSize=r.chunkSize||1048576,n}return __extends$2(t,e),t.prototype.summary=function(){return"FileChunks "+this.file},t.prototype.next=function(){return __awaiter$3(this,void 0,void 0,function(){var e,t,r=this;return __generator$3(this,function(n){switch(n.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(e=new Promise(function(e,t){var n=r.offset+r.chunkSize;if(r.file instanceof Uint8Array)e(new Uint8Array(r.file.slice(r.offset,n)));else{var a=new FileReader;a.onload=function(r){var n=a.result;if(n instanceof ArrayBuffer&&(n=new Uint8Array(n)),!(n instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(n)},a.onabort=function(e){return t(new Error("Aborted"))},a.onerror=function(e){return t(new Error(e.type))};var o=r.file.slice(r.offset,n);a.readAsArrayBuffer(o)}r.offset=n}),t={},[4,e]);case 1:return[2,(t.value=n.sent(),t.done=!1,t)]}})})},t}(ByteChunkIterator);function urlChunkIterator(e,t){return void 0===t&&(t={}),__awaiter$3(this,void 0,void 0,function(){var r,n,a,o;return __generator$3(this,function(i){switch(i.label){case 0:return ENV.get("IS_BROWSER")?[4,fetch(e)]:[3,5];case 1:return(r=i.sent()).ok?[4,r.blob()]:[3,3];case 2:return n=i.sent(),[2,new FileChunkIterator(n,t)];case 3:throw new Error(r.statusText);case 4:return[3,9];case 5:if(a=require("node-fetch"),"string"!=typeof e)throw new Error("URL must be a string. Request objects are not supported in the node.js environment yet.");return[4,a(e)];case 6:return(r=i.sent()).ok?[4,r.buffer()]:[3,8];case 7:return o=i.sent(),[2,new FileChunkIterator(o,t)];case 8:throw new Error(r.statusText);case 9:return[2]}})})}var URLDataSource=function(e){function t(t,r){void 0===r&&(r={});var n=e.call(this)||this;return n.url=t,n.fileOptions=r,n}return __extends$2(t,e),t.prototype.iterator=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){return[2,urlChunkIterator(this.url,this.fileOptions)]})})},t}(DataSource);function csv(e,t){return void 0===t&&(t={}),new CSVDataset(new URLDataSource(e),t)}var FileDataSource=function(e){function t(t,r){void 0===r&&(r={});var n=e.call(this)||this;return n.input=t,n.options=r,n}return __extends$2(t,e),t.prototype.iterator=function(){return __awaiter$3(this,void 0,void 0,function(){return __generator$3(this,function(e){return[2,new FileChunkIterator(this.input,this.options)]})})},t}(DataSource),version$3="0.1.4",tfData_esm=Object.freeze({array:array,Dataset:Dataset,datasetFromIteratorFn:datasetFromIteratorFn,zip:zip,CSVDataset:CSVDataset,TextLineDataset:TextLineDataset,csv:csv,FileDataSource:FileDataSource,URLDataSource:URLDataSource,version_data:version$3}),version$4="0.14.1",version$5={"tfjs-core":version,"tfjs-data":version$3,"tfjs-layers":version$1,"tfjs-converter":version$2,tfjs:version$4};exports.data=tfData_esm,exports.version=version$5,exports.setBackend=setBackend,exports.getBackend=getBackend,exports.disposeVariables=disposeVariables,exports.memory=memory,exports.version_core=version,exports.nextFrame=nextFrame,exports.environment=environment,exports.io=io,exports.math=math,exports.serialization=serialization,exports.test_util=test_util,exports.util=util,exports.webgl=webgl,exports.AdadeltaOptimizer=AdadeltaOptimizer,exports.AdagradOptimizer=AdagradOptimizer,exports.AdamOptimizer=AdamOptimizer,exports.AdamaxOptimizer=AdamaxOptimizer,exports.MomentumOptimizer=MomentumOptimizer,exports.Optimizer=Optimizer,exports.RMSPropOptimizer=RMSPropOptimizer,exports.SGDOptimizer=SGDOptimizer,exports.Tensor=Tensor,exports.TensorBuffer=TensorBuffer,exports.variable=variable,exports.Variable=Variable,exports.ENV=ENV,exports.Environment=Environment,exports.KernelBackend=KernelBackend,exports.DataStorage=DataStorage,exports.image=image_ops,exports.linalg=linalg_ops,exports.losses=loss_ops,exports.spectral=spectral_ops,exports.op=op,exports.batchNormalization2d=batchNormalization2d,exports.batchNormalization3d=batchNormalization3d,exports.batchNormalization4d=batchNormalization4d,exports.batchNormalization=batchNormalization,exports.complex=complex,exports.real=real,exports.imag=imag,exports.concat=concat,exports.concat1d=concat1d,exports.concat2d=concat2d,exports.concat3d=concat3d,exports.concat4d=concat4d,exports.split=split$1,exports.conv1d=conv1d,exports.conv2d=conv2d,exports.conv3d=conv3d,exports.conv2dDerFilter=conv2dDerFilter,exports.depthwiseConv2d=depthwiseConv2d,exports.separableConv2d=separableConv2d,exports.conv2dTranspose=conv2dTranspose,exports.matMul=matMul,exports.dot=dot,exports.outerProduct=outerProduct,exports.reverse=reverse,exports.reverse1d=reverse1d,exports.reverse2d=reverse2d,exports.reverse3d=reverse3d,exports.reverse4d=reverse4d,exports.maxPool=maxPool,exports.avgPool=avgPool,exports.pool=pool,exports.slice=slice,exports.slice1d=slice1d,exports.slice2d=slice2d,exports.slice3d=slice3d,exports.slice4d=slice4d,exports.abs=abs,exports.acos=acos,exports.acosh=acosh,exports.asin=asin,exports.asinh=asinh,exports.atan=atan,exports.atanh=atanh,exports.ceil=ceil,exports.clipByValue=clipByValue,exports.cos=cos,exports.cosh=cosh,exports.erf=erf,exports.exp=exp,exports.expm1=expm1,exports.floor=floor,exports.log=log$1,exports.log1p=log1p,exports.logSigmoid=logSigmoid,exports.neg=neg,exports.reciprocal=reciprocal,exports.round=round,exports.rsqrt=rsqrt,exports.sigmoid=sigmoid,exports.sign=sign,exports.sin=sin,exports.sinh=sinh,exports.softplus=softplus,exports.sqrt=sqrt,exports.square=square,exports.step=step,exports.tan=tan,exports.tanh=tanh$1,exports.all=all,exports.any=any,exports.argMax=argMax,exports.argMin=argMin,exports.logSumExp=logSumExp,exports.max=max,exports.mean=mean,exports.min=min,exports.moments=moments,exports.sum=sum$1,exports.prod=prod,exports.equal=equal,exports.equalStrict=equalStrict,exports.greater=greater,exports.greaterEqual=greaterEqual,exports.greaterEqualStrict=greaterEqualStrict,exports.greaterStrict=greaterStrict,exports.less=less,exports.lessEqual=lessEqual,exports.lessEqualStrict=lessEqualStrict,exports.lessStrict=lessStrict,exports.notEqual=notEqual,exports.notEqualStrict=notEqualStrict,exports.add=add,exports.addN=addN,exports.addStrict=addStrict,exports.atan2=atan2,exports.div=div,exports.divStrict=divStrict,exports.floorDiv=floorDiv,exports.maximum=maximum,exports.maximumStrict=maximumStrict,exports.minimum=minimum,exports.minimumStrict=minimumStrict,exports.mod=mod,exports.modStrict=modStrict,exports.mul=mul,exports.mulStrict=mulStrict,exports.pow=pow,exports.powStrict=powStrict,exports.squaredDifference=squaredDifference,exports.squaredDifferenceStrict=squaredDifferenceStrict,exports.sub=sub,exports.subStrict=subStrict,exports.elu=elu,exports.leakyRelu=leakyRelu,exports.prelu=prelu,exports.relu=relu,exports.selu=selu,exports.logicalAnd=logicalAnd,exports.logicalNot=logicalNot,exports.logicalOr=logicalOr,exports.logicalXor=logicalXor,exports.where=where,exports.whereAsync=whereAsync,exports.buffer=buffer,exports.toPixels=toPixels,exports.print=print,exports.batchToSpaceND=batchToSpaceND,exports.cast=cast,exports.clone=clone,exports.cumsum=cumsum,exports.depthToSpace=depthToSpace,exports.expandDims=expandDims,exports.eye=eye,exports.fromPixels=fromPixels,exports.multinomial=multinomial,exports.oneHot=oneHot,exports.pad=pad,exports.pad1d=pad1d,exports.pad2d=pad2d,exports.pad3d=pad3d,exports.pad4d=pad4d,exports.rand=rand,exports.randomNormal=randomNormal,exports.randomUniform=randomUniform,exports.reshape=reshape,exports.spaceToBatchND=spaceToBatchND,exports.squeeze=squeeze,exports.stack=stack,exports.tile=tile,exports.truncatedNormal=truncatedNormal,exports.unstack=unstack,exports.setdiff1dAsync=setdiff1dAsync,exports.fill=fill,exports.linspace=linspace,exports.ones=ones$1,exports.range=range,exports.scalar=scalar,exports.tensor=tensor,exports.tensor1d=tensor1d,exports.tensor2d=tensor2d,exports.tensor3d=tensor3d,exports.tensor4d=tensor4d,exports.tensor5d=tensor5d,exports.tensor6d=tensor6d,exports.zeros=zeros,exports.onesLike=onesLike,exports.zerosLike=zerosLike,exports.transpose=transpose,exports.softmax=softmax,exports.logSoftmax=logSoftmax,exports.localResponseNormalization=localResponseNormalization,exports.norm=norm,exports.gather=gather,exports.unsortedSegmentSum=unsortedSegmentSum,exports.basicLSTMCell=basicLSTMCell,exports.multiRNNCell=multiRNNCell,exports.movingAverage=movingAverage,exports.stridedSlice=stridedSlice,exports.topk=topk,exports.scatterND=scatterND,exports.fft=fft,exports.ifft=ifft,exports.rfft=rfft,exports.irfft=irfft,exports.sparseToDense=sparseToDense,exports.gatherND=gatherND,exports.train=train,exports.tidy=tidy,exports.keep=keep,exports.dispose=dispose,exports.time=time,exports.profile=profile,exports.customGrad=customGrad,exports.grad=grad,exports.grads=grads,exports.valueAndGrad=valueAndGrad,exports.valueAndGrads=valueAndGrads,exports.variableGrads=variableGrads,exports.constraints=exports_constraints,exports.initializers=exports_initializers,exports.layers=exports_layers,exports.models=exports_models,exports.metrics=exports_metrics,exports.regularizers=exports_regularizers,exports.CallbackList=CallbackList,exports.CustomCallback=CustomCallback,exports.History=History,exports.Callback=Callback,exports.InputSpec=InputSpec,exports.SymbolicTensor=SymbolicTensor,exports.Model=Model,exports.input=input,exports.loadModel=loadModel,exports.model=model,exports.registerCallbackConstructor=registerCallbackConstructor,exports.sequential=sequential,exports.RNN=RNN,exports.Sequential=Sequential,exports.LayerVariable=LayerVariable,exports.version_layers=version$1,exports.FrozenModel=FrozenModel,exports.loadFrozenModel=loadFrozenModel,exports.loadTfHubModule=loadTfHubModule,exports.version_converter=version$2,Object.defineProperty(exports,"__esModule",{value:!0})}); -//# sourceMappingURL=tf.min.js.map diff --git a/lib/engine/maia/lc0_policy_index.json b/lib/engine/maia/lc0_policy_index.json new file mode 100644 index 00000000..2a47dfb5 --- /dev/null +++ b/lib/engine/maia/lc0_policy_index.json @@ -0,0 +1 @@ +["a1b1","a1c1","a1d1","a1e1","a1f1","a1g1","a1h1","a1a2","a1b2","a1c2","a1a3","a1b3","a1c3","a1a4","a1d4","a1a5","a1e5","a1a6","a1f6","a1a7","a1g7","a1a8","a1h8","b1a1","b1c1","b1d1","b1e1","b1f1","b1g1","b1h1","b1a2","b1b2","b1c2","b1d2","b1a3","b1b3","b1c3","b1d3","b1b4","b1e4","b1b5","b1f5","b1b6","b1g6","b1b7","b1h7","b1b8","c1a1","c1b1","c1d1","c1e1","c1f1","c1g1","c1h1","c1a2","c1b2","c1c2","c1d2","c1e2","c1a3","c1b3","c1c3","c1d3","c1e3","c1c4","c1f4","c1c5","c1g5","c1c6","c1h6","c1c7","c1c8","d1a1","d1b1","d1c1","d1e1","d1f1","d1g1","d1h1","d1b2","d1c2","d1d2","d1e2","d1f2","d1b3","d1c3","d1d3","d1e3","d1f3","d1a4","d1d4","d1g4","d1d5","d1h5","d1d6","d1d7","d1d8","e1a1","e1b1","e1c1","e1d1","e1f1","e1g1","e1h1","e1c2","e1d2","e1e2","e1f2","e1g2","e1c3","e1d3","e1e3","e1f3","e1g3","e1b4","e1e4","e1h4","e1a5","e1e5","e1e6","e1e7","e1e8","f1a1","f1b1","f1c1","f1d1","f1e1","f1g1","f1h1","f1d2","f1e2","f1f2","f1g2","f1h2","f1d3","f1e3","f1f3","f1g3","f1h3","f1c4","f1f4","f1b5","f1f5","f1a6","f1f6","f1f7","f1f8","g1a1","g1b1","g1c1","g1d1","g1e1","g1f1","g1h1","g1e2","g1f2","g1g2","g1h2","g1e3","g1f3","g1g3","g1h3","g1d4","g1g4","g1c5","g1g5","g1b6","g1g6","g1a7","g1g7","g1g8","h1a1","h1b1","h1c1","h1d1","h1e1","h1f1","h1g1","h1f2","h1g2","h1h2","h1f3","h1g3","h1h3","h1e4","h1h4","h1d5","h1h5","h1c6","h1h6","h1b7","h1h7","h1a8","h1h8","a2a1","a2b1","a2c1","a2b2","a2c2","a2d2","a2e2","a2f2","a2g2","a2h2","a2a3","a2b3","a2c3","a2a4","a2b4","a2c4","a2a5","a2d5","a2a6","a2e6","a2a7","a2f7","a2a8","a2g8","b2a1","b2b1","b2c1","b2d1","b2a2","b2c2","b2d2","b2e2","b2f2","b2g2","b2h2","b2a3","b2b3","b2c3","b2d3","b2a4","b2b4","b2c4","b2d4","b2b5","b2e5","b2b6","b2f6","b2b7","b2g7","b2b8","b2h8","c2a1","c2b1","c2c1","c2d1","c2e1","c2a2","c2b2","c2d2","c2e2","c2f2","c2g2","c2h2","c2a3","c2b3","c2c3","c2d3","c2e3","c2a4","c2b4","c2c4","c2d4","c2e4","c2c5","c2f5","c2c6","c2g6","c2c7","c2h7","c2c8","d2b1","d2c1","d2d1","d2e1","d2f1","d2a2","d2b2","d2c2","d2e2","d2f2","d2g2","d2h2","d2b3","d2c3","d2d3","d2e3","d2f3","d2b4","d2c4","d2d4","d2e4","d2f4","d2a5","d2d5","d2g5","d2d6","d2h6","d2d7","d2d8","e2c1","e2d1","e2e1","e2f1","e2g1","e2a2","e2b2","e2c2","e2d2","e2f2","e2g2","e2h2","e2c3","e2d3","e2e3","e2f3","e2g3","e2c4","e2d4","e2e4","e2f4","e2g4","e2b5","e2e5","e2h5","e2a6","e2e6","e2e7","e2e8","f2d1","f2e1","f2f1","f2g1","f2h1","f2a2","f2b2","f2c2","f2d2","f2e2","f2g2","f2h2","f2d3","f2e3","f2f3","f2g3","f2h3","f2d4","f2e4","f2f4","f2g4","f2h4","f2c5","f2f5","f2b6","f2f6","f2a7","f2f7","f2f8","g2e1","g2f1","g2g1","g2h1","g2a2","g2b2","g2c2","g2d2","g2e2","g2f2","g2h2","g2e3","g2f3","g2g3","g2h3","g2e4","g2f4","g2g4","g2h4","g2d5","g2g5","g2c6","g2g6","g2b7","g2g7","g2a8","g2g8","h2f1","h2g1","h2h1","h2a2","h2b2","h2c2","h2d2","h2e2","h2f2","h2g2","h2f3","h2g3","h2h3","h2f4","h2g4","h2h4","h2e5","h2h5","h2d6","h2h6","h2c7","h2h7","h2b8","h2h8","a3a1","a3b1","a3c1","a3a2","a3b2","a3c2","a3b3","a3c3","a3d3","a3e3","a3f3","a3g3","a3h3","a3a4","a3b4","a3c4","a3a5","a3b5","a3c5","a3a6","a3d6","a3a7","a3e7","a3a8","a3f8","b3a1","b3b1","b3c1","b3d1","b3a2","b3b2","b3c2","b3d2","b3a3","b3c3","b3d3","b3e3","b3f3","b3g3","b3h3","b3a4","b3b4","b3c4","b3d4","b3a5","b3b5","b3c5","b3d5","b3b6","b3e6","b3b7","b3f7","b3b8","b3g8","c3a1","c3b1","c3c1","c3d1","c3e1","c3a2","c3b2","c3c2","c3d2","c3e2","c3a3","c3b3","c3d3","c3e3","c3f3","c3g3","c3h3","c3a4","c3b4","c3c4","c3d4","c3e4","c3a5","c3b5","c3c5","c3d5","c3e5","c3c6","c3f6","c3c7","c3g7","c3c8","c3h8","d3b1","d3c1","d3d1","d3e1","d3f1","d3b2","d3c2","d3d2","d3e2","d3f2","d3a3","d3b3","d3c3","d3e3","d3f3","d3g3","d3h3","d3b4","d3c4","d3d4","d3e4","d3f4","d3b5","d3c5","d3d5","d3e5","d3f5","d3a6","d3d6","d3g6","d3d7","d3h7","d3d8","e3c1","e3d1","e3e1","e3f1","e3g1","e3c2","e3d2","e3e2","e3f2","e3g2","e3a3","e3b3","e3c3","e3d3","e3f3","e3g3","e3h3","e3c4","e3d4","e3e4","e3f4","e3g4","e3c5","e3d5","e3e5","e3f5","e3g5","e3b6","e3e6","e3h6","e3a7","e3e7","e3e8","f3d1","f3e1","f3f1","f3g1","f3h1","f3d2","f3e2","f3f2","f3g2","f3h2","f3a3","f3b3","f3c3","f3d3","f3e3","f3g3","f3h3","f3d4","f3e4","f3f4","f3g4","f3h4","f3d5","f3e5","f3f5","f3g5","f3h5","f3c6","f3f6","f3b7","f3f7","f3a8","f3f8","g3e1","g3f1","g3g1","g3h1","g3e2","g3f2","g3g2","g3h2","g3a3","g3b3","g3c3","g3d3","g3e3","g3f3","g3h3","g3e4","g3f4","g3g4","g3h4","g3e5","g3f5","g3g5","g3h5","g3d6","g3g6","g3c7","g3g7","g3b8","g3g8","h3f1","h3g1","h3h1","h3f2","h3g2","h3h2","h3a3","h3b3","h3c3","h3d3","h3e3","h3f3","h3g3","h3f4","h3g4","h3h4","h3f5","h3g5","h3h5","h3e6","h3h6","h3d7","h3h7","h3c8","h3h8","a4a1","a4d1","a4a2","a4b2","a4c2","a4a3","a4b3","a4c3","a4b4","a4c4","a4d4","a4e4","a4f4","a4g4","a4h4","a4a5","a4b5","a4c5","a4a6","a4b6","a4c6","a4a7","a4d7","a4a8","a4e8","b4b1","b4e1","b4a2","b4b2","b4c2","b4d2","b4a3","b4b3","b4c3","b4d3","b4a4","b4c4","b4d4","b4e4","b4f4","b4g4","b4h4","b4a5","b4b5","b4c5","b4d5","b4a6","b4b6","b4c6","b4d6","b4b7","b4e7","b4b8","b4f8","c4c1","c4f1","c4a2","c4b2","c4c2","c4d2","c4e2","c4a3","c4b3","c4c3","c4d3","c4e3","c4a4","c4b4","c4d4","c4e4","c4f4","c4g4","c4h4","c4a5","c4b5","c4c5","c4d5","c4e5","c4a6","c4b6","c4c6","c4d6","c4e6","c4c7","c4f7","c4c8","c4g8","d4a1","d4d1","d4g1","d4b2","d4c2","d4d2","d4e2","d4f2","d4b3","d4c3","d4d3","d4e3","d4f3","d4a4","d4b4","d4c4","d4e4","d4f4","d4g4","d4h4","d4b5","d4c5","d4d5","d4e5","d4f5","d4b6","d4c6","d4d6","d4e6","d4f6","d4a7","d4d7","d4g7","d4d8","d4h8","e4b1","e4e1","e4h1","e4c2","e4d2","e4e2","e4f2","e4g2","e4c3","e4d3","e4e3","e4f3","e4g3","e4a4","e4b4","e4c4","e4d4","e4f4","e4g4","e4h4","e4c5","e4d5","e4e5","e4f5","e4g5","e4c6","e4d6","e4e6","e4f6","e4g6","e4b7","e4e7","e4h7","e4a8","e4e8","f4c1","f4f1","f4d2","f4e2","f4f2","f4g2","f4h2","f4d3","f4e3","f4f3","f4g3","f4h3","f4a4","f4b4","f4c4","f4d4","f4e4","f4g4","f4h4","f4d5","f4e5","f4f5","f4g5","f4h5","f4d6","f4e6","f4f6","f4g6","f4h6","f4c7","f4f7","f4b8","f4f8","g4d1","g4g1","g4e2","g4f2","g4g2","g4h2","g4e3","g4f3","g4g3","g4h3","g4a4","g4b4","g4c4","g4d4","g4e4","g4f4","g4h4","g4e5","g4f5","g4g5","g4h5","g4e6","g4f6","g4g6","g4h6","g4d7","g4g7","g4c8","g4g8","h4e1","h4h1","h4f2","h4g2","h4h2","h4f3","h4g3","h4h3","h4a4","h4b4","h4c4","h4d4","h4e4","h4f4","h4g4","h4f5","h4g5","h4h5","h4f6","h4g6","h4h6","h4e7","h4h7","h4d8","h4h8","a5a1","a5e1","a5a2","a5d2","a5a3","a5b3","a5c3","a5a4","a5b4","a5c4","a5b5","a5c5","a5d5","a5e5","a5f5","a5g5","a5h5","a5a6","a5b6","a5c6","a5a7","a5b7","a5c7","a5a8","a5d8","b5b1","b5f1","b5b2","b5e2","b5a3","b5b3","b5c3","b5d3","b5a4","b5b4","b5c4","b5d4","b5a5","b5c5","b5d5","b5e5","b5f5","b5g5","b5h5","b5a6","b5b6","b5c6","b5d6","b5a7","b5b7","b5c7","b5d7","b5b8","b5e8","c5c1","c5g1","c5c2","c5f2","c5a3","c5b3","c5c3","c5d3","c5e3","c5a4","c5b4","c5c4","c5d4","c5e4","c5a5","c5b5","c5d5","c5e5","c5f5","c5g5","c5h5","c5a6","c5b6","c5c6","c5d6","c5e6","c5a7","c5b7","c5c7","c5d7","c5e7","c5c8","c5f8","d5d1","d5h1","d5a2","d5d2","d5g2","d5b3","d5c3","d5d3","d5e3","d5f3","d5b4","d5c4","d5d4","d5e4","d5f4","d5a5","d5b5","d5c5","d5e5","d5f5","d5g5","d5h5","d5b6","d5c6","d5d6","d5e6","d5f6","d5b7","d5c7","d5d7","d5e7","d5f7","d5a8","d5d8","d5g8","e5a1","e5e1","e5b2","e5e2","e5h2","e5c3","e5d3","e5e3","e5f3","e5g3","e5c4","e5d4","e5e4","e5f4","e5g4","e5a5","e5b5","e5c5","e5d5","e5f5","e5g5","e5h5","e5c6","e5d6","e5e6","e5f6","e5g6","e5c7","e5d7","e5e7","e5f7","e5g7","e5b8","e5e8","e5h8","f5b1","f5f1","f5c2","f5f2","f5d3","f5e3","f5f3","f5g3","f5h3","f5d4","f5e4","f5f4","f5g4","f5h4","f5a5","f5b5","f5c5","f5d5","f5e5","f5g5","f5h5","f5d6","f5e6","f5f6","f5g6","f5h6","f5d7","f5e7","f5f7","f5g7","f5h7","f5c8","f5f8","g5c1","g5g1","g5d2","g5g2","g5e3","g5f3","g5g3","g5h3","g5e4","g5f4","g5g4","g5h4","g5a5","g5b5","g5c5","g5d5","g5e5","g5f5","g5h5","g5e6","g5f6","g5g6","g5h6","g5e7","g5f7","g5g7","g5h7","g5d8","g5g8","h5d1","h5h1","h5e2","h5h2","h5f3","h5g3","h5h3","h5f4","h5g4","h5h4","h5a5","h5b5","h5c5","h5d5","h5e5","h5f5","h5g5","h5f6","h5g6","h5h6","h5f7","h5g7","h5h7","h5e8","h5h8","a6a1","a6f1","a6a2","a6e2","a6a3","a6d3","a6a4","a6b4","a6c4","a6a5","a6b5","a6c5","a6b6","a6c6","a6d6","a6e6","a6f6","a6g6","a6h6","a6a7","a6b7","a6c7","a6a8","a6b8","a6c8","b6b1","b6g1","b6b2","b6f2","b6b3","b6e3","b6a4","b6b4","b6c4","b6d4","b6a5","b6b5","b6c5","b6d5","b6a6","b6c6","b6d6","b6e6","b6f6","b6g6","b6h6","b6a7","b6b7","b6c7","b6d7","b6a8","b6b8","b6c8","b6d8","c6c1","c6h1","c6c2","c6g2","c6c3","c6f3","c6a4","c6b4","c6c4","c6d4","c6e4","c6a5","c6b5","c6c5","c6d5","c6e5","c6a6","c6b6","c6d6","c6e6","c6f6","c6g6","c6h6","c6a7","c6b7","c6c7","c6d7","c6e7","c6a8","c6b8","c6c8","c6d8","c6e8","d6d1","d6d2","d6h2","d6a3","d6d3","d6g3","d6b4","d6c4","d6d4","d6e4","d6f4","d6b5","d6c5","d6d5","d6e5","d6f5","d6a6","d6b6","d6c6","d6e6","d6f6","d6g6","d6h6","d6b7","d6c7","d6d7","d6e7","d6f7","d6b8","d6c8","d6d8","d6e8","d6f8","e6e1","e6a2","e6e2","e6b3","e6e3","e6h3","e6c4","e6d4","e6e4","e6f4","e6g4","e6c5","e6d5","e6e5","e6f5","e6g5","e6a6","e6b6","e6c6","e6d6","e6f6","e6g6","e6h6","e6c7","e6d7","e6e7","e6f7","e6g7","e6c8","e6d8","e6e8","e6f8","e6g8","f6a1","f6f1","f6b2","f6f2","f6c3","f6f3","f6d4","f6e4","f6f4","f6g4","f6h4","f6d5","f6e5","f6f5","f6g5","f6h5","f6a6","f6b6","f6c6","f6d6","f6e6","f6g6","f6h6","f6d7","f6e7","f6f7","f6g7","f6h7","f6d8","f6e8","f6f8","f6g8","f6h8","g6b1","g6g1","g6c2","g6g2","g6d3","g6g3","g6e4","g6f4","g6g4","g6h4","g6e5","g6f5","g6g5","g6h5","g6a6","g6b6","g6c6","g6d6","g6e6","g6f6","g6h6","g6e7","g6f7","g6g7","g6h7","g6e8","g6f8","g6g8","g6h8","h6c1","h6h1","h6d2","h6h2","h6e3","h6h3","h6f4","h6g4","h6h4","h6f5","h6g5","h6h5","h6a6","h6b6","h6c6","h6d6","h6e6","h6f6","h6g6","h6f7","h6g7","h6h7","h6f8","h6g8","h6h8","a7a1","a7g1","a7a2","a7f2","a7a3","a7e3","a7a4","a7d4","a7a5","a7b5","a7c5","a7a6","a7b6","a7c6","a7b7","a7c7","a7d7","a7e7","a7f7","a7g7","a7h7","a7a8","a7b8","a7c8","b7b1","b7h1","b7b2","b7g2","b7b3","b7f3","b7b4","b7e4","b7a5","b7b5","b7c5","b7d5","b7a6","b7b6","b7c6","b7d6","b7a7","b7c7","b7d7","b7e7","b7f7","b7g7","b7h7","b7a8","b7b8n","b7c8","b7d8","c7c1","c7c2","c7h2","c7c3","c7g3","c7c4","c7f4","c7a5","c7b5","c7c5","c7d5","c7e5","c7a6","c7b6","c7c6","c7d6","c7e6","c7a7","c7b7","c7d7","c7e7","c7f7","c7g7","c7h7","c7a8","c7b8","c7c8","c7d8","c7e8","d7d1","d7d2","d7d3","d7h3","d7a4","d7d4","d7g4","d7b5","d7c5","d7d5","d7e5","d7f5","d7b6","d7c6","d7d6","d7e6","d7f6","d7a7","d7b7","d7c7","d7e7","d7f7","d7g7","d7h7","d7b8","d7c8","d7d8","d7e8","d7f8","e7e1","e7e2","e7a3","e7e3","e7b4","e7e4","e7h4","e7c5","e7d5","e7e5","e7f5","e7g5","e7c6","e7d6","e7e6","e7f6","e7g6","e7a7","e7b7","e7c7","e7d7","e7f7","e7g7","e7h7","e7c8","e7d8","e7e8","e7f8","e7g8","f7f1","f7a2","f7f2","f7b3","f7f3","f7c4","f7f4","f7d5","f7e5","f7f5","f7g5","f7h5","f7d6","f7e6","f7f6","f7g6","f7h6","f7a7","f7b7","f7c7","f7d7","f7e7","f7g7","f7h7","f7d8","f7e8","f7f8","f7g8","f7h8","g7a1","g7g1","g7b2","g7g2","g7c3","g7g3","g7d4","g7g4","g7e5","g7f5","g7g5","g7h5","g7e6","g7f6","g7g6","g7h6","g7a7","g7b7","g7c7","g7d7","g7e7","g7f7","g7h7","g7e8","g7f8","g7g8","g7h8","h7b1","h7h1","h7c2","h7h2","h7d3","h7h3","h7e4","h7h4","h7f5","h7g5","h7h5","h7f6","h7g6","h7h6","h7a7","h7b7","h7c7","h7d7","h7e7","h7f7","h7g7","h7f8","h7g8","h7h8","a8a1","a8h1","a8a2","a8g2","a8a3","a8f3","a8a4","a8e4","a8a5","a8d5","a8a6","a8b6","a8c6","a8a7","a8b7","a8c7","a8b8","a8c8","a8d8","a8e8","a8f8","a8g8","a8h8","b8b1","b8b2","b8h2","b8b3","b8g3","b8b4","b8f4","b8b5","b8e5","b8a6","b8b6","b8c6","b8d6","b8a7","b8b7","b8c7","b8d7","b8a8","b8c8","b8d8","b8e8","b8f8","b8g8","b8h8","c8c1","c8c2","c8c3","c8h3","c8c4","c8g4","c8c5","c8f5","c8a6","c8b6","c8c6","c8d6","c8e6","c8a7","c8b7","c8c7","c8d7","c8e7","c8a8","c8b8","c8d8","c8e8","c8f8","c8g8","c8h8","d8d1","d8d2","d8d3","d8d4","d8h4","d8a5","d8d5","d8g5","d8b6","d8c6","d8d6","d8e6","d8f6","d8b7","d8c7","d8d7","d8e7","d8f7","d8a8","d8b8","d8c8","d8e8","d8f8","d8g8","d8h8","e8e1","e8e2","e8e3","e8a4","e8e4","e8b5","e8e5","e8h5","e8c6","e8d6","e8e6","e8f6","e8g6","e8c7","e8d7","e8e7","e8f7","e8g7","e8a8","e8b8","e8c8","e8d8","e8f8","e8g8","e8h8","f8f1","f8f2","f8a3","f8f3","f8b4","f8f4","f8c5","f8f5","f8d6","f8e6","f8f6","f8g6","f8h6","f8d7","f8e7","f8f7","f8g7","f8h7","f8a8","f8b8","f8c8","f8d8","f8e8","f8g8","f8h8","g8g1","g8a2","g8g2","g8b3","g8g3","g8c4","g8g4","g8d5","g8g5","g8e6","g8f6","g8g6","g8h6","g8e7","g8f7","g8g7","g8h7","g8a8","g8b8","g8c8","g8d8","g8e8","g8f8","g8h8","h8a1","h8h1","h8b2","h8h2","h8c3","h8h3","h8d4","h8h4","h8e5","h8h5","h8f6","h8g6","h8h6","h8f7","h8g7","h8h7","h8a8","h8b8","h8c8","h8d8","h8e8","h8f8","h8g8","a7a8q","a7a8r","a7a8b","a7b8q","a7b8r","a7b8b","b7a8q","b7a8r","b7a8b","b7b8q","b7b8r","b7b8b","b7c8q","b7c8r","b7c8b","c7b8q","c7b8r","c7b8b","c7c8q","c7c8r","c7c8b","c7d8q","c7d8r","c7d8b","d7c8q","d7c8r","d7c8b","d7d8q","d7d8r","d7d8b","d7e8q","d7e8r","d7e8b","e7d8q","e7d8r","e7d8b","e7e8q","e7e8r","e7e8b","e7f8q","e7f8r","e7f8b","f7e8q","f7e8r","f7e8b","f7f8q","f7f8r","f7f8b","f7g8q","f7g8r","f7g8b","g7f8q","g7f8r","g7f8b","g7g8q","g7g8r","g7g8b","g7h8q","g7h8r","g7h8b","h7g8q","h7g8r","h7g8b","h7h8q","h7h8r","h7h8b"] \ No newline at end of file diff --git a/lib/engine/maia/maia-1100.onnx b/lib/engine/maia/maia-1100.onnx new file mode 100644 index 00000000..c94ee7cd Binary files /dev/null and b/lib/engine/maia/maia-1100.onnx differ diff --git a/lib/engine/maia/maia-1200.onnx b/lib/engine/maia/maia-1200.onnx new file mode 100644 index 00000000..53f8eaec Binary files /dev/null and b/lib/engine/maia/maia-1200.onnx differ diff --git a/lib/engine/maia/maia-1300.onnx {"code":"deadline_exceeded","msg":"operation timed out"}